如何使用urllib2使用带身份验证的代理访问ftp/http服务器

2024-04-23 15:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:查看我的解决方案的注释。在

我的python代码使用urllib2通过带有用户和密码的代理访问FTP服务器。我使用urllib2.ProxyHandlerurllib2.ProxyBasicAuthHandler来实现这一点,方法是遵循urllib2 examples

1 import urllib2
2 proxy_host = 'host.proxy.org:3128'  # only host name, no scheme (http/ftp)
3 proxy_handler = urllib2.ProxyHandler({'ftp': proxy_host}) 
4 proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
5 proxy_auth_handler.add_password(None, proxy_host, proxy_user, proxy_passwd)
6 opener_thru_proxy = urllib2.build_opener(proxy_handler, proxy_auth_handler)
7 conn = opener_thru_proxy.open('ftp://ftp.ftpserver.org/targetfile.txt')
8 print conn.read()

代码在第7行停止。在

错误消息包括:

^{pr2}$

我通过定义env变量ftp_proxy测试了代理服务器,并使用

wget --proxy-user=proxy_user --proxy-password=proxy_passwd ftp://ftp.ftpserver.org/targetfile.txt

它成功地从ftp服务器下载了文件。在

如何改进代码以使用带身份验证的代理访问ftp站点?在


Tags: 代码org服务器authhost代理ftppassword