Why Python for Cybersecurity?
Python is the #1 language for security professionals because of its rich libraries (socket, requests, scapy, paramiko), rapid development, and massive community.
Network Programming Basics
Single Port Checker
import socket
def check_port(host, port, timeout=1):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except socket.error:
return False
target = "192.168.1.1"
for port in range(1, 1025):
if check_port(target, port):
print(f"[+] Port {port} is OPEN")
Multithreaded Port Scanner
import socket
import concurrent.futures
def scan_port(args):
host, port = args
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
return port, service
except Exception:
pass
return None
def fast_scan(host, start=1, end=1024):
print(f"[*] Scanning {host}...")
with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
results = executor.map(scan_port, [(host, p) for p in range(start, end+1)])
for result in results:
if result:
print(f"[+] {result[0]}/tcp OPEN {result[1]}")
fast_scan("192.168.1.1")
HTTP Requests for Recon
import requests
from concurrent.futures import ThreadPoolExecutor
def check_path(url, path):
full_url = f"{url}/{path}"
try:
resp = requests.get(full_url, timeout=3, allow_redirects=False)
if resp.status_code not in [404, 403]:
return full_url, resp.status_code
except requests.RequestException:
pass
return None
def dir_bruteforce(url, wordlist_path):
with open(wordlist_path) as f:
words = [line.strip() for line in f if line.strip()]
with ThreadPoolExecutor(max_workers=20) as executor:
for result in executor.map(lambda w: check_path(url, w), words):
if result:
print(f"[{result[1]}] {result[0]}")
dir_bruteforce("http://target.com", "/usr/share/wordlists/dirb/common.txt")
SSH with Paramiko
import paramiko
def ssh_connect(host, username, password, port=22):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(host, port=port, username=username, password=password, timeout=5)
_, stdout, _ = client.exec_command("id && hostname")
print(stdout.read().decode())
client.close()
return True
except paramiko.AuthenticationException:
return False
Recommended Projects to Build
- Port Scanner ← Start here
- Subdomain Enumeration tool
- Web Directory Brute-forcer
- Packet Sniffer using Scapy
- SSH brute-force (authorized targets only!)