import paramiko import os import datetime from stat import S_ISDIR as isdir def down_from_remote(sftp_obj, remote_dir_name, local_dir_name): """遠程下載文件""" remote_file = sftp_obj.stat(remote_dir_name) if isdir(remote_file.st_mode): # 文件夾,不能直接下載,需要繼續循環 check_local_dir(local_dir_name) print('開始下載文件夾:' + remote_dir_name) for remote_file_name in sftp.listdir(remote_dir_name): sub_remote = os.path.join(remote_dir_name, remote_file_name) sub_remote = sub_remote.replace('\\', '/') sub_local = os.path.join(local_dir_name, remote_file_name) sub_local = sub_local.replace('\\', '/') down_from_remote(sftp_obj, sub_remote, sub_local) else: # 文件,直接下載 print('開始下載文件:' + remote_dir_name) sftp.get(remote_dir_name, local_dir_name) def check_local_dir(local_dir_name): """本地文件夾是否存在,不存在則創建""" if not os.path.exists(local_dir_name): os.makedirs(local_dir_name) if __name__ == "__main__": """程序主入口""" # 服務器連接信息 host_name = '你的端口' user_name = '你的用戶名' password = '你的密碼' port = 22 # 遠程文件路徑(需要絕對路徑) remote_dir = '/home/zhengquan/tumaoOffice/wpsweb-demo-nodejs/dir' # 本地文件存放路徑(絕對路徑或者相對路徑都可以) local_dir = 'D:\\ServerFile\\'+str(datetime.date.today()) # 連接遠程服務器 t = paramiko.Transport((host_name, port)) t.connect(username=user_name, password=password) sftp = paramiko.SFTPClient.from_transport(t) # 遠程文件開始下載 down_from_remote(sftp, remote_dir, local_dir) # 關閉連接 t.close()