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_us er, 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("B asic " +
base64.encodest ring("%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.HTTPErr or. But
then If I ran the exact same script again afterward, I get access. lookup.mr814('u sername', '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(ur l, 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(ht tplib.HTTP, req)
File "/usr/lib/python2.3/urllib2.py", line 843, in do_open
return self.parent.err or('http', req, fp, code, msg, hdrs)
File "/usr/lib/python2.3/urllib2.py", line 359, in error
return self._call_chai n(*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_defa ult
raise HTTPError(req.g et_full_url(), code, msg, hdrs, fp)
urllib2.HTTPErr or: HTTP Error 401: Unauthorized lookup.mr814('a dmin', '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('a dmin', '54wins')
.... except urllib2.HTTPErr or: #I only want to catch 401 here, but how?
.... print "I got back the 401 error. Trying again..."
.... lookup.mr814('a dmin', '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 3957
In article <sl************ *****@overlook. homelinux.net>, Matthew Wilson wrote:
[snip] lookup.mr814('u sername', '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(ur l, 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(ht tplib.HTTP, req) File "/usr/lib/python2.3/urllib2.py", line 843, in do_open return self.parent.err or('http', req, fp, code, msg, hdrs) File "/usr/lib/python2.3/urllib2.py", line 359, in error return self._call_chai n(*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_defa ult raise HTTPError(req.g et_full_url(), code, msg, hdrs, fp) urllib2.HTTPErr or: HTTP Error 401: Unauthorized lookup.mr814('a dmin', '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('u sername', 'password')
versus
lookup.mr814('a dmin', '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('a dmin', '54wins') ... except urllib2.HTTPErr or: #I only want to catch 401 here, but how? ... print "I got back the 401 error. Trying again..." ... lookup.mr814('a dmin', '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.HTTPErr or 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('a dmin', '54wins')
except urllib2.HTTPErr or, 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 our Internet
proxy server (I was trying to contact an internal machine). Upon digging
into the code a little, I found that urllib2 was pulling the proxy
information out of the Windows registry (Internet Explorer uses these
settings). However,...
|
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 censoring proxy and
wanting to test things *locally*. IE is set to not use the proxy when
fetching local adresses, but urllib2 ignores that part of the setting
and uses the proxy for everything.
|
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
urllib2.socket.setdefauttimeout(300.0),
|
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 using only port 80? From
what I've read and if I understand this correctly, a TCP/UDP port a maintain
connection with one client at a time. Can someone explain it to me? I
believe FTP works the same way right?
Thanks in advance
Aaron
|
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 screen.
How do I have to set it up so that users won't get that? I can't even
figure out what username and password will work.
I'm trying this using http://nnn.nnn.nnn.nnn/dotnetnuke. (nnn to keep
the address a secret for now) Oh, I just...
|
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 the SQL Server 2000 on the
pages (authorization). What's the best way to do this (least amount of
maintenance if users get added/removed)? Thanks.
|
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 the use of the Expect:
100-Continue header, in order to determine whether the problem is with my
client or their server.
Here's the situation:
After invoking the web service successfully one time, all subsequent
requests then fail. Using...
|
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".
How do I force urllib2 to use HTTP v1.1?
Regards,
Nirnimesh
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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 then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |