使用ftp下载文件

时间:2014-11-09 09:12:58

标签: python ftp

我正在编写一个python脚本,以便使用ftp登录并下载文件。但是每当我运行此脚本时,它说我提供了错误的用户名或passwd。我输入正确的密码仍然无法运行此script.My代码是:

    import os,getpass
    from urllib.request import urlopen
    filename='68544.jpg'
    password=getpass.getpass('??')

在下面的这一行,脚本无法运行,每当我在浏览器中运行此地址时,它运行正常。

    remoteaddr='ftp://Kamal:%s@localhost/%s;type=i'%(password,filename)
    remotefile=urlopen(remoteaddr)
    localfile=open(filename,'wb')
    localfile.write(remotefile.read())
    localfile.close()
    remotefile.close()

2 个答案:

答案 0 :(得分:0)

    def ftp_connect(path):
         link = FTP(host = 'example.com', timeout = 5) #Keep low timeout
         link.login(passwd = 'ftppass', user = 'ftpuser')
         debug("%s - Connected to FTP" % strftime("%d-%m-%Y %H.%M"))
         link.cwd(path)
         return link

    downloaded = open('/local/path/to/file.tgz', 'wb')
    def debug(txt):
         print txt

    link = ftp_connect(path)
    file_size = link.size(filename)
    max_attempts = 5 #I dont want death loops.
    while file_size != downloaded.tell():
      try:
            debug("%s while > try, run retrbinary\n" % strftime("%d-%m-%Y %H.%M"))
            if downloaded.tell() != 0:
                   link.retrbinary('RETR ' + filename, downloaded.write, downloaded.tell())
            else:
                   link.retrbinary('RETR ' + filename, downloaded.write)
      except Exception as myerror:
            if max_attempts != 0:
                 debug("%s while > except, something going wrong: %s\n \tfile lenght is: %i > %i\n"(strftime("%d-%m-%Y %H.%M"), myerror, file_size, downloaded.tell()))
                 link = ftp_connect(path)
                 max_attempts -= 1
            else:
                 break
      debug("Done with file, attempt to download m5dsum")

[...]

答案 1 :(得分:0)

使用Paramiko库

import paramiko
paramiko.util.log_to_file('/tmp/paramiko.log')

# Open a transport

host = "example.com"
port = 22
transport = paramiko.Transport((host, port))

# Auth

password = "foo"
username = "bar"
transport.connect(username = username, password = password)

# Go!

sftp = paramiko.SFTPClient.from_transport(transport)

# Download

### It is relative path from the folder path on which this sftp user has default rights.
filepath = 'folder/file1.txt'           
localpath = '/opt/backup/file.txt'
sftp.get(filepath, localpath)

# Close

sftp.close()
transport.close()