Search code examples
pythonpasswordsurllib2

Python handling username and password for URL


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?


Solution

  • 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.