Brute Force A Website Login In Python


Screen shot of python script running brute-force attack on my college’s website.

This post gives brief introduction to Brute Force Attack, Mechanize in Python for web browsing and explains a sample python script to brute force a website login.

Brute Force Attack

Brute force is the easiest way one can implement to recover lost passwords (Yet it can take literally ages to crack one). Basically,  this involves checking all possible combinations of passwords until the right one is found. This can be really helpful when characters in the password is known but not the correct combination, here possible combinations decrease drastically. Following paragraph gives a vague idea of how much time it can take to find right combination in the worst case scenario.

Suppose the length of password is N and we know nothing about characters present in the string, possible characters can be all alphabets (upper and lowercase), numbers (0-9) and special characters (~, @, #, $, ^), thus each character of the password string can be any of the above 67 characters which leads to a total of 67^N combinations (as you can clearly see it increases exponentially with the length). If we are brute forcing a website login, time taken significantly depends on the internet speed, for instance it can do four login checks per second, it takes nearly 58 hours to crack a password of four character length. Suppose if we know the characters, we can find the correct combination in 64 seconds, far less than previous case.


In the following brute-force script we use Mechanize, a python library for stateful programmatic web browsing, used for automating interaction with websites (Initially it was written for PERL users). There are many ways to install this library. Following two ways will automatically download the latest version source and install it (for linux users).

Easy Install:

easy_install mechanize


pip install mechanize

For installing it manually you can go through their documentation at Mechanize. Here are few things you have to know about mechanize in order to understand the sample script.

1. Initializing browser object: 

import mechanize
br = mechanize.Browser()

2. Opening the login page:

response =

3. Selecting the required form in the page:

br.select_form("form name") #selecting forms by name
br.select_form(nr=0)        #use to select the first form in the page if it is unnamed

Continue reading