使用Python来写模拟Xshell实现远程命令执行与交互

一、模块

这里使用的是

paramiko带三方库
pip install paramiko

二、效果图

三、代码实现(这里的IP,用户名,密码修改为自己对应服务器的)

import paramiko
import time

class Linux(object):
    # 参数初始化
    def __init__(self, ip, username, passwd, timeout=30):
        self.ip = ip
        self.username = username
        self.passwd = passwd
        self.timeout = timeout
        self.t = ''
        self.chan = ''
        self.try_times = 3

    # 创建连接
    def connect(self):
        while True:
            try:
                self.t = paramiko.Transport(sock=(self.ip, 22))
                self.t.connect(username=self.username, password=self.passwd)
                self.chan = self.t.open_session()
                self.chan.settimeout(self.timeout)
                self.chan.get_pty()
                self.chan.invoke_shell()
                print(f'{self.ip}连接成功。',end='')
                # print('接收到的网络数据解码为str')
                # print(self.chan.recv(65535).decode('utf-8'))
                return
            except Exception as e:
                if self.try_times != 0:
                    print('连接失败正在重试!')
                    self.try_times -= 1
                else:
                    print('重试3次连接失败程序结束。')
                    exit(1)

    # 关闭连接
    def close(self):
        self.chan.close()
        self.t.close()

    def send_command(self, cmd):  # 重命名方法为send_command
        cmd += '\r'
        result = ''
        # 发送命令
        self.chan.send(cmd)  # 修改此处为self.chan.send(cmd)
        # 回显很长的命令可能要执行很久,通过循环分批次回显,执行成功返回true,失败false
        while True:
            time.sleep(0.5)
            ret = self.chan.recv(65535)
            ret = ret.decode('utf-8')
            result += ret
            return result


if __name__ == '__main__':
    host = Linux('192.168.12.155', 'root', '12345678')
    host.connect()
    adsl = host.send_command('adsl-start')  # 发送一个拨号指令
    result = host.send_command('whoami')  # 查看IP的命令
    getname = result.split('\r')
    name = getname[-1]
    while True:
        a = input(name)
        if a =='Q':
            break
        result = host.send_command(a)  # 查看IP的命令
        info = result.split('\r')
        t = info[-1]
        result=result.replace(t,'')
        result = result.replace(a, '')
        print(result,end='')
        name=info[-1]
    host.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值