Skip to main content
 首页 » 编程设计

用于连接到 FTP 和下载文件的 Python 2.5 脚本

2025年05月04日11over140

我确信这之前已经解决了,但我似乎找不到类似的问答(新手) 使用 Windows XP 和 Python 2.5,我尝试使用脚本连接到 FTP 服务器并下载文件。它应该很简单但是按照类似脚本的说明我得到了错误:

ftp.login('USERNAME') 
  File "C:\Python25\lib\ftplib.py", line 373, in login 
    if resp[0] == '3': resp = self.sendcmd('PASS ' + passwd) 
  File "C:\Python25\lib\ftplib.py", line 241, in sendcmd 
    return self.getresp() 
  File "C:\Python25\lib\ftplib.py", line 216, in getresp 
    raise error_perm, resp 
error_perm: 530 User USERNAME cannot log in. 

我使用的脚本是:

def handleDownload(block): 
    file.write(block) 
    print ".", 
 
# Create an instance of the FTP object 
# FTP('hostname', 'username', 'password') 
ftp = FTP('servername') 
 
print 'ftplib example' 
# Log in to the server 
print 'Logging in.' 
# You can specify username and password here if you like: 
ftp.login('USERNAME', 'password')  
#print ftp.login() 
 
# This is the directory  
directory = '/GIS/test/data' 
# Change to that directory.   
print 'Changing to ' + directory 
ftp.cwd(directory) 
 
# Print the contents of the directory 
ftp.retrlines('LIST') 

我明白这可能是一个微不足道的问题,但如果有人能提供一些见解,那将非常有帮助!

谢谢你

请您参考如下方法:

我不明白你使用的是哪个库。 Python 标准 urllib2足够了:

import urllib2, shutil 
 
ftpfile = urllib2.urlopen("ftp://host.example.com/path/to/file") 
localfile = open("/tmp/downloaded", "wb") 
shutil.copyfileobj(ftpfile, localfile) 

如果您需要登录(匿名 登录是不够的),请在 url 中指定凭据:

urllib2.urlopen("ftp://user:password@host.example.com/rest/of/the/url")