My first python project, converting speedy.js (JavaScript speedy bandwidth usage checking) into python script. Thanks to this project, I’ve learned little knowledge about some python library like: urllib, urllib2, cookielib, and regular expression.


#!/usr/bin/python

import urllib2, urllib, cookielib, re

username = "XXX@telkom.net"
password = "XXXXXXXXXX"

try:
    postdata = urllib.urlencode({
        "username": username, 
        "password": password,
        })
    
    cj = cookielib.CookieJar()
    
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    r = opener.open("http://divre5.telkomspeedy.com/session.php", postdata)
    if r:
        r2 = opener.open("http://divre5.telkomspeedy.com/?")
        if r2:
            content = r2.read()
            content = re.sub(r"[rn]", "", content)
            p = re.compile(r'<b>Pemakaian Speedy</b>(.*?)</TD>.*?' + 
                '<td[^>]*>Pemakaian</td><td[^>]*>(.*?)</td>.*?' + 
                '<td[^>]*>Pemakaian</td><td[^>]*>(.*?)</td>.*?' + 
                '<td[^>]*>Limit</td><td[^>]*>(.*?)</td>.*?'+ 
                '<td[^>]*>Kelebihan</td><td[^>]*>(.*?)</td>', 
                re.IGNORECASE)
            result = p.findall(content)
            if result:
                (bulan, persen, pemakaian, bandwidth, kelebihan) = result[0]
                bulan = bulan.replace("&nbsp;", "")
                bulan = re.sub("<.*?>", "", bulan)
                s = "Pemakain Speedy %snn" + 
                    "Terpakai: %sn" + 
                    "Pemakaian: %sn" + 
                    "Limit: %sn" + 
                    "Kelebihan: %sn" % (bulan, persen, pemakaian, bandwidth, kelebihan)
                print s
                raw_input("press return...")
except Exception, why:
    print "Error: %s" % why

Copy and save as file speedy.py. If you’re running on Ubuntu or Gentoo, I’m sure you have python installed.