使用身份验证从 https 下载文件 [英] Download a file from https with authentication

查看:29
本文介绍了使用身份验证从 https 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

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!

推荐答案

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

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

这篇关于使用身份验证从 https 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆