2023年10月6日 星期五

用Python從FTP伺服器下載檔案

  1. FTP伺服端程式(黃底部份需要視情況變動):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_user("demo", "1234", "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test", perm="elradfmwMT")
authorizer.add_anonymous("C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test")

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(("127.0.0.1", 2121), handler)
server.serve_forever()

2.FTP客戶端程式(黃底部份需要視情況變動):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from ftplib import FTP
import sys, getpass, os.path

host = '127.0.0.1'
port = 2121
timeout = 30
username = 'demo'
password = '1234'
remote_file = 'test6.py'
local_path = '.'  # 下載到目前的工作目錄

ftp = FTP()

try:
    ftp.connect(host, port, timeout)
    ftp.login(username, password)
    remote_file_list = ftp.nlst()  # 列出遠程目錄中的文件

    if remote_file in remote_file_list:
        local_file_path = os.path.join(local_path, remote_file)
        with open(local_file_path, 'wb') as local_file:
            ftp.retrbinary('RETR ' + remote_file, local_file.write)
        print(f'下載 {remote_file} 到 {local_file_path} 完成。')
    else:
        print(f'{remote_file} 不存在於遠程目錄 {remote_path} 中。')

except Exception as e:
    print(f'發生錯誤: {e}')

finally:
    ftp.quit()

沒有留言:

張貼留言