繁体   English   中英

Python 处理 URL 的用户名和密码

[英]Python handling username and password for URL

弄乱 Python,我正在尝试使用这个https://updates.opendns.com/nic/update?hostname= ,当你到达 URL 时,它会提示用户名和密码。 我一直在四处寻找,发现了一些关于密码管理器的东西,所以我想出了这个:

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())

这一切都有效,但它通过命令行提示用户名和密码,需要用户的交互。 我希望它自动输入这些值。 我究竟做错了什么?

您可以改用请求 代码很简单:

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

您的请求网址是“受限制的”。

如果您尝试此代码,它会告诉您:

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']

您应该添加授权标头。 有关详细信息,请查看: http//www.voidspace.org.uk/python/articles/authentication.shtml

另一个代码示例是: http//code.activestate.com/recipes/305288-http-basic-authentication/

如果您想发送POST请求,请尝试:

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

注意:这只是如何将POST请求发送到URL的示例。

我有一段时间没有玩python,但试试这个:

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

如果你像我一样需要Digest Auth ,我建议使用“请求”内置方法requests.auth.HTTPDigestAuth

import requests

resp = requests.get("http://myserver.com/endpoint",
                    auth=requests.auth.HTTPDigestAuth("username", "password"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM