Python Security Tools Collection
A curated collection of Python security tools organized by category with installation, usage examples, and practical workflows.
Network & Port Scanning
| Tool | Installation | Purpose |
|---|---|---|
| nmap (python-nmap) | pip install python-nmap | Port scanning and network discovery |
| Shodan | pip install shodan | Internet-connected device search |
| Scapy | pip install scapy | Packet crafting and network analysis |
| netaddr | pip install netaddr | Network address manipulation |
| paramiko | pip install paramiko | SSH protocol implementation |
| pysock5 | pip install pysocks | SOCKS protocol support |
Installation & Setup
Create Security Tools Environment
# Create virtual environment
python3 -m venv sec-tools
source sec-tools/bin/activate # On Windows: sec-tools\Scripts\activate
# Install core security libraries
pip install requests urllib3 certifi
pip install paramiko pycryptodome pycurl
pip install beautifulsoup4 lxml html5lib
Install Network Tools
# Install Scapy for packet manipulation
pip install scapy
# Install network utilities
pip install python-nmap netaddr dnspython
# Install Shodan (requires API key)
pip install shodan
Install Exploitation & Testing Tools
# Install exploitation framework
pip install pwntools
# Install vulnerability scanning
pip install vulners
# Install fuzzing framework
pip install atheris
Install Web Security Tools
# Install web scraping and analysis
pip install scrapy mechanize selenium
pip install SQLAlchemy sqlparse
# Install API testing
pip install requests httpx aiohttp
Standalone Tool Installation
# SQLmap (SQL injection testing)
git clone https://github.com/sqlmapproject/sqlmap.git
cd sqlmap
python sqlmap.py --version
# Nikto (web vulnerability scanner)
pip install nikto
# Metasploit Framework (requires Ruby)
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfconsole.erb | bash
Reconnaissance & OSINT Tools
Web Reconnaissance
# Install reconnaissance tools
pip install whois dnspython requests
Whois & DNS Lookup
import whois
import dns.resolver
# Perform WHOIS lookup
domain = "example.com"
w = whois.whois(domain)
print(w.registrar, w.creation_date, w.expiration_date)
# DNS enumeration
answers = dns.resolver.resolve(domain, 'A')
for rdata in answers:
print(rdata)
# Reverse DNS lookup
import socket
ip = "8.8.8.8"
print(socket.gethostbyaddr(ip)[0])
Shodan API Usage
from shodan import Shodan
api = Shodan('YOUR_API_KEY')
# Search for devices
results = api.search('apache 2.4.1')
print(f'Results found: {results["total"]}')
# Get host information
host = api.host('8.8.8.8')
print(host)
# Search by location
results = api.search('country:US port:22')
Vulnerability Scanning & Assessment
Port Scanning with Nmap
import nmap
# Create nmap scanner
nm = nmap.PortScanner()
# Scan host
nm.scan('192.168.1.0/24', arguments='-sV -p 1-1000')
# Parse results
for host in nm.all_hosts():
print(f'Host: {host} ({nm[host].state()})')
for port in nm[host]['tcp'].keys():
print(f' Port {port}: {nm[host]["tcp"][port]["state"]}')
Web Application Testing
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
# Basic web reconnaissance
url = "https://example.com"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# Extract links
for link in soup.find_all('a'):
print(urljoin(url, link.get('href')))
# Extract forms
for form in soup.find_all('form'):
print(f"Form action: {form.get('action')}")
for input_field in form.find_all('input'):
print(f" Input: {input_field.get('name')}")
SQL Injection Testing
# Using SQLmap
python sqlmap.py -u "http://target.com/page.php?id=1" --dbs
# With authentication
python sqlmap.py -u "http://target.com/page.php?id=1" --data="username=admin&password=test" --dbs
# Crawl and test
python sqlmap.py -u "http://target.com/" --crawl=2 --batch
XSS & CSRF Detection
from selenium import webdriver
from selenium.webdriver.common.by import By
# Automated XSS testing
driver = webdriver.Chrome()
driver.get("http://target.com/search")
# Find input forms
inputs = driver.find_elements(By.TAG_NAME, "input")
for input_elem in inputs:
# Test XSS payload
input_elem.send_keys('<script>alert("xss")</script>')
# Check if reflected in response
page_source = driver.page_source
if '<script>' in page_source:
print(f"XSS found in: {input_elem.get_attribute('name')}")
driver.quit()
Password & Cryptography Tools
Password Testing & Hashing
import hashlib
from Crypto.Hash import SHA256, PBKDF2
# Calculate hash
password = "password123"
sha256_hash = hashlib.sha256(password.encode()).hexdigest()
print(sha256_hash)
# PBKDF2 hash
from Crypto.Random import get_random_bytes
salt = get_random_bytes(16)
from Crypto.Protocol.KDF import PBKDF2
key = PBKDF2(password, salt, dkLen=32, count=100000)
# Offline password cracking
import hashlib
wordlist = ['admin', 'password', '123456']
target_hash = "5e884898da28047151d0e56f8dc62927"
for word in wordlist:
if hashlib.md5(word.encode()).hexdigest() == target_hash:
print(f"Password found: {word}")
SSH Key Management
import paramiko
# Generate SSH key pair
key = paramiko.RSAKey.generate(2048)
key.write_private_key_file('private_key')
# Load SSH key
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username='user', key_filename='private_key')
# Execute command
stdin, stdout, stderr = ssh.exec_command('whoami')
print(stdout.read().decode())
ssh.close()
SSL/TLS Certificate Analysis
import ssl
import socket
from datetime import datetime
# Check certificate
hostname = "example.com"
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
print(f"Subject: {cert['subject']}")
print(f"Issued by: {cert['issuer']}")
print(f"Version: {cert['version']}")
Packet Analysis & Network Protocols
Scapy Packet Crafting
from scapy.all import IP, TCP, send, sniff, ARP
# Create and send IP packet
packet = IP(dst="192.168.1.1")/TCP(dport=80)
send(packet)
# ARP scan
arp_request = ARP(pdst="192.168.1.0/24")
broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = srp(arp_request_broadcast, timeout=1, verbose=False)[0]
for element in answered_list:
print(f"IP: {element[1].psrc} MAC: {element[1].hwsrc}")
# Packet sniffing
def packet_callback(packet):
print(packet.show())
sniff(prn=packet_callback, count=10)
DNS Enumeration
import dns.resolver
import dns.axfr
# Zone transfer attempt (DNS enumeration)
try:
xfr = dns.axfr.zone_for_name('example.com', ['8.8.8.8'])
for name, node in xfr.items():
print(name)
except Exception as e:
print(f"Zone transfer failed: {e}")
# DNS brute force
common_subdomains = ['www', 'mail', 'ftp', 'localhost', 'webmail', 'smtp', 'pop', 'ns1']
for subdomain in common_subdomains:
try:
result = dns.resolver.resolve(f'{subdomain}.example.com', 'A')
print(f"{subdomain}.example.com: {result[0]}")
except:
pass
Protocol Analysis
# Capture traffic
sudo tcpdump -i eth0 -n -w capture.pcap
# Analyze with Scapy
from scapy.all import rdpcap
packets = rdpcap('capture.pcap')
for packet in packets:
print(packet.summary())
Exploit Development & Fuzzing
Buffer Overflow Exploitation
from pwn import *
# Connect to target
target = remote('localhost', 5005)
# Create payload
payload = b'A' * 100 + p32(0x080484d0) # Address to jump to
# Send exploit
target.send(payload)
target.interactive()
Fuzzing with AFL
# Install AFL
sudo apt-get install afl afl++
# Compile target with AFL instrumentation
afl-gcc vulnerable.c -o vulnerable
# Create test cases
mkdir testcases
echo "normal input" > testcases/input1
# Run fuzzer
afl-fuzz -i testcases -o findings ./vulnerable @@
Web Fuzzing
import requests
import itertools
# Fuzz directory enumeration
wordlist = ['admin', 'login', 'api', 'backup', 'config', 'upload']
for word in wordlist:
url = f"http://target.com/{word}"
try:
response = requests.get(url, timeout=2)
if response.status_code != 404:
print(f"Found: {url} ({response.status_code})")
except:
pass
# Parameter fuzzing
params_list = [
{'id': '1'},
{'id': '1"'},
{'id': '1 OR 1=1'},
{'id': "1'; DROP TABLE users; --"}
]
for params in params_list:
response = requests.get("http://target.com/page.php", params=params)
print(f"Params: {params}, Status: {response.status_code}")
Automation & Scripting Frameworks
Metasploit Framework Integration
import subprocess
import json
# Run Metasploit module
msf_cmd = [
'msfconsole', '-x',
'use exploit/windows/smb/ms17_010_eternalblue; ' +
'set RHOSTS 192.168.1.100; ' +
'exploit; exit'
]
result = subprocess.run(msf_cmd, capture_output=True, text=True)
print(result.stdout)
Multi-threaded Scanning
import concurrent.futures
import requests
def scan_port(host, port):
try:
response = requests.get(f'http://{host}:{port}', timeout=1)
return f'{host}:{port} - {response.status_code}'
except:
return f'{host}:{port} - Closed'
hosts = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
ports = [80, 443, 8080, 8443]
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = []
for host in hosts:
for port in ports:
futures.append(executor.submit(scan_port, host, port))
for future in concurrent.futures.as_completed(futures):
print(future.result())
Custom Scanner Framework
class SecurityScanner:
def __init__(self, target):
self.target = target
self.results = {}
def port_scan(self):
nm = nmap.PortScanner()
nm.scan(self.target, arguments='-sV')
self.results['ports'] = nm[self.target].all_tcp()
def web_scan(self):
response = requests.get(f'http://{self.target}')
self.results['web_status'] = response.status_code
def dns_scan(self):
try:
result = socket.gethostbyname(self.target)
self.results['dns'] = result
except:
self.results['dns'] = 'Failed'
def scan_all(self):
self.port_scan()
self.web_scan()
self.dns_scan()
return self.results
# Usage
scanner = SecurityScanner('example.com')
results = scanner.scan_all()
print(results)
Reporting & Documentation
Generate HTML Reports
from jinja2 import Template
html_template = """
<html>
<head><title>Security Assessment Report</title></head>
<body>
<h1>Penetration Test Report</h1>
<h2>Target: {{ target }}</h2>
<h2>Date: {{ date }}</h2>
<h3>Vulnerabilities Found: {{ vuln_count }}</h3>
<table border="1">
<tr><th>Severity</th><th>Vulnerability</th><th>CVE</th></tr>
{% for vuln in vulnerabilities %}
<tr>
<td>{{ vuln.severity }}</td>
<td>{{ vuln.name }}</td>
<td>{{ vuln.cve }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
"""
from datetime import datetime
data = {
'target': 'example.com',
'date': datetime.now().strftime('%Y-%m-%d'),
'vuln_count': 3,
'vulnerabilities': [
{'severity': 'High', 'name': 'SQL Injection', 'cve': 'CVE-2021-1234'},
{'severity': 'Medium', 'name': 'XSS', 'cve': 'CVE-2021-5678'},
{'severity': 'Low', 'name': 'Missing Headers', 'cve': 'N/A'}
]
}
template = Template(html_template)
html_output = template.render(data)
with open('report.html', 'w') as f:
f.write(html_output)
CSV Export Results
import csv
results = [
{'host': '192.168.1.1', 'port': 22, 'service': 'SSH', 'version': 'OpenSSH 7.4'},
{'host': '192.168.1.1', 'port': 80, 'service': 'HTTP', 'version': 'Apache 2.4'},
{'host': '192.168.1.2', 'port': 3306, 'service': 'MySQL', 'version': '5.7'}
]
with open('scan_results.csv', 'w', newline='') as csvfile:
fieldnames = ['host', 'port', 'service', 'version']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)
JSON Report Generation
import json
report = {
'scan_info': {
'target': 'example.com',
'scanner': 'Custom Python Scanner',
'date': '2025-03-30',
'duration': '2h 15m'
},
'findings': [
{
'id': 'FINDING-001',
'type': 'SQL Injection',
'severity': 'CRITICAL',
'endpoint': '/search.php?q=',
'remediation': 'Use prepared statements'
}
],
'statistics': {
'total_endpoints': 45,
'vulnerabilities_found': 8,
'critical': 1,
'high': 3,
'medium': 2,
'low': 2
}
}
with open('report.json', 'w') as f:
json.dump(report, f, indent=2)
Environment Variables for Security Testing
| Variable | Purpose | Example |
|---|---|---|
PYTHONPATH | Python module search path | export PYTHONPATH=/opt/python-security-tools |
SHODAN_API_KEY | Shodan API authentication | export SHODAN_API_KEY=your_key |
VIRUSTOTAL_API_KEY | VirusTotal API key | export VIRUSTOTAL_API_KEY=your_key |
PROXY | HTTP/HTTPS proxy | export PROXY=http://localhost:8080 |
SOCKS_PROXY | SOCKS proxy | export SOCKS_PROXY=socks5://localhost:1080 |
TARGET_URL | Default target URL | export TARGET_URL=http://target.com |
WORDLIST_PATH | Path to wordlist files | export WORDLIST_PATH=/opt/wordlists |
THREADS | Default thread count | export THREADS=50 |
Configuration Files for Security Tools
Python Security Tools Config
# ~/.security-tools/config.yaml
security:
timeout: 30
retries: 3
threads: 50
verify_ssl: true
scanning:
port_range: "1-65535"
nmap_args: "-sV -sC --script vuln"
aggressive: false
web_testing:
user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
follow_redirects: true
timeout: 10
intelligence:
shodan_api_enabled: true
virustotal_enabled: true
alienvault_enabled: false
reporting:
format: "html"
include_evidence: true
output_dir: "./reports"
.env File for API Keys
# ~/.security-tools/.env
SHODAN_API_KEY=xxxxxxxxxxxxx
VIRUSTOTAL_API_KEY=xxxxxxxxxxxxx
EXPLOIT_DB_API_KEY=xxxxxxxxxxxxx
PROXIES_HTTP=http://localhost:8080
PROXIES_HTTPS=http://localhost:8080
TARGET_TIMEOUT=30
Nmap Configuration
# ~/.nmap/nmap.conf
# Default arguments
--privileged
--script-timeout=30
--max-hostgroup=256
--max-parallelism=256
--max-rate=1000.00
Complete Pentest Workflow Examples
Reconnaissance Phase
#!/usr/bin/env python3
# reconnaissance.py
import whois
import dns.resolver
import socket
from shodan import Shodan
target = "example.com"
api = Shodan('YOUR_API_KEY')
print(f"[*] Reconnaissance for {target}")
# WHOIS lookup
print("\n[+] WHOIS Information:")
try:
w = whois.whois(target)
print(f"Registrar: {w.registrar}")
print(f"Created: {w.creation_date}")
except:
print("WHOIS lookup failed")
# DNS enumeration
print("\n[+] DNS Records:")
for record_type in ['A', 'MX', 'NS', 'TXT']:
try:
answers = dns.resolver.resolve(target, record_type)
print(f"{record_type}: {answers[0]}")
except:
pass
# Shodan search
print("\n[+] Shodan Results:")
results = api.search(f'hostname:{target}')
for result in results['matches']:
print(f"IP: {result['ip_str']} - Port: {result['port']}")
Scanning Phase
#!/usr/bin/env python3
# scanning.py
import nmap
from scapy.all import IP, TCP, send
target = "192.168.1.0/24"
print(f"[*] Scanning {target}")
# Nmap scan
nm = nmap.PortScanner()
nm.scan(target, arguments='-sV -p 1-1000')
print("[+] Open Ports:")
for host in nm.all_hosts():
for port in nm[host]['tcp']:
if nm[host]['tcp'][port]['state'] == 'open':
service = nm[host]['tcp'][port]['name']
print(f" {host}:{port} - {service}")
# Custom TCP syn scan with Scapy
print("\n[+] Syn scan with Scapy:")
for port in [22, 80, 443]:
packet = IP(dst=target)/TCP(dport=port, flags="S")
response = sr1(packet, timeout=2, verbose=False)
if response:
print(f"Port {port}: OPEN")
Vulnerability Assessment
#!/usr/bin/env python3
# vuln_scan.py
import requests
from bs4 import BeautifulSoup
import ssl
import socket
target = "https://example.com"
vulnerabilities = []
print(f"[*] Vulnerability Assessment for {target}")
# SSL certificate check
print("\n[+] SSL Certificate Analysis:")
hostname = target.replace("https://", "").replace("http://", "")
try:
context = ssl.create_default_context()
with socket.create_connection((hostname, 443)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
print(f"Issuer: {cert['issuer']}")
print(f"Expires: {cert['notAfter']}")
except:
print("SSL check failed")
# Web server headers
print("\n[+] Security Headers:")
response = requests.get(target)
headers_to_check = ['X-Frame-Options', 'X-Content-Type-Options', 'Strict-Transport-Security']
for header in headers_to_check:
if header in response.headers:
print(f"[+] {header}: {response.headers[header]}")
else:
print(f"[-] {header}: Missing")
vulnerabilities.append(header)
print(f"\n[*] Found {len(vulnerabilities)} potential issues")
for vuln in vulnerabilities:
print(f" - {vuln}")
Best Practices for Security Testing
Legal & Ethical
- Always get written authorization before testing
- Follow responsible disclosure practices
- Do not access systems without permission
- Respect data privacy and confidentiality
- Document everything with timestamps
- Report findings through proper channels
- Do not modify or destroy data
- Comply with local computer fraud laws
Technical Security
- Use isolated VMs for testing dangerous payloads
- Create network-isolated test environments
- Never test on production systems without approval
- Use strong authentication for all credentials
- Encrypt sensitive data at rest and in transit
- Rotate API keys and credentials regularly
- Keep tools and libraries updated
- Disable logging before executing exploits (in authorized tests only)
Operational Security
- Use VPN/proxy for anonymity when authorized
- Clean up artifacts after testing
- Secure all test reports and findings
- Use encrypted storage for sensitive data
- Implement proper access controls for tools
- Monitor for unauthorized access
- Maintain audit trails
- Use separate accounts for sensitive operations
Reporting
- Document all findings with proof of concept
- Include remediation recommendations
- Categorize by severity (Critical, High, Medium, Low)
- Provide clear reproduction steps
- Include timeline for responsible disclosure
- Maintain confidentiality of findings
- Follow reporting deadlines
- Provide executive summary for management
Resources & References
Python Security Libraries
- Scapy - Packet manipulation and network protocols
- paramiko - SSH protocol implementation
- pycryptodome - Cryptographic library
- requests - HTTP library
- beautifulsoup4 - HTML parsing
Penetration Testing Tools
- Metasploit - Exploitation framework
- Burp Suite - Web application testing
- SQLmap - SQL injection detection
- OWASP ZAP - Web app security scanner
Wordlists & Datasets
- SecLists - Security testing wordlists
- PayloadsAllTheThings - Payload database
- Exploit-DB - Exploit database
Learning & Training
- HackTheBox - CTF challenges
- TryHackMe - Interactive training
- PortSwigger Web Security Academy - Free training
- OWASP Top 10 - Web vulnerabilities guide
Community & Blogs
- Reddit r/cybersecurity - Community discussion
- Stack Exchange Security - Q&A platform
- Medium Cybersecurity - Articles and guides
- GitHub Security Research - Open research
Vulnerability Databases
- CVE Details - CVE vulnerability database
- NVD - National Vulnerability Database
- Rapid7 - Vulnerability research
- ZeroDayInitiative - 0-day research
Last updated: 2026-03-30