【问题标题】:Download a file from https with authentication通过身份验证从 https 下载文件
【发布时间】:2016-05-24 09:27:13
【问题描述】:

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

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

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

【问题讨论】:

标签: python urllib2 python-2.6


【解决方案1】:

如果您可以使用requests 库,那将非常简单。如果可能的话,我强烈推荐使用它:

import requests

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

【讨论】:

  • request.get 在最后一行对我不起作用。我想应该用's'将它更正为requests.get
【解决方案2】:

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

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

【讨论】:

【解决方案3】:

使用 requests 库并将凭据放入您的 .netrc 文件中。

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

【讨论】:

  • 澄清一下:不要提交你的 .netrc 文件,只提交你的代码
猜你喜欢
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多