import os
import stat
import paramiko
class Sftp_server(object):
def __init__(self, host, username, password, port=22):
self.host = host
self.port = port
self.username = username
self.password = password
self.sftp = paramiko.SSHClient()
self.sftp.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.__connect()
def __connect(self):
try:
self.sftp.connect(hostname=self.host, port=self.port, username=self.username, password=self.password)
except:
self.sftp.connect(hostname=self.host, port=self.port, username=self.username, password=self.password,
look_for_keys=False, allow_agent=False)
def close(self):
self.sftp.close()
def upload(self, sftp_client, local_path, remote_path):
'''
利用sftp服务上传文件
:param sftp_client:
:param local_path:
:param remote_path:
:return:
'''
filename = os.path.basename(local_path)
print('正在上传:{}.'.format(filename))
sftp_client.put(local_path, remote_path, callback=self.__callback_function) # 上传文件要传完整路径
def upload_dir(self, sftp_client, local_path, remote_path):
'''
利用sftp服务上传文件夹
:param sftp_client:
:param local_path:
:param remote_path:
:return:
'''
try:
sftp_client.mkdir(remote_path)
except:
pass
for file in os.listdir(local_path):
# 资源路径
filepath = os.path.join(local_path, file)
# 判断资源文件类型
if os.path.isfile(filepath):
# 1.文件
self.upload(sftp_client, filepath, os.path.join(remote_path, file))
elif os.path.isdir(filepath):
# 2.目录
try:
sftp_client.chdir(filepath)
except Exception as e:
print(e)
sftp_client.mkdir(filepath)
sftp_client.chdir(filepath)
self.upload_dir(sftp_client, filepath, os.path.join(remote_path, file))
### 重置数据
# 返回上一层目录
sftp_client.chdir('..')
def download(self, remote_path, local_path):
'''
利用sftp服务下载文件
:param remote_path:
:param local_path:
:return:
'''
sftp_client = self.sftp.open_sftp()
sftp_client.get(remote_path, local_path)
sftp_client.close()
def download_dir(self, remote_path, local_path):
'''
下载远程文件夹
:param remote_path:
:param local_path:
:return:
'''
sftp_client = self.sftp.open_sftp()
self.__download_dir(sftp_client, remote_path, local_path)
sftp_client.close()
def __download_dir(self, sftp_client, remote_path, local_path):
os.makedirs(local_path, exist_ok=True)
dir_items = sftp_client.listdir_attr(remote_path)
for item in dir_items:
remote_child_path = os.path.join(remote_path, item.filename)
local_child_path = os.path.join(local_path, item.filename)
if stat.S_ISDIR(item.st_mode):
self.__download_dir(sftp_client, remote_child_path, local_child_path)
else:
sftp_client.get(remote_child_path, local_child_path)
def __callback_function(self, current_size, size):
'''
put的回调函数
:param current_size: 当前上传大小
:param size: 总大小
:return:
'''
if current_size == size:
print('File uploaded successfully!')
python使用SFTP上传下载文件
最新推荐文章于 2024-05-27 14:50:58 发布