Archive

Posts Tagged ‘mechanize’

Automatic Login for Hotel WiFi, …

October 14th, 2012 3 comments

The internet in my current apartment pisses me off. I have to login (usr/pw) into a strange website every time I connect the laptop. The login uses the POST method, so that I can’t control the cgi script via URL variables. ping isn’t available (maybe blocked by the router or ISP, not sure). And it’s only a LAN router, which had 24 hours ago a 0.5m LAN cable. The cable was upgraded to 3m :-), enough to write this post in my bed.

I’m also not sure about the security and logging of my ISP and a new Japanese copyright law is really hard. This why I wrote my last post, but lets fix the login problem first.

Willi gave me a hint to try pexpect, which is expect for python. That wasn’t exactly what I was searching for, but a good starting point and probably a handy tool for other purposes. I kind of wanted to stay with python, and found mechanize (Ubuntu has the package already “python-mechanize”; for Mac OSX just download package from their website). This python module is among other stuff able to emulate a browser and interact with the elements on the website, like following links, fill out forms, …

Here is my current script to login on the ISP webpage in my apartment to get a IP lease. In my case the URL is an IP address since I use external DNS servers.

import mechanize

br = mechanize.Browser()
br.open("http://172.16.dead.beef")

br.select_form(name="LoginUser")
br["username"]="fucking"
br["passwd"]="capitalism"
br.form.find_control("LoginMode").get("AutoLogin").selected = False
response = br.submit()

if response.get_data().find("Success") > 0:
    print "Login successful"
    br.close()
else:
    print "Error: something has gone wrong"
    print ""
    print "Page returned from server:"
    print response.read()
    br.close()

Ok, the basics are: start the browser; get the form for the login, change the input variables for username and password (HTML source looks like: <INPUT type=”text” name=”username”>); deselect the AutoLogin checkbox (which doesn’t work anyway) and in the end “click” the submit button.

In case you want to know more, the website of mechanize has some examples or just use the help function of python. The mechanize package and its function are well documented.

My script can easily be modified to connect to a Hotel/Airport WiFi or other websites you want to control in an automatic fashion.