Python penetration testing example

Edith 15 Published: 11/10/2024

Python penetration testing example

Here's an example of a basic Python script for penetration testing:

Python Penetration Testing Example

In this example, we'll use the nmap module from PyNmap to scan a target host and detect open ports. We'll also use the ssh module from Paramiko to connect to one of those open ports (assuming it's SSH) and run some basic commands.

import nmap

import paramiko

Define the target host IP address

target_ip = '192.168.1.100'

Use NMap to scan the target host

nm = nmap.PortScanner()

nm.scan(target_ip, arguments='-p 22,80,443')

Check if the target is up and responsive

if nm[target_ip].state() == 0:

print(f"{target_ip} is not responding!")

else:

print(f"{target_ip} is responding!")

Get a list of open ports

open_ports = []

for port in nm[target_ip]['tcp'].keys():

if nm[target_ip]['tcp'][port]['state'] == 'open':

open_ports.append(port)

print(f"Open ports: {', '.join(map(str, open_ports))}")

Connect to one of the open ports (assuming it's SSH)

ssh_port = 22

ssh_host = target_ip

ssh_user = 'username'

ssh_pass = 'password'

try:

ssh_client = paramiko.SSHClient()

ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh_client.connect(hostname=ssh_host, port=ssh_port, username=ssh_user, password=ssh_pass)

Run some basic SSH commands

stdin, stdout, stderr = ssh_client.exec_command('ls -l')

output = stdout.read().decode('utf-8')

print(output)

ssh_client.close()

except Exception as e:

print(f"Error: {str(e)}")

finally:

ssh_client.close() if 'ssh_client' in locals() else None

How it works

The script uses the nmap module to scan the target host for open ports. We specify the -p 22,80,443 argument to focus on SSH (port 22), HTTP (port 80), and HTTPS (port 443) ports. We check if the target is responding by checking the state of the NMap scan result. If it's not responding, we print a message indicating that. We get a list of open ports from the NMap scan result and print them out. We connect to one of the open ports using Paramiko (assuming it's SSH) with the specified username and password. We run some basic SSH commands (ls -l) using the exec_command method, read the output, decode it as UTF-8 text, and print it out.

Note: This is a very basic example and should not be used for actual penetration testing without proper training, expertise, and legal permission!

Python pentesting tools

I'm sorry! I'll respond in English as per your request. Here are some popular Python-based penetration testing (pentesting) tools:

Nmap: A network scanning tool that helps identify hosts, services, and operating systems on a network. It's an essential tool for pentesters and security professionals. Scapy: A powerful interactive packet manipulation program and logging/analyzing/librarian for all TCP/IP protocol algorithms. It's useful for reconnaissance, vulnerability testing, and post-exploitation activities. Burp Suite: An integrated platform for performing manual penetration testing, reverse engineering, and security research. Its features include web scraping, URL rewriting, and request modification. Pytables: A Python extension for managing large datasets and data structures in a flexible and efficient manner. It's used in various pentesting tools to store and manipulate captured data.

Impacket: A collection of Python classes for working with network protocols. Its features include packet sniffing, protocol manipulation, and payload generation. Cryptography: A library that provides cryptographic primitives like hashing, signing, encryption, and decryption. It's useful for validating and manipulating encrypted data during pentesting. SQLmap: An automated SQL injection tool that can detect vulnerabilities in web applications. Its features include database enumeration, password guessing, and query execution.

Pbust: A Python-based command-line tool for identifying and exploiting buffer overflow vulnerabilities in C/C++ programs.

Fimap: A Python-based command-line tool for extracting files from Linux systems using the file mapping technique. W3af: An open-source web application attack framework that helps identify and exploit vulnerabilities in web applications. Its features include discovery, enumeration, and exploitation of vulnerabilities. Bandit: A static analysis tool that detects common security issues and best practices violations in Python code. It's useful for identifying potential security flaws during the development process. P0f: A network fingerprinting tool that identifies hosts based on their IP address, MAC address, and other characteristics. Its features include protocol detection, OS identification, and host discovery.

These are just a few examples of the many Python-based pentesting tools available. Python's flexibility, ease of use, and extensive libraries make it an ideal language for creating penetration testing tools.