Python 使用paramiko模块封装ssh工具类

复制代码
# coding=utf-8
import sys, logging


from paramiko.client import SSHClient, AutoAddPolicy
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError
class SshClient:
    def __init__(self, host_ip, username, password):
     # 创建ssh对象
        self.ssh_client = SSHClient()
        self.host_ip = host_ip
        self.username = username
        self.password = password
        self.port = 22

    def __enter__(self):
        try:
            # 设置允许连接known_hosts文件中的主机(默认连接不在known_hosts文件中的主机会拒绝连接抛出SSHException)
            self.ssh_client.set_missing_host_key_policy(AutoAddPolicy)
       # 连接服务器
            self.ssh_client.connect(self.host_ip, self.port, self.username, self.password, timeout=60)
        except AuthenticationException as e:
            logging.warning('username or password error')
            raise e
            # return 1001
        except NoValidConnectionsError as e:
            logging.warning('connect time out')
            raise e
            # return 1002
        except Exception as a:
            print('Unexpected error:', sys.exc_info()[0])
            raise a
            # return 1003
        return self

    def excute_command(self, commands):
        # 执行命令
        # stdin:标准输入(就是你输入的命令);stdout:标准输出(就是命令执行结果);stderr:标准错误
        # (命令执行过程中如果出错了就把错误打到这里),stdout和stderr仅会输出一个
        stdin, stdout, stderr = self.ssh_client.exec_command(commands)
     # 返回命令结果
        return stdout.read().decode()

    def __exit__(self, exc_type, exc_val, exc_tb):
     # 关闭服务器连接
        self.ssh_client.close()


if __name__ == '__main__':
    with SshClient('192.168.2.63', 'root', 'password') as ssh_c:
        blk = 'vdb'
        command = "df -h | grep /dev/%s" % blk
        result = ssh_c.excute_command(command)
        if len(result) == 0:
            mount_command = "mount /dev/%s /mnt" % blk
            mount_result = ssh_c.excute_command(mount_command)
            print(mount_result)
复制代码

 

posted @   莫离m  阅读(567)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示