#!/usr/bin/python
# coding=utf-8
import paramiko
import os
def sftp_upload(host, port, username, password, local, remote):
sf = paramiko.Transport((host, port))
sf.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local): # 判断本地参数是目录还是文件
for f in os.listdir(local): # 遍历本地目录
local_path = os.path.join(local + f)
local_path = local_path.replace('/', '\\') # 转为Windows标准路径
remote_path = os.path.join(remote + f)
remote_path = remote_path.replace('\\', '/') # 转为linux标准路径
try:
sftp.stat(remote_path)
except IOError:
sftp.mkdir(remote_path)
for local_file in os.listdir(local_path):
local_file_path = os.path.join(local_path , local_file)
remote_file_path = os.path.join(remote_path,local_file)
remote_file_path = remote_file_path.replace('\\', '/') # 转为linux标准路径
try:
sftp.stat(remote_file_path)
except IOError:
print("====",local_file_path,remote_file_path)
sftp.put(local_file_path, remote_file_path) # 上传目录中的文件
else:
sftp.put(local, remote) # 上传文件
except Exception as e:
print('upload exception:',e)
sf.close()
def sftp_download(host, port, username, password, local, remote):
sf = paramiko.Transport((host, port))
sf.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local): # 判断本地参数是目录还是文件
for f in sftp.listdir(remote): # 遍历远程目录
local_path = os.path.join(local , f)
local_path = local_path.replace('/', '\\') # 转为Windows标准路径
if not os.path.isdir(local_path):
os.mkdir(local_path)
remote_path = os.path.join(remote , f)
remote_path = remote_path.replace('\\', '/') # 转为linux标准路径
for remote_file in sftp.listdir(remote_path):
remote_file_path = os.path.join(remote_path , remote_file)
remote_file_path = remote_file_path.replace('\\', '/') # 转为linux标准路径
local_file_path = os.path.join(local_path , remote_file)
local_file_path = local_file_path.replace('/', '\\') # 转为Windows标准路径
if not os.path.exists(local_file_path):
print("111====",remote_file_path,local_file_path)
sftp.get(remote_file_path, local_file_path) # 下载目录中文件
else:
sftp.get(remote, local) # 下载文件
except Exception as e:
print('download exception:',e)
sf.close()
if __name__ == '__main__':
host = '172.16.1.58' # 主机
port = 22 # 端口
username = 'user' # 用户名
password = 'xxxxxxx' # 密码
local = 'C:\\resources\\' # 本地文件或目录,与远程一致,当前为windows目录格式,window目录中间需要使用双斜线
remote = '/resources/' # 远程文件或目录,与本地一致,当前为linux目录格式
sftp_upload(host, port, username, password, local, remote) # 上传
sftp_download(host,port,username,password,local,remote)#下载
python使用sftp上传下载文件
最新推荐文章于 2024-05-21 09:22:25 发布