#!/usr/bin/python
# coding=utf-8
import paramiko
import os
def sftp_download(sftp,localDir,remoteDir):
if remoteDir.find(".") == -1:#判断远程目录参数是否是目录,前提是远程的文件名中都包含扩展名,否则此方法不可用
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主机
port = 22 #端口
username = 'sftp' #sftp用户名
password = '123456'
localDir = '/data/test'#本地文件或目录
remoteDir = '/'#远程文件或目录
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
sftp_download(sftp,localDir,remoteDir)
sf.close()