Python for Security

Python is the security industry’s lingua franca
Exploit development, automation scripts, web scraping, API interaction, data parsing, fuzzing, and tool building all use Python because it balances readability with power and has the richest security library ecosystem

Why Python Wins

  • Reads almost like pseudocode (easy to share)
  • Massive library ecosystem (requests, scapy, pwntools, impacket)
  • Cross-platform (Windows, Linux, macOS)
  • Great for both quick scripts and complex tools
  • Large security community (find examples for everything)

Essential Libraries

LibraryPurpose
requestsHTTP client (API interaction, web testing)
scapyPacket manipulation and crafting
pwntoolsExploit development framework
impacketWindows protocol implementation
socketLow-level network communication
socketRaw TCP/UDP (standard library)
argparseCLI argument handling
reRegular expressions
json/yamlConfig file parsing
sqlite3Database interaction
asyncioAsync operations
paramikoSSH client/server

Basic Security Script Template

#!/usr/bin/env python3
import argparse
import sys
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def setup_args():
    parser = argparse.ArgumentParser(description='Security Tool')
    parser.add_argument('-t', '--target', required=True, help='Target host')
    parser.add_argument('-p', '--port', type=int, default=80, help='Target port')
    parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
    return parser.parse_args()

def main():
    args = setup_args()
    logging.info(f"Targeting {args.target}:{args.port}")
    # Your logic here

if __name__ == '__main__':
    main()

Network Tools with Python

# TCP Port Scanner
import socket

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

# Usage
for port in [22, 80, 443, 8080]:
    if scan_port('192.168.1.1', port):
        print(f"Port {port}: OPEN")
# Web Request with requests
import requests

r = requests.get('https://api.target.com/endpoint', 
                 headers={'User-Agent': 'Mozilla/5.0'},
                 timeout=10)
print(f"Status: {r.status_code}")
print(f"Headers: {dict(r.headers)}")

Error Handling

try:
    response = requests.get(url, timeout=5)
    response.raise_for_status()
except requests.exceptions.Timeout:
    logging.error(f"Request to {url} timed out")
except requests.exceptions.ConnectionError:
    logging.error(f"Could not connect to {url}")
except requests.exceptions.HTTPError as e:
    logging.error(f"HTTP error: {e}")
except Exception as e:
    logging.error(f"Unexpected error: {e}")

Posted · Updated