python3使用paramiko下载sftp文件
脚本内容如下:
点击查看代码
# coding: utf-8
import os, re, sys, stat
import paramiko
import autoApiDeamo
def sftp_download(sftp, localDir, remoteDir):
# if remoteDir.find(".") == -1:#判断远程目录参数是否是目录,前提是远程的文件名中都包含扩展名,否则此方法不可用,比较靠谱的方法用下面这个
print('--------')
try:
sftp.stat(remoteDir) # 判断远程目录或文件是否存在
except FileNotFoundError as e:
print(e)
sys.exit()
if stat.S_ISDIR(sftp.stat(remoteDir).st_mode): # 如果sftp服务端的remoterDir是目录,则返回True
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.mkdir(localPath) # 可创建多级目录
try:
print('==sftp文件为:{0}'.format(remoteDir))
print('==下载文件到本地:{0}'.format(localDir))
sftp.get(remoteDir, localDir)
except Exception as e:
print('download exception:', e)
def get_xlsFile(filename):
'''
从固定的sftp服务器上下载文件到当前目录
:paras filename: 下载的文件
:return: None
'''
# sftp信息
host = '10.xx.xx.68'
port = 5555
username = 'root'
password = 'root@123432432'
sftp_dwglpt_path = '/sftpdir'
# 本地文件或目录
localDir = os.path.join(os.getcwd(), filename)
# 远程文件或目录
remoteDir = sftp_dwglpt_path + '/' + filename
sf = paramiko.Transport((host, port))
sf.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(sf)
sftp_download(sftp, localDir, remoteDir)
sf.close()
def update_context(filename, excelfile):
'''
将本地excel文件内容更新到在线表格
:param filename: 本地excel文件
:param excelfile: 在线表格excel文件
:return: true/False
'''
autoApiDeamo.dealwith_data(excelfile, '时间', sheetNum=0)
if __name__ == '__main__':
filename = '2023-06-15-08-51001.xls'
get_xlsFile(filename)
# update_context(filename, excelfile)