繁体   English   中英

使用ftp下载文件

[英]downloading file using ftp

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

    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()
    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")

[...]

使用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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM