473,414 Members | 1,878 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

urllib2 http authorization question


I am writing a script to check on my router's external IP address. My
ISP refreshes my IP very often and I use dyndns for the hostname for my
computer. My Netgear mr814 router has a webserver that uses HTTP basic
authorization.

My script uses urllib2 to connect to the router and read the html page
with the current external IP address. This is the function I wrote to
lookup the router's external IP:

def mr814(router_user, router_password):
"Looks up the IP from the router and returns it as a string."
req = urllib2.Request('http://192.168.0.1/sysstatus.html')
req.add_header("USER-AGENT",
"Mozilla/4.76 [en] (X11; U; Linux 2.4.1-0.1.9 i586)")
req.add_header("AUTHORIZATION", string.strip("Basic " +
base64.encodestring("%s:%s" % (router_user, router_password))))
IP = re.compile('(\d{1,3}\.){3}\d{1,3}')
for line in urllib2.urlopen(req):
if IP.search(line):
ip = line.strip()
return ip

The first time I run this script, I always get a urllib2.HTTPError. But
then If I ran the exact same script again afterward, I get access.
lookup.mr814('username', 'password') Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "lookup.py", line 13, in mr814
for line in urllib2.urlopen(req):
File "/usr/lib/python2.3/urllib2.py", line 136, in urlopen
return _opener.open(url, data)
File "/usr/lib/python2.3/urllib2.py", line 333, in open
'_open', req)
File "/usr/lib/python2.3/urllib2.py", line 313, in _call_chain
result = func(*args)
File "/usr/lib/python2.3/urllib2.py", line 849, in http_open
return self.do_open(httplib.HTTP, req)
File "/usr/lib/python2.3/urllib2.py", line 843, in do_open
return self.parent.error('http', req, fp, code, msg, hdrs)
File "/usr/lib/python2.3/urllib2.py", line 359, in error
return self._call_chain(*args)
File "/usr/lib/python2.3/urllib2.py", line 313, in _call_chain
result = func(*args)
File "/usr/lib/python2.3/urllib2.py", line 419, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized lookup.mr814('admin', '54wins') '66.72.200.255'

This is baffling me. Does the webserver ignore the AUTHORIZATION header
on the first request? Should I do something like this:
try:

.... lookup.mr814('admin', '54wins')
.... except urllib2.HTTPError: #I only want to catch 401 here, but how?
.... print "I got back the 401 error. Trying again..."
.... lookup.mr814('admin', '54wins')
.... except:
.... print "something else went wrong."

If that is recommended, how do I distinguish between 401 errors, vs
other errors?

Thanks for the help.
Jul 18 '05 #1
1 3933
In article <sl*****************@overlook.homelinux.net>, Matthew Wilson wrote:

[snip]
lookup.mr814('username', 'password') Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "lookup.py", line 13, in mr814
for line in urllib2.urlopen(req):
File "/usr/lib/python2.3/urllib2.py", line 136, in urlopen
return _opener.open(url, data)
File "/usr/lib/python2.3/urllib2.py", line 333, in open
'_open', req)
File "/usr/lib/python2.3/urllib2.py", line 313, in _call_chain
result = func(*args)
File "/usr/lib/python2.3/urllib2.py", line 849, in http_open
return self.do_open(httplib.HTTP, req)
File "/usr/lib/python2.3/urllib2.py", line 843, in do_open
return self.parent.error('http', req, fp, code, msg, hdrs)
File "/usr/lib/python2.3/urllib2.py", line 359, in error
return self._call_chain(*args)
File "/usr/lib/python2.3/urllib2.py", line 313, in _call_chain
result = func(*args)
File "/usr/lib/python2.3/urllib2.py", line 419, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized lookup.mr814('admin', '54wins') '66.72.200.255'
To me, but maybe this is a copy-n-paste error, it looks like you aren't calling
lookup.mr814() with exactly the same args:
lookup.mr814('username', 'password')
versus
lookup.mr814('admin', '54wins')

?

This is baffling me. Does the webserver ignore the AUTHORIZATION header
on the first request? Should I do something like this:
try:
... lookup.mr814('admin', '54wins')
... except urllib2.HTTPError: #I only want to catch 401 here, but how?
... print "I got back the 401 error. Trying again..."
... lookup.mr814('admin', '54wins')
... except:
... print "something else went wrong."

If that is recommended, how do I distinguish between 401 errors, vs
other errors?


I don't know if it's recommended, but take a look at the source for the
urllib2.HTTPError class, at the definition of __str__ (which is used by the
traceback system):

def __str__(self):
return 'HTTP Error %s: %s' % (self.code, self.msg)

In other words, the actual HTTP error code is in self.code... you could check
for that something like this:

try:
lookup.mr814('admin', '54wins')
except urllib2.HTTPError, err:
if err.code != 401:
raise

Thanks for the help.


I hope the above helps,

/Troels Therkelsen
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Carl Waldbieser | last post by:
**** Post for FREE via your newsreader at post.usenet.com **** When using urllib2.urlopen() on my Windows 2000 machine at work, I was puzzled that I kept getting back authentication errors from...
4
by: Fuzzyman | last post by:
urllib2 (under windows) will auto-detect your proxy settings and use those. Normally that's a good thing (I guess), except when it's not ! How do I switch off this behaviour ? I'm behind a...
2
by: Gerard C Blais | last post by:
I'm trying to get a page from a slow server. and i'm timing out. I've tried socket.setdefaulttimeout9300), and urllib2.socket.setdefaulttimeout(300), and ...
3
by: Aaron | last post by:
I'm trying to learn how the HTTP protocol works. When aserver has many clients accessing it at the same time. Say 200 people. How does it maintain connection with 200 different concurrent client...
1
by: caldera | last post by:
is it possible define custom authorization on specific user control (.ascx) Thank You.
1
by: dgk | last post by:
I'm trying my first website on my home PC and I keep getting a logon screen (part of windows) asking for a username and password when I access it remotely. The with the little face in the username...
3
by: dw | last post by:
I'm a newbie with ASP.NET 1.1. I'm building an application which will allow only 5 or 6 people access (authentication) and they're all on the domain; and only 2 or 3 will have write permission to...
0
by: DT | last post by:
I'm writing a .NET 1.1 client that invokes a method of a Web Service running on another organization's IIS 5 server. I need help understanding a fine point about HTTP, specifically in relation to...
1
by: Nirnimesh | last post by:
I'm using urllib2 module to fetch a URL from a server which understands HTTP/1.1 only (no HTTP/1.0). urllib2.urlopen() results in "urllib2.HTTPError: HTTP Error 505: HTTP Version not supported"....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.