Generating Python Executables with PyInstaller:

This tutorial will cover compiling a Python script into an executable file.  This allows your Python code to be more portable across different instances of Windows that might not have Python installed.  First we must download the necessary dependencies, which include python (version 2.7 in this example), and in the case of windows, cygwin (or some other variant, we are using PyWin).

Linux: sudo apt-get install python2.7 build-essential python-dev zlib1g-dev upx
Windows: (fully packaged installer file)

Install Pywin32, Setuptools, PyInstaller

After install:

Next we can run the following command to generate the python executable script: python –onefile <scriptName>

This will process the python script, pull the necessary import dependencies, and generate a new folder containing a <scriptName>.txt, a <scriptName>.spec, and a <scriptName>.exe. The <scriptName>.exe can now be used, and the .txt and .spec can be removed.

After building the executable:

The Python script has now been compiled into a Windows PE file and can be executed on Windows without using a Python interpreter.  This allows you to more easily move your code between instances of Windows without worrying about dependencies.

Sample Script:


import os

os.system("echo Hello World!")

Now we can take this and save it to a file and then covert it to an executable with the following command:

c:PathToPythonpython.exe --onefile

> helloWorld.exe
Hello World!

You can reverse this process which we covered in a previous blog post here.

Compiling a Python script to an executable can be very useful when running Windows privilege escalation exploits that are written in Python on a System you don’t have the ability to install and setup Python.

Practice taking a more advanced script, like the Reverse Shell covered in Tutorial 0x2 and compiling it to an executable.