本文主要介绍Python中ftplib库使用示例代码,包括连接ftp,上传,下载,创建文件夹,获取文件大小等操作。

1、验证ftp是否能登陆成功

def ValidateLogin(ipaddr, userName, passWord):
    userName = userName.replace("\n","")
    passWord = passWord.replace("\n","")
    try:
        print "-"*12
        print "User:",userName,"Password:",passWord
        ftp = FTP(ipaddr)
        ftp.login(userName,passWord)
        ftp.retrlines('LIST')
        print "\t\n[!] Login successful:",userName, passWord
        ftp.quit()
        sys.exit(2)
    except (ftplib.all_errors), msg: 
        #print "[-] An error occurred:", msg
        pass 

2、尝试登陆ftp服务器

def try_login(custom_users, custom_passwords, host, port):
    for user in custom_users:
        for password in custom_passwords:
            try:
                con = ftplib.FTP(timeout=3.5)
                con.connect(host, port)
                ans = con.login(user,password)
                if "230" in ans:
                    anon_login = "Success ({} - {})".format(user, password)
                    dir_listing = get_directory_listing(con)
                    return (anon_login, dir_listing)
                else:
                    con.quit()
                    con.close()
                    continue
            except socket.timeout:
                anon_login = "Timed out"
                return (anon_login, None)
            except Exception as e:
                anon_login = "Disallowed"
    return (anon_login, None) 

3、在ftp上创建文件夹

def create_folder(folder,hostname, username, password):
        try:
            folder = xbmc.makeLegalFilename(folder)
            control.makeFile(folder)
            try:
                if not 'ftp://' in folder: raise Exception()
                from ftplib import FTP
                ftp = FTP(host=hostname, user=username, passwd=password)
                try:
                    ftp.cwd(folder)
                except:
                    ftp.mkd(folder)
                ftp.quit()
            except:
                pass
        except:
            pass 

4、上传文件到ftp

def upload( project_name, filename,server_host,ftp_port,dst_filename = None):
        if dst_filename == None:
            dst_filename = os.path.split(filename)[-1]
        ftp = FTP()
        ftp.connect(server_host, ftp_port)
        ftp.login()
        filename_to_write_to = os.path.join(project_name, dst_filename)
        ftp.storbinary('STOR ' + filename_to_write_to, open(filename, 'rb'))
        ftp.close()
        return "uploaded" 

5、列出path路径的所有子路径

def list_children(self, path):
        """
     生成给定的root相对路径的所有直接子路径,如root相对路径。如果路径引用一个文件,则没有子文件。
        """        
        if len(path) > 0 and not path.endswith("/"):
            #我们需要在urljoin的实际目录名后面加上一个斜杠
            path = path + "/"
        path = path.lstrip("/")      
        #在FTP server上的实际路径 
        ftp_path = urlparse.urljoin(self.base_path, path)
      
        Logger.debug("Listing {}".format(ftp_path))
        
        for child in robust_nlst(self.connection, ftp_path):
            #对于每个子路径 , 生成相对root的URL
            yield urlparse.urljoin(path, child) 

6、获取ftp server上文件大小

def ftp_size(host_name, path):
    from ftplib import FTP
    try:
        ftp = FTP(host_name)
    except Exception as e:
        print(e)
        return -1
    try:
        ftp.login()
        ftp.voidcmd('TYPE I')
        size = ftp.size(path)
        ftp.quit()
    except Exception as e:
        print(e)
        return 0
    return size 

7、从ftp server上下载文件

def download(self, project_name, filename):
        if dst_filename == None:
            dst_filename = os.path.split(filename)[-1]
        ftp = FTP()
        ftp.connect(self.server_host, self.ftp_port)
        ftp.login()
        handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
        ftp.retrbinary('RETR %s' % filename, handle.write)
        ftp.close()
        return "uploaded"