【Python】ssh工具类,使用python远程执行linux命令

1.首先安装 paramiko 第三方库:

pip install paramiko

出现如下图,表示安装成功:

在这里插入图片描述

2.编写 ssh工具类,我这里取名为 ssh_util.py

import paramiko
import socket
import time


class SshUtil:
    def __init__(self, ip, username, password, port=22):
        self.ip = ip
        self.username = username
        self.password = password
        self.port = port
        self.ssh = None
        self.channel = None
        self.sftp = None

    def connect(self):
        ''''建立ssh远程连接'''
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password)
            self.channel = self.ssh.invoke_shell(width=240)
            self.sftp = self.ssh.open_sftp()
            print(f'成功连接远程主机:host = {self.ip}, user = {self.username}')
        except Exception as e:
            print(e)

    def disconnect(self):
        ''''断开远程连接'''
        if self.sftp:
            self.sftp.close()
        if self.channel:
            self.channel.close()
        if self.ssh:
            self.ssh.close()
        print('关闭远程连接')

    def exec_command(self, cmd):
        '''远程执行指令,非交互式,不维持会话状态'''
        try:
            stdin, stdout, stderr = self.ssh.exec_command()
            output = stdout.read().decode().strip()
            error = stderr.read().decode().strip()
            return output, error
        except Exception as e:
            print(e)

    def send(self, cmd, timeout=5):
        '''交互式shell的写方法,可维持会话状态, 将执行指令写入管道,发送给远程主机'''
        try:
            cmd = f'{cmd}\n'.encode('utf-8')
            self.channel.send(cmd)
        except socket.timeout:
            print('发送指令超时')

    def read(self, timeout=5, keyword='$'):
        '''交互式shell的读方法,读取管道中的响应数据,直到超时没有读取到关键字,则将之前读到的数据返回'''
        startTime = time.time()
        result = ''
        while True:
            if self.channel.recv_ready():
                output = self.channel.recv(65535).decode('utf-8')
                result += output
            # 结果中查到了关键字,则退出循环
            if keyword in result:
                break
            # 等待读取结果超时,则退出循环
            nowTime = time.time()
            if nowTime - startTime > timeout:
                print('等待读取结果超时!')
                break
            time.sleep(0.1)
        return result

    def read_remote_file(self, remotePath):
        '''读取远端文件内容'''
        try:
            with self.sftp.open(remotePath, 'r') as f:
                data = f.read().decode('utf-8')
            return data
        except Exception as e:
            print(e)

    def rewrite_remote_file(self, remotePath, data):
        '''重写远端文件内容'''
        try:
            with self.sftp.open(remotePath, 'w') as f:
                f.write(data)
        except Exception as e:
            print(e)


if __name__ == '__main__':
    # 主机信息
    ip = '192.168.215.1'
    username = 'admin'
    password = '123456'
    # 创建对象
    ssh = SshUtil(ip, username, password)
    ssh.connect()
    # 非交互式命令
    cmd = 'pwd'
    output, error = ssh.exec_command(cmd)
    print(output)
    # 交互式命令(比如连接上以后,会显示一个菜单界面)
    result = ssh.read(5, 'Menu') # 读取到主菜单页面显示完毕
    print(result)
    ssh.send('Q') # 退出主菜单
    result = ssh.read()
    print(result)
    ssh.disconnect()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值