【python】python连接NAS服务并拉取下载文件(SSH方式)

连接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}")

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值