连接SSH客户端
这里是通过SSH的方式跟nas服务器做连接,主要是集成一些常用的nas方法,可以当作一个工具类
import posixpath
from stat import S_ISDIR
import paramiko
from zoy.main.configuration.logger import logger
class Nas:
# 这里的配置换成自己的SSH配置
def __init__(self, app):
self.host = app.config['SSH_SERVER_IP']
self.username = app.config['SSH_USERNAME']
self.password = app.config['SSH_PASSWORD']
self.port = app.config['SSH_PORT']
self.ssh = None
self.sftp = None
self.connect()
# 连接SSH客户端
def connect(self):
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.host, username=self.username, password=self.password, port=self.port, timeout=30)
self.sftp = self.ssh.open_sftp()
except Exception as e:
logger.error(f"Error occurred while connecting to SSH server: {e}")
def close(self):
try:
if self.sftp:
self.sftp.close()
if self.ssh:
self.ssh.close()
except Exception as e:
logger.error(f"Error occurred while closing SSH connection: {e}")
# 列出远程目录文件
def list_remote_files(self, directory):
files = []
try:
for item in self.sftp.listdir_attr(directory):
remote_path = posixpath.join(directory, item.filename)
if S_ISDIR(item.st_mode):
files.extend(self.list_remote_files(remote_path))
else:
files.append(remote_path)
except Exception as e:
logger.error(f"Error occurred while listing remote files: {e}")
return files
# 下载文件
def download_file(self, remote_file_path, local_file_path):
try:
self.sftp.get(remote_file_path, local_file_path)
except Exception as e:
logger.error(f"Error occurred while downloading file: {e}")