Question

Messing with Python and I'm trying to use this https://updates.opendns.com/nic/update?hostname=, when you got to the URL it will prompt a username and password. I've been looking around and I found something about password managers, so I came up with this:

urll = "http://url.com"
username = "username"
password = "password"

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()

passman.add_password(None, urll, username, password)

authhandler = urllib2.HTTPBasicAuthHandler(passman)

urllib2 = urllib2.build_opener(authhandler)

pagehandle = urllib.urlopen(urll)

print (pagehandle.read())

This all works, but it's prompting the username and password via the command line, requiring the user's interaction. I want it to automatically enter those values. What am I doing wrong?

Was it helpful?

Solution 2

Your request url is "RESTRICTED".

If you try this code it will tell you:

import urllib2
theurl = 'https://updates.opendns.com/nic/update?hostname='
req = urllib2.Request(theurl)
try:
    handle = urllib2.urlopen(req)
except IOError, e:
    if hasattr(e, 'code'):
        if e.code != 401:
            print 'We got another error'
            print e.code
        else:
            print e.headers
            print e.headers['www-authenticate']

You should add authorization headers. For more details have a look into: http://www.voidspace.org.uk/python/articles/authentication.shtml

And another code example is: http://code.activestate.com/recipes/305288-http-basic-authentication/

If you wish to send POST request , try it:

import urllib
import urllib2
username = "username"
password = "password"
url = 'http://url.com/'
values = { 'username': username,'password': password }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
print result

Note: this is just an example of how to send POST request to URL.

OTHER TIPS

You could use requests instead. The code is as simple as:

import requests
url = 'https://updates.opendns.com/nic/update?hostname='
username = 'username'
password = 'password'
print(requests.get(url, auth=(username, password)).content)

I haven't played with python in awhile, but try this:

urllib.urlopen("http://username:password@host.com/path")

If you like me need Digest Auth, I recommend using "requests" builtin method requests.auth.HTTPDigestAuth:

import requests

resp = requests.get("http://myserver.com/endpoint",
                    auth=requests.auth.HTTPDigestAuth("username", "password"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top