python ftp遞歸下載目錄

1.源碼實現

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from ftplib import FTP
from pathlib import Path
import re
import os
import sys

def nlstall(ftp, path, res):
    nlst = ftp.nlst(path)

    for file in nlst:
        if not file in res:
            res.add(file)
            num = len(res)
            nlstall(ftp, file, res)
            #print("------------")
            #print(num)
            #print(len(res))
            #print("------------")

            if len(res) != num:
                res.remove(file)

def get_file(ftp, path, local):

    dirname = os.path.dirname(path)
    filename = os.path.basename(path)
    path = local + dirname;

    #print(dirname)
    #print(filename)

    if not Path(path).is_dir():
        os.makedirs(path)

    path = path + "/" + filename;

    file2 = open(path, 'wb')

    ftp.retrbinary('RETR ' + path, file2.write, blocksize=1024)

    file2.close();

#文件夾處理邏輯
def get_remote_files(ftp, paths, local):
    for path in paths:
        get_file(ftp, path, local)

ftp = FTP(sys.argv[1])

ftp.login(sys.argv[2], sys.argv[3])

ftp.set_pasv(False)

ftp.cwd('/')

nlst = set()

nlstall(ftp, sys.argv[4], nlst)

get_remote_files(ftp, nlst, ".");

ftp.quit()

2.測試及其運行結果

$ python3 get_mail_from_ftp.py 192.168.137.135 amy1 amy1 /home/amy1/ftp
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章