This Python 2 class logs in and connect to a secured website. The class inherit from thread so that it is possible to run multiple instance of the class.
class CRReader(threading.Thread):data = Noneheaders = Nonedef __init__(self, crNo, semaphore):threading.Thread.__init__(self, name=crNo)self.loggedin = False self.crNo = crNo self.semaphore = semaphoreself.opener = Noneself.status = Nonedef login(self):if self.loggedin is False:#print 'Login ' + self.crNourl = "https://example.com/login.php"opts = {'username': 'John','password': 'pass1',}CRReader.headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12','Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5','Accept-Language': 'en-gb,en;q=0.5','Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7','Connection': 'keep-alive'}CRReader.data = urllib.urlencode(opts)request = urllib2.Request(url, CRReader.data, CRReader.headers)cookies = cookielib.CookieJar()response = urllib2.urlopen(url)cookies.extract_cookies(response, request)cookie_handler = urllib2.HTTPCookieProcessor(cookies)redirect_handler = urllib2.HTTPRedirectHandler()self.opener = urllib2.build_opener(redirect_handler, cookie_handler)response = self.opener.open(request)self.loggedin = Truereturn self.opener
Commentaires