Use Python Requests to Authenticate

Using requests, you can authenticate on a secure website with a username and password.

This method, will also read the CSRF field and cookie, and get it ready for the validation.


import requests
from bs4 import BeautifulSoup, SoupStrainer
from termcolor import colored, cprint

def login(target):
    # We will set a few default objects / values

    # Header details, that will contain user agent
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    # Payload, used to sent username, password and the rest of the default fields
    payload = {
        target['username']['field_name']: target['username']['value'],
        target['password']['field_name']: target['password']['value']

    # In order to generate our object, first we will search for hidden fields
    # A hidden field, can be CSRF ( )
    loginPage = requests.get(target['website'])

    # Using bs4, we can easily generate a list of forms
    forms = BeautifulSoup(loginPage.text, "html.parser", parse_only=SoupStrainer('form'))

    # Once our forms object was generated, we will generate an object with all available fields
    for form in forms:
        # Our search, will be mainly on input / textarea and submit fields
        fields = form.findAll(['input', 'textarea', 'submit'])

        # Each field will be parsed, but, the ones that already have a value, will be ignored
        # Usefull to ignore username and password
        for field in fields:
                if payload[field.get("name")]:
                    # Value Already there, pass
            except Exception:
                # If there is a valid field, that has a name, add it to our object and keep the default value
                # Who knows, maybe it is an CSRF field
                if field.get("name"):
                    payload[field.get("name")] = field.get("value")

    with requests.Session() as s:

        # Set the current cookies, as if we are visiting that website
        # Most of the csrf validations, also use a csrf cookie :)

        for cookie, cookieValue in loginPage.cookies.items():
            s.cookies.update({cookie: cookieValue})

        # This will go over https security issue
        # And, what "referer" is better than the login page itself?
        s.headers.update({"referer": target['website']})

        # Return login details
        return['website'], data=payload, headers=headers)

target = {
    'website': '',
    'username': {
        # You can always replace 'username' with 'email', or, whatever field name you'll need
        'field_name': 'username',
        'value': ''
    'password': {
        # In case there is a different name used instead of 'password', just change the field name
        'field_name': 'password',
        'value': ''

cprint("Trying to authenticate", 'white')
cprint("\nWebsite : " + str(target['website']), 'blue')
cprint("Username : " + str(target['username']['value']), 'blue')
cprint("Password : *****\n", 'blue')
authTry = login(target)
if authTry.url == target['website']:
    cprint("[-] Invalid login details\n", 'red')
    cprint("[+] Authenticated!\n", 'green')


Python Tutorials
Create daily snapshots using Python on Digitalocean
Use python to automatically create daily snapshots on digitalocean. This script will generate the new snapshot and automatically remove the old one.
Linux Python Django Tutorials
Serve Django Applications with uWSGI and Nginx on CentOS
In this tutorial you will learn how to install and configure VirtualEnv and VirtualEnvWrapper on centos. Also, you will learn how to create your first django application and deploy it.