14 Python Libraries for Ethical Hacking

Jul 26, 2023 8 min read

Python is a powerful language that can be used for a variety of purposes, including ethical hacking. In this blog post, we will discuss 14 of the most popular Python libraries you can use for ethical hacking.

1. Scapy

Scapy is a powerful interactive packet manipulation library written in Python. It can be used to send, sniff, forge, and decode packets of a wide number of protocols. Scapy can also be used to dissect network traffic, create custom network applications, and develop exploit code.

Install Scapy with:

pip install scapy

Sample code to perform a simple network scan:

Python
from scapy.all import Ether, ARP, srp


def scan_network(subnet):
    hosts = []

    # Send ARP request packet
    request = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=subnet)
    responses, _ = srp(request, timeout=5, verbose=False)

    # Process the responses and extract active hosts
    for response in responses:
        mac_addr = response[1].src
        ip_addr = response[1].psrc
        hosts.append((ip_addr, mac_addr))

    return hosts


# Usage example
hosts = scan_network('192.168.1.0/24')

if hosts:
    print("Active Hosts:")
    for ip_addr, mac_addr in hosts:
        print(f"IP address: {ip_addr}, MAC address: {mac_addr}")
else:
    print("No active hosts found.")

2. Requests

Requests is a Python library that makes it easy to send HTTP requests. It abstracts the complexities of making HTTP requests behind a beautiful, simple API. You can focus on interacting with services and consuming data in your application, without having to worry about the underlying details of how HTTP requests work.

Install the library with:

pip install requests

Sample code to make HTTP POST request:

Python
import requests


def make_http_post_request(url, data):
    try:
        r = requests.post(url, data=data)
        r.raise_for_status()
        return r.text
    except requests.exceptions.RequestException as e:
        print(f'An error occured: {e}')


# Usage example
url = 'https://www.example.com'
data = {
  'username': 'user1',
  'password': 'password123'
}
response = make_http_post_request(url, data)

3. Socket

The socket library is a low-level networking library that provides access to the underlying operating system’s networking stack. It allows you to create network sockets and perform various network-related tasks like port scanning and banner grabbing. This library comes with your Python installation so you don’t have to install anything.

Here is a sample code to grab the banner from the specified IP address and port:

Python
import socket


def banner_grabbing(ip_addr, port):
    try:
        # Create a TCP connection
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        s.connect((ip_addr, port))

        # Print the banner (limited to 1024 bytes here, adjust if needed)
        banner = s.recv(2048).decode("utf-8").strip()
        print(f"Banner from {ip_addr}:{port}:")
        print(banner)

    except socket.timeout:
        print("Connection attempt timed out.")
    except socket.error as e:
        print(f"An error occurred: {e}")
    finally:
        s.close()


# Usage example
banner_grabbing('192.168.1.1', 80)

4. BeautifulSoup

BeautifulSoup is a library for web scraping and parsing HTML documents, which can be useful in extracting information and finding vulnerabilities in web pages.

Install BeautifulSoup with:

pip install beautifulsoup4

Here is the sample code to retrieve all of the links from a web page:

Python
import requests 
from bs4 import BeautifulSoup 


def get_links_from_url(url):
    links = []

    try:
        # Fetch the HTML content of the web page
        response = requests.get(url)
        response.raise_for_status() 

        # Find all anchor tags (links) 
        soup = BeautifulSoup(response.text, "html.parser")
        links = soup.find_all("a")

        for link in links:
            href = link.get("href")
            if href:
                links.append(href)
    except requests.exceptions.RequestException as e:
        print(f"An error occurred while fetching the URL: {e}")
    except Exception as e:
        print(f"An error occurred while parsing the web page: {e}")

    return links


# Usage example
url = 'https://www.example.com/index.html'
links = get_links_from_url(url)

5. Paramiko

Paramiko is a Python library that provides a comprehensive and easy-to-use API for interacting with SSH servers. It can be used to connect to remote servers, execute commands, transfer files, and more.

Install paramiko with:

pip install paramiko

Here is a sample code to establish an SSH connection to a remote server, run a command on the server, and retrieve the output:

Python
import paramiko

def run_ssh_command(hostname, username, password, command, port=22):
    try:
        client = paramiko.SSHClient()

        # Automatically add the server's host key 
        # (not recommended for production use)
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Run the command on the remote server
        client.connect(hostname, port, username, password)
        stdin, stdout, stderr = client.exec_command(command)

        # Print the output of the command
        output = stdout.read().decode("utf-8")
        print(output)

    except paramiko.AuthenticationException:
        print("Authentication failed. Please check your credentials.")
    except paramiko.SSHException as e:
        print(f"SSH error occurred: {e}")
    except paramiko.BadHostKeyException as e:
        print(f"Host key could not be verified: {e}")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Close the SSH connection
        client.close()


# Usage example
username = '<your_username>'  
password = '<your_password>' 
run_ssh_command('127.0.0.1', username, password, 'ls -l')

6. Python-nmap

Python-nmap is a Python library that provides an interface to the Nmap port scanner. It can be used to scan networks for open ports and services, and to identify vulnerabilities.

To use the python-nmap library, make sure you have the nmap tool installed on your machine. Refer to the documentation about how to install nmap on your operating system.

Once you have nmap installed, you can install python-nmap with:

pip install python-nmap

Here is a sample code for scanning open ports:

Python
import nmap


def scan_ports(id_addr):
    nm = nmap.PortScanner()

    # Perform a TCP port scan on the target IP address
    scan_result = nm.scan(hosts=id_addr, arguments="-p 1-1024")

    # Extract and print open ports and their states
    for host, scan_data in scan_result["scan"].items():
        print(f"Host: {host}")
        for port, port_data in scan_data["tcp"].items():
            if port_data["state"] == "open":
                print(f"Port: {port}, State: {port_data['state']}")


# Usage example
scan_ports('127.0.0.1')

7. Cryptography

The cryptography library is a Python library that provides cryptographic algorithms and primitives. It is a successor to the deprecated PyCrypto library, and it is designed to be more secure and easier to use.

Install the cryptography library:

pip install cryptography

Sample code to perform encryption and decryption using the Fernet symmetric encryption scheme:

Python
from cryptography.fernet import Fernet


def fernet_generate_key():
    # Generate a new Fernet key
    key = Fernet.generate_key()
    return key


def fernet_encrypt(message, key):
    fernet = Fernet(key)
    encrypted_message = fernet.encrypt(message.encode())
    return encrypted_message


def fernet_decrypt(encrypted_message, key):
    fernet = Fernet(key)
    decrypted_message = fernet.decrypt(encrypted_message).decode()
    return decrypted_message


# Usage example
message = 'Top secret message'
key = fernet_generate_key() 

encrypted_message = fernet_encrypt(message, key)
print(f'Encrypted message: {encrypted_message}')

decrypted_message = fernet_decrypt(encrypted_message, key)
print(f'Decrypted message: {decrypted_message}')

8. Dnspython

Dnspython provides a high-level interface to the Domain Name System (DNS). It can be used to query DNS servers, parse DNS responses, and perform other DNS-related tasks.

Install the dnspython library with:

pip install dnspython

Sample code to perform a DNS query and retrieve the IP addresses associated with a domain name (A records):

Python
import dns.resolver


def dns_lookup(domain_name):
    try:
        # Perform a DNS query to retrieve A records (IPv4 addresses) 
        # for the domain name
        result = dns.resolver.resolve(domain_name, 'A')

        # Extract and print the IP addresses
        print(f"IP addresses for '{domain_name}':")
        for record in result:
            print(record.address)

    except dns.resolver.NoAnswer:
        print(f"No A records found for '{domain_name}'")
    except dns.resolver.NXDOMAIN:
        print(f"The domain '{domain_name}' does not exist")
    except dns.resolver.Timeout:
        print("DNS query timed out")
    except dns.resolver.NoNameservers:
        print("No nameservers found for the domain")
    except Exception as e:
        print(f"An error occurred: {e}")


# Usage example
dns_lookup('example.com')

9. Selenium

Selenium is a web automation library that can be used for testing web applications and APIs. It can be used to automate tasks such as logging in to websites, filling out forms, and clicking on links.

The main advantage of Selenium is it supports Javascript so you can use it for finding frontend-related vulnerabilities such as XSS attacks.

Install the selenium library with:

pip install selenium

Sample code of using Selenium with Python to automate a web browser and perform a search on Google:

Python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By


def google_search(query):
    # Create a new instance of Chrome WebDriver
    driver = webdriver.Chrome()

    try:
        # Open Google's homepage
        driver.get("https://www.google.com")

        # Find the search box and enter the query
        search_box = driver.find_element(By.NAME, 'q')
        search_box.send_keys(query)
        search_box.send_keys(Keys.RETURN)

        # Wait for the search results to load
        driver.implicitly_wait(5)

        # Print the search results
        search_results = driver.find_elements(By.CSS_SELECTOR, "div.g")
        print("Search results:")
        for result in search_results:
            print(result.text)
            print("-" * 50)

    finally:
        # Close the browser
        driver.quit()


# Usage example
google_search('The hacking blog')

10. GeoIP2

GeoIP2 is a library that can be used to identify the geographical location of an IP address. It can be used to determine the country, city, and region of an IP address.

Install the GeoIP2 library with:

pip install geoip2

Here is the sample code to find the geolocation of an IP address:

Python
import geoip2.database


def geolocation_by_ip(ip_address):
    # Replace 'path/to/GeoIP2-City.mmdb' with the actual path to your GeoIP2 City database
    database_path = 'path/to/GeoIP2-City.mmdb'

    try:
        # Load the GeoIP2 City database
        reader = geoip2.database.Reader(database_path)

        # Perform the IP geolocation lookup
        response = reader.city(ip_address)

        # Extract and print geolocation information
        print(f"IP Address: {ip_address}")
        print(f"City: {response.city.name}")
        print(f"Region: {response.subdivisions.most_specific.name}")
        print(f"Country: {response.country.name}")
        print(f"Latitude: {response.location.latitude}")
        print(f"Longitude: {response.location.longitude}")

    except FileNotFoundError:
        print("GeoIP2 database file not found.")
    except geoip2.errors.AddressNotFoundError:
        print("IP address not found in the database.")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Close the database reader
        reader.close()


# Usage example
geolocation_by_ip('4.4.4.4)

11. Twisted

Twisted is a Python framework that is designed to make it easy to write event-driven network applications. It is a powerful tool that can be used for writing web servers and other network applications.

Install the library:

pip install twisted

Here is a sample code to create a basic TCP echo server with Twisted. The server will listen for incoming connections and echo back any data it receives from clients.

Python
from twisted.internet import reactor, protocol


class EchoServer(protocol.Protocol):
    def dataReceived(self, data):
        # Echo back the received data
        self.transport.write(data)


class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return EchoServer()


if __name__ == "__main__":
    # Specify the port number on which the server will listen
    port = 12345

    # Start the Twisted reactor with the EchoFactory
    reactor.listenTCP(port, EchoFactory())
    print(f"Echo server started on port {port}")

    # Start the Twisted event loop
    reactor.run()

12. Impacket

Impacket provides a comprehensive and easy-to-use API for interacting with network protocols. It can be used to send and receive packets, parse network traffic, and perform other network-related tasks.

Install the library with:

pip install impacket

Below is a simple example of using the Impacket library to perform a basic SMB (Server Message Block) client connection and list the files in a remote directory:

Python
from impacket import smb


def smb_client_connect(ip_addr, username, password):
    try:
        # Connect to the remote server
        client = smb.SMB(ip_addr, ip_addr)
        client.login(username, password)

        # List files in a remote directory
        share_name = 'C$'  # Replace with the name of the shared directory you want to list
        directory = '\\'  # Replace with the directory path you want to list
        file_list = client.listPath(share_name, directory)

        print(f"Files in {directory} on {ip_addr}:\n")
        for file_info in file_list:
            print(file_info.get_longname())

    except smb.SessionError as e:
        print(f"Authentication failed: {e}")
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        # Close the SMB connection
        client.logout()


# Usage example
ip_addr = '192.168.1.100'
username = '<your_username>'
password = '<your_password>'

smb_client_connect(ip_addr, username, password)

13. Faker

Faker is a Python library that generates fake data. It can be used to generate a variety of data, including names, addresses, phone numbers, and email addresses. While the library itself is not explicitly designed for ethical hacking, it can be a useful tool in certain hacking-related tasks.

Install with:

pip install faker

Sample code to generate fake user data:

Python
from faker import Faker


def generate_fake_user_data(num_users=10):
    fake = Faker()

    users = []
    for _ in range(num_users):
        user_data = {
            "name": fake.name(),
            "email": fake.email(),
            "address": fake.address(),
            "phone_number": fake.phone_number(),
        }
        users.append(user_data)

    return users


# Usage example
fake_users = generate_fake_user_data()
for user in fake_users:
    print(user)

14. IPy

IPy provides a comprehensive and easy-to-use API for handling IPv4 and IPv6 addresses and networks. It can be used to parse IP addresses and networks, generate IP addresses and networks, and perform other IP-related tasks.

Install the library with:

pip install IPy

Below is a sample code to perform subnet calculations and generate IP addresses within a given subnet:

Python
from IPy import IP


def generate_ip_addresses(subnet):
    try:
        subnet_ip = IP(subnet)
        print(f"IP addresses within the subnet {subnet}:")
        for ip in subnet_ip:
            print(ip)
    except ValueError as e:
        print(f"Something went wrong: {e}")


generate_ip_addresses('192.168.1.0/24')

Summary

Python is a powerful language that can be used for a variety of purposes, including ethical hacking. There are a number of Python libraries that you can use for ethical hacking, each with its own strengths and weaknesses.

In this blog post, we have looked at 14 Python libraries to perform a variety of tasks, such as scanning networks for vulnerabilities, web scraping, and data encryption.

The libraries listed in this post are just a few of the many that are available. There are many other libraries that can be used for ethical hacking, so it is important to do your research and find the libraries that are right for you.