MortenSickel
MortenSickel

Reputation: 2200

Delete cookies / end session using cookiejar

I have written a python script fetching a State of Health web page from some hardware we are using. Looking into the HTML and javascript files, it was relatively easy to fetch what I wanted. The problem is that I am not able to end the session and delete the cookies so that the web interface is usable for other users before my session times out. I have no possibility to change anything on the server side.

What I am doing is basically:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
url=mydataurl
headers={"Authorization:"username:encrytptedpassword","Cookie":"user=username; password="encryptedpassword"}
# Both Authorization and Cookie need to be set to go further
data="something"

req=urllib2.Request(url,data,headers)
connection=urllib2.urlopen(req)
response=connection.read()

# Now I have what I want in response and can work on that. 
# But the server thinks I am still active and does not let anybody else in

# So I call what is called when I press logout on the web page:

url=logouturl
headers={}
data=""
req=urllib2.Request(url,None,headers)
connection=urllib2.urlopen(req)
logoutresponse=connection.read()

#and just in case

headers={}
cj.clear()
cj.clear_session_cookies()
url="http://myserver/index.htm"
req=urllib2.Request(url,None,headers)
connection=urllib2.urlopen(req)
logoutresponse=connection.read()

connection.close()

Am I doing something wrong to get rid of the cookies in this session? I have also tried to close all the three connections I have started but to no avail.

I can open the web page in a browser on the computer I am running the script on, then log out and immediately after opening it on another computer. If I run the script I have to wait some minutes to something times out on the server before being able to log on again.

It might, of course, be that the server is doing something else as well to keep the session alive, if so I may be out of luck.

I prefer to use built-in libraries and it is not possible for me at the moment to upgrade to use python 3.

Upvotes: 1

Views: 1432

Answers (1)

Sam Hollenbach
Sam Hollenbach

Reputation: 672

A common way to "delete" cookies is to simply set the expiration date of the cookie to a time in the past (many systems can just set it to time=0 which should work). I am not familiar with cookiejar, but you might want to look into this method.

Upvotes: 1

Related Questions