從 Linux 服務(wù)器上遞歸下載文件夾下所有文件
本文將介紹如何使用Python從Linux服務(wù)器上遞歸下載文件夾下的所有文件。我們將使用paramiko庫來實現(xiàn)SSH連接,以及os和shutil庫來處理文件和目錄。如果你還沒有安裝paramiko庫,請先使用以下命令安裝:
pip install paramiko
1. 創(chuàng)建SSH連接
首先創(chuàng)建一個SSH連接到Linux服務(wù)器:
import paramiko
def create_ssh_client(hostname, port, username, password):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password)
return client
2. 遞歸下載文件夾下的所有文件
編寫一個函數(shù)來遞歸下載文件夾下的所有文件。這個函數(shù)將接收一個SSH客戶端對象、一個遠程文件夾路徑和一個本地保存路徑作為參數(shù)。
import os
import shutil
def download_folder(ssh_client, remote_folder, local_folder):
# 在遠程服務(wù)器上創(chuàng)建本地文件夾(如果不存在)
sftp = ssh_client.open_sftp()
sftp.mkdir(local_folder) if not os.path.exists(local_folder) else None
sftp.close()
# 在遠程服務(wù)器上獲取文件夾列表
stdout, _ = ssh_client.exec_command(f"ls -lR {remote_folder}")
folder_list = [line.split()[-1] for line in stdout.readlines()]
# 遍歷文件夾列表并遞歸下載每個文件
for file in folder_list:
remote_file = f"{remote_folder}/{file}"
local_file = f"{local_folder}/{file}"
sftp.get(remote_file, local_file) if os.path.isfile(remote_file) else None
download_folder(ssh_client, remote_file, local_file) if os.path.isdir(remote_file) else None
3. 使用示例
整體調(diào)用這些函數(shù)來從Linux服務(wù)器上遞歸下載文件夾下的所有文件。假設(shè)我們的服務(wù)器地址為example.com,端口為22,用戶名為user,密碼為password,我們想要下載的遠程文件夾為/remote/folder,并將其保存到本地的/local/folder中。
if __name__ == "__main__":
hostname = "example.com"
port = 22
username = "user"
password = "password"
remote_folder = "/remote/folder"
local_folder = "/local/folder"
ssh_client = create_ssh_client(hostname, port, username, password)
download_folder(ssh_client, remote_folder, local_folder)
運行上述代碼后,在本地的/local/folder中可以看到遠程服務(wù)器上的/remote/folder文件夾及其內(nèi)容。