Python 使用身份验证从 https 下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35376005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a file from https with authentication
提问by user3262537
I have a Python 2.6 script that downloades a file from a web server. I want this this script to pass a username and password(for authenrication before fetching the file) and I am passing them as part of the url as follows:
我有一个从 Web 服务器下载文件的 Python 2.6 脚本。我希望此脚本传递用户名和密码(用于在获取文件之前进行身份验证),并将它们作为 url 的一部分传递,如下所示:
import urllib2
response = urllib2.urlopen("http://'user1':'password'@server_name/file")
However, I am getting syntax error in this case. Is this the correct way to go about it? I am pretty new to Python and coding in general. Can anybody help me out? Thanks!
但是,在这种情况下我收到语法错误。这是正确的方法吗?我对 Python 和编码很陌生。有人可以帮我吗?谢谢!
采纳答案by Arton Dorneles
I suppose you are trying to pass through a Basic Authentication. In this case, you can handle it this way:
我想您正在尝试通过基本身份验证。在这种情况下,您可以这样处理:
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")
回答by willnx
回答by sorin
Use requests library and just put the credentials inside your .netrc file.
使用请求库并将凭据放入您的 .netrc 文件中。
The library will load them from there and you will be able to commit the code to your SCM of choice without any security worries.
该库将从那里加载它们,您将能够将代码提交到您选择的 SCM,而无需担心任何安全问题。