Sometimes I need to create a valid windows executable file from a Python script for the sake of running a test.
1 2 3 4 5 6
import struct a=["MZ",176,"PE",332,1,224,259,267,9,16,64,16,2,5,32,2,2,132]+*5+[".text",16,2,2,16,96,"3\xc0\xc3"] f="60sL112x4sHH12x3HB14xB12xHxB3xB10xH7xB3xB6xHxBxxBxxB4xBxxB6xB131x13sB3xB3xB14xB2xB48x512s" b=struct.pack(f,*a) file("test.exe","wb").write(b)
You can see how to create a really small windows executable at this site: http://www.phreedom.org/research/tinype/. I wondered how I could get some of those ideas into creating the smallest Python script that will generate an executable, and came up with this code. The generated exe itself is 1024 bytes, so a long way from the smallest possible 133-byte file, however it can be signed with signtool from the Microsoft SDK, which is one of my requirements. Most of the 1024 bytes are, of course zeros.
The generated PE file runs, does nothing and returns exit code '0'. The Python can be made slightly smaller if you don't care what the return code is (remove the text 3\xc0). It hasn't been tested on windows 2000, and the generated EXE may not run on that.