ftplib 实例

#!/usr/bin/env python

import ftplib
import os

class FTPSync(object):
    def __init__(self,host,username, password, ftp_base_dir,
                            local_base_dir, delete=False):
        self.host = host
        self.username = username
        self.password = password
        self.ftp_base_dir = ftp_base_dir
        self.local_base_dir = local_base_dir
        self.delete = delete
        self.conn = ftplib.FTP(host, username, password)
        self.conn.cwd(ftp_base_dir)
        try:
            os.makedirs(local_base_dir)
        except OSError:
            pass
        os.chdir(local_base_dir)

    def get_dirs_files(self):
        dir_res = []
        self.conn.dir('.', dir_res.append)
        for f in dir_res:
            print f
        files= [ f.split(None, 8)[-1] for f in dir_res if f.startswith('-')]
        dirs = [ f.split(None, 8)[-1] for f in dir_res if f.startswith('d')]
        return (files, dirs)
    
    def walk(self, next_dir):
        print "walking to", next_dir
        self.conn.cwd(next_dir)
        try:
            os.mkdir(next_dir)
        except OSError:
            pass
        os.chdir(next_dir)

        ftp_curr_dir = self.conn.pwd()
        local_curr_dir = os.getcwd()

        files, dirs = self.get_dirs_files()
        print "FILES:", files
        print "DIRS:", dirs
        for f in files:
            print next_dir, ':', f
            outf = open(f,'wb')
            try:
                self.conn.retrbinary('RETR %s' % f, outf.write)
            finally:
                outf.close()
            if False:
                print self.delete
                print "Deleting",f
                self.conn.delete(f)
        for d in dirs:
            os.chdir(local_curr_dir)
            self.conn.cwd(ftp_curr_dir)
            self.walk(d)

    def run(self):
        self.walk('.')

if __name__ == '__main__':
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-o","--host", dest="host",
            action='store', help ="FTP host")
    parser.add_option("-u","--username",dest="username",
            action ='store', help = "FTP username")
    parser.add_option("-p","--password",dest="password",
            action = 'store', help = "FTP password")
    parser.add_option("-r","--remote_dir",dest = "remote_dir",
            action = 'store', help = "FTP remote starting directory")
    parser.add_option("-l", "--local_dir",dest = "local_dir",
            action = 'store', help = "Local starting directory")
    parser.add_option("-d", "--delete",dest = "delete",default = False,
            action = 'store_true', help= "use regex parser")
    (options, args) = parser.parse_args()
    f = FTPSync(options.host, options.username, options.password,options.remote_dir, options.local_dir, options.delete)
    f.run()

在命令行输入:

./ftpimage.py -o localhost -u hzhida -p password -r lighttpd-1.4.31 -l python -d False


FTP Library Routines Release 4.0 Thomas Pfau (tfpfau@gmail.com) June 7, 2013 This package implements a callable interface to FTP. The FTP protocol is specified in RFC 959. The library has been tested on linux, OpenVMS and Windows NT. It should also work without major modification on other POSIX systems. All programs using the library should include ftplib.h. FTP开源库。 Miscellaneous Functions FtpInit() - Initialize the library FtpSite() - Send a 'SITE' command FtpLastResponse() - Retrieve last server response FtpSysType() - Determine remote system type FtpSize() - Determine size of remote file FtpSizeLong() - Determine size of remote file FtpModDate() - Determine modification time of file FtpSetCallback() - Establish a callback function FtpClearCallback() - Remove a callback function Server Connection FtpConnect() - Connect to a remote server FtpLogin() - Login to remote machine FtpQuit() - Disconnect from remote server FtpOptions() - Set Connection Options Directory Functions FtpChdir() - Change working directory FtpMkdir() - Create a directory FtpRmdir() - Remove a directory FtpDir() - List a remote directory FtpNlst() - List a remote directory FtpCDUp() - Change to parent directory FtpPwd() - Determine current working directory File to File Transfer FtpGet() - Retreive a remote file FtpPut() - Send a local file to remote FtpDelete() - Delete a remote file FtpRename() - Rename a remote file File to Program Transfer These routines allow programs access to the data streams connected to remote files and directories. FtpAccess() - Open a remote file or directory FtpRead() - Read from remote file or directory FtpWrite() - Write to remote file FtpClose() - Close data connection Utilities qftp - Command line ftp utility
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值