使用身份验证从 https 下载文件

Download a file from https with authentication

我有一个 Python 2.6 脚本,可以从网络服务器下载文件。我希望此脚本传递用户名和密码(用于在获取文件之前进行身份验证)并且我将它们作为 url 的一部分传递,如下所示:

import urllib2
response = urllib2.urlopen("http://'user1':'password'@server_name/file")

但是,在这种情况下我遇到了语法错误。这是正确的方法吗?我对 Python 和一般编码还很陌生。 有人可以帮帮我吗? 谢谢!

我想您正在尝试通过基本身份验证。这种情况,你可以这样处理:

import urllib2

username = 'user1'
password = '123456'

#This should be the base url you wanted to access.
baseurl = 'http://server_name.com'

#Create a password manager
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, baseurl, username, password)

#Create an authentication handler using the password manager
auth = urllib2.HTTPBasicAuthHandler(manager)

#Create an opener that will replace the default urlopen method on further calls
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)

#Here you should access the full url you wanted to open
response = urllib2.urlopen(baseurl + "/file")

如果您可以使用 requests 库,那就太简单了。如果可能,我强烈建议使用它:

import requests

url = 'http://somewebsite.org'
user, password = 'bob', 'I love cats'
resp = requests.get(url, auth=(user, password))

使用请求库并将凭据放入 .netrc 文件中。

库将从那里加载它们,您将能够将代码提交给您选择的 SCM,而无需担心任何安全问题。