Home > Back-end >  How do I connect a Python script to run combinations on a webpage input?
How do I connect a Python script to run combinations on a webpage input?

Time:06-23

As a little project for practice, I am attempting to write a Python script to essentially brute force a coupon code input on the website for a random restaurant. The codes take the form of two capital letters followed by 6 integers. For example: XZ957483. As a starting point, I've written a script which generates an infinite amount of combinations in the correct form. That looks like this:

import random
import string

i = 1
while i>=1:
    number = random.randint(100000,999999)
    print(random.choice(string.ascii_uppercase) random.choice(string.ascii_uppercase) str(number))
    i = i 1

How do I actually make the connection to run the piece of code on the webpage and make it continue until it finds the correct combination? And also I was thinking, is it better to run the script and generate all the combinations on the webpage input, or should I write the combinations to a text file and use that as a dictionary to run on the webpage? Any help is much appreciated!

CodePudding user response:

A real example would be hard (and unethical) to do, as websites will block requests after too many attempts, or use captcha to prevent bots, and so on.

But we can write a simple webserver to implement a simple scenario, where requests to the /cupons/{cupon_id} endpoint may respond with 200 OK if found, or 404 NOT FOUND otherwise.

To do this, we'll need some extra libraries which you can install with pip:

pip install fastapi requests uvicorn
from fastapi import FastAPI, HTTPException, status

VALID_CUPON = "XZ12345"

app = FastAPI()

@app.get("/cupons/{cupon_id}")
def get(cupon_id: str):

    if cupon_id == VALID_CUPON:
        return {"msg": f"{cupon_id} is a valid cupon!"}
    
    else:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"{cupon_id} is NOT a valid cupon!")

Now we can run this FastAPI app with the uvicorn server. I called it webserver.py, and the app is saved in the variable app, so the argument for uvicorn will be webserver:app:

python3 -m uvicorn webserver:app --reload

The server will be running in the console and we can send requests to it. For example, you can try it in your browser, at http://localhost:8000/cupons/XZ12345.

Now we can write a script to send requests to it and run it in a different console:

import random
import string
import requests

i = 1
while i>=1:
    number = random.randint(100000,999999)
    random_cupon = random.choice(string.ascii_uppercase) random.choice(string.ascii_uppercase) str(number)

    response = requests.get(f"http://127.0.0.1:8000/cupons/{random_cupon}")

    if response.status_code == 404:
        print(f"Failed attempt with {random_cupon}")
    
    if response.status_code == 200:
        print(f"Succesful attempt with cupon {random_cupon}!!!")
        break

    i = i 1

This script will send many requests to your local server and print a message announcing failure or success. If success, it also breaks from the loop and stops.

We can make some improvements:

  • i is not really needed, as we want it to run forever: we can just use True
  • In your code, the number starts at 100000, so the cupon "AX000001" would never be found. We can include all possible numbers and then do some string formatting tricks to add leading 0s.
import random
import string
import requests

while True:
    letter1 = random.choice(string.ascii_uppercase)
    letter2 = random.choice(string.ascii_uppercase)
    number = random.randint(0,999999)
    random_cupon = f"{letter1}{letter2}{number:06}"

    response = requests.get(f"http://127.0.0.1:8000/cupons/{random_cupon}")

    if response.status_code == 404:
        print(f"Failed attempt with {random_cupon}")
    
    if response.status_code == 200:
        print(f"Succesful attempt with cupon {random_cupon}!!!")
        break

Keep in mind this will take you a long, long time to finish. With 2 letters and 6 digits, we get 26*26*1000000 combinations, ie 67 million - if each request to your local server takes 1 milisecond, that's going to take an average of 676,000 seconds to complete! A request to a remote webserver is likely to take much longer, eg at least 50ms, likely more.

So it may be better to start with smaller values, eg 2 letters and 1 digits. To do this, you'll need to change:

  • the valid cupon in the server
  • the random generator
  • the string formatting which adds leading zeroes

CodePudding user response:

You could try to check if their is an API where you can make post calls too with a different coupon code each time. However I'm not sure if this is ethical and I doubt it will work.

This is because you're trying to generate a coupon code with about half a billion possibilities. No server will allow you to try to brute force this, and if they allow this it will most likely crash before a result is achieved.

  • Related