#!/usr/bin/python
# coding=utf-8
import paramiko
import os
def sftp_download(sftp,localDir,remoteDir):
if remoteDir.find(".") == -1:#判斷遠(yuǎn)程目錄參數(shù)是否是目錄,前提是遠(yuǎn)程的文件名中都包含擴(kuò)展名,否則此方法不可用
for file in sftp.listdir(remoteDir):
remoteDirTmp=os.path.join(remoteDir,file)
localDirTmp=os.path.join(localDir,file)
sftp_download(sftp,localDirTmp,remoteDirTmp)
else:
localPath=localDir.rpartition("/")[0]
if not os.path.exists(localPath):
os.makedirs(localPath)
print("download file:",remoteDir)
try:
sftp.get(remoteDir,localDir)
except Exception as e:
print('download exception:',e)
if __name__ == '__main__':
host = '192.168.149.128'#sftp主機(jī)
port = 22 #端口
username = 'sftp' #sftp用戶名
password = '123456'
localDir = '/data/test'#本地文件或目錄
remoteDir = '/'#遠(yuǎn)程文件或目錄
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
sftp_download(sftp,localDir,remoteDir)
sf.close()