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. 1 3908
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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
...
|
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...
|
by: caldera |
last post by:
is it possible define custom authorization on specific user control (.ascx)
Thank You.
|
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...
|
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...
|
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...
|
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"....
|
by: lllomh |
last post by:
Define the method first
this.state = {
buttonBackgroundColor: 'green',
isBlinking: false, // A new status is added to identify whether the button is blinking or not
}
autoStart=()=>{
|
by: Aliciasmith |
last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
|
by: giovanniandrean |
last post by:
The energy model is structured as follows and uses excel sheets to give input data:
1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
|
by: NeoPa |
last post by:
Hello everyone.
I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report).
I know it can be done by selecting :...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
|
by: isladogs |
last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, Mike...
|
by: GKJR |
last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
|
by: SueHopson |
last post by:
Hi All,
I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...
| |