0

更新:查看我的解决方案的评论。

我的 python 代码用于urllib2通过具有用户名和密码的代理访问 FTP 服务器。我通过以下urllib2 示例使用 aurllib2.ProxyHandler和 aurllib2.ProxyBasicAuthHandler来实现这一点:

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 行停止。

错误消息是:

    conn = urllib2.urlopen(remote_fn)           
  File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.6/urllib2.py", line 391, in open
    response = self._open(req, data)
  File "/usr/lib/python2.6/urllib2.py", line 409, in _open
    '_open', req)
  File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.6/urllib2.py", line 1344, in ftp_open
    fw = self.connect_ftp(user, passwd, host, port, dirs, req.timeout)
  File "/usr/lib/python2.6/urllib2.py", line 1365, in connect_ftp
    fw = ftpwrapper(user, passwd, host, port, dirs, timeout)
  File "/usr/lib/python2.6/urllib.py", line 856, in __init__
    self.init()
  File "/usr/lib/python2.6/urllib.py", line 862, in init
    self.ftp.connect(self.host, self.port, self.timeout)
  File "/usr/lib/python2.6/ftplib.py", line 134, in connect
    self.welcome = self.getresp()
  File "/usr/lib/python2.6/ftplib.py", line 209, in getresp
    resp = self.getmultiline()
  File "/usr/lib/python2.6/ftplib.py", line 195, in getmultiline
    line = self.getline()
  File "/usr/lib/python2.6/ftplib.py", line 185, in getline
    if not line: raise EOFError
urllib2.URLError: <urlopen error ftp error: >

我已经通过定义 env 变量ftp_proxy并使用访问 ftp 文件来测试代理服务器

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

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

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

4

0 回答 0