实现功能: 利用python自动连接sftp,并实现本地文件(文件夹)自动上传到远程sftp服务中指定路径下,且保持本地目录结构
系统环境:centos7
python版本:python3
使用模块包:paramiko ,若未安装,可使用 pip install paramiko 进行安装
难点分析:
(1)sftp.put(localfile,remotefile) 函数必须是两个文件名,且sftp远端的文件路径要存在,因此需要提前创建好目录
(2)sftp.mkdir() 函数只能创建一级目录,不能循环创建多级目录,本文通过一级一级获取本地路径,然后判断远程路径是否存在,若不存在就创建好,由此来保证上传的文件能够在sftp远端找到对应的目录
(3)用到的重点函数有 sftp.mkdir 、sftp.stat,更多函数可参见帮助文档:https://docs.paramiko.org/en/stable/api/sftp.html
(4)关于sftp文件下载的方法,参考博文:https://blog.csdn.net/d1240673769/article/details/106295184
(5)关于sftp文件上传和下载,另一种最简单的方法就是利用 shell脚本,lftp工具,详情参考:https://blog.csdn.net/d1240673769/article/details/106307421
实现代码:
import paramiko
import os
import stat
def create_dir(sftp,remoteDir):
try:
if stat.S_ISDIR(sftp.stat(remoteDir).st_mode):
pass
except Exception as e:
sftp.mkdir(remoteDir)
print("在远程sftp上创建目录:{}".format(remoteDir))
def sftp_upload(sftp,localDir,remoteDir):
if os.path.isdir(localDir):
for file in os.listdir(localDir):
remoteDirTmp=os.path.join(remoteDir,file)
localDirTmp=os.path.join(localDir,file)
if os.path.isdir(localDirTmp):
create_dir(sftp,remoteDirTmp)
sftp_upload(sftp,localDirTmp,remoteDirTmp)
else:
print("upload file:",localDir)
try:
sftp.put(localDir,remoteDir)
except Exception as e:
print('upload error:',e)
if __name__ == '__main__':
host = '192.168.149.153'
port = 22
username = 'sftpuser'
password = 'passwd'
localDir = '/test/sftp'
remoteDir = '/sftp'
sf = paramiko.Transport((host,port))
sf.connect(username = username,password = password)
sftp = paramiko.SFTPClient.from_transport(sf)
sftp_upload(sftp,localDir,remoteDir)
sf.close()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)