【问题标题】:Python handling username and password for URLPython 处理 URL 的用户名和密码
【发布时间】:2023-08-23 03:18:01
【问题描述】:

搞砸了 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())

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

【问题讨论】:

    标签: python passwords urllib2


    【解决方案1】:

    您可以改用requests。代码很简单:

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

    【讨论】:

    • 您好,在编译上面的sn-p时,出现错误:b'{"error_code":401,"error":"authentication_required","error_message":"请登录后继续."}'
    • @NoobGeek 如果用户名/密码与服务器期望的不匹配,您将收到 401 响应。如果您使用了这个确切的示例(url + 凭据),我很确定您会得到 401(因为这些凭据是为了示例的目的而编造的)。
    【解决方案2】:

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

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

    【讨论】:

    • 是的,python 不喜欢因为符号...
    • 这是一种不安全的添加到脚本的方法,因为密码是开放给读者查看的。然而,这对于我在内部网络上运行的一些脚本来说就像一个魅力。
    【解决方案3】:

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

    如果你尝试这段代码,它会告诉你:

    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
    

    注意:这只是一个如何向 URL 发送 POST 请求的示例。

    【讨论】:

    • @AnthonyHonciano 注意用户名和密码(字典键)应该是您输入元素的名称。你的表格有其他字段吗?您可以将表单代码粘贴到您的状态中吗? (更新您的状态)。 401 表示未经授权。
    • 没有形式,就是这样。我只是在为自己构建一个个人更新器应用程序。所以我会让脚本像这样运行我运行python脚本。也是的,我知道“用户名和密码”需要与实际帐户信息不同。
    • @AnthonyHonciano 我更新了我的帖子。请检查一下。希望它能解决你的问题;)
    • 完美完美完美!!!与你相比,带有 base64 的顶部就像一个魅力!