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

时间:2011-02-25 11:08:55

标签: python ftp

我确信此问题已经解决,但我似乎无法找到类似的Q& A(新手) 使用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')

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

谢谢,S

3 个答案:

答案 0 :(得分:5)

我无法理解您使用的是哪个库。 Python标准urllib2就足够了:

import urllib2, shutil

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

如果您需要登录(匿名登录还不够),请在网址中指定凭据:

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

答案 1 :(得分:4)

ftp.login('USERNAME', 'password') 

将其替换为真实数据。根据错误,您尝试使用密码“password”登录为“USERNAME”,这显然无效。

另外,将servername中的ftp = FTP('servername') 替换为您要连接的服务器的主机名。

答案 2 :(得分:-1)

第一个简单的检查是打开一个交互式会话(即使用相同的凭据自己ftp到这个服务器),以确保这不是权限问题..

另一个失败的原因是,在连接到MS ftp服务器时,您可能需要将用户名设为 domain \ username

也许这有帮助?

相关问题