一、模块
这里使用的是
paramiko带三方库
pip install paramiko
二、效果图
三、代码实现(这里的IP,用户名,密码修改为自己对应服务器的)
import paramiko
import timeclass Linux(object):# 参数初始化def __init__(self, ip, username, passwd, timeout=30):self.ip = ipself.username = usernameself.passwd = passwdself.timeout = timeoutself.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'))returnexcept Exception as e:if self.try_times != 0:print('连接失败正在重试!')self.try_times -= 1else:print('重试3次连接失败程序结束。')exit(1)# 关闭连接def close(self):self.chan.close()self.t.close()def send_command(self, cmd): # 重命名方法为send_commandcmd += '\r'result = ''# 发送命令self.chan.send(cmd) # 修改此处为self.chan.send(cmd)# 回显很长的命令可能要执行很久,通过循环分批次回显,执行成功返回true,失败falsewhile True:time.sleep(0.5)ret = self.chan.recv(65535)ret = ret.decode('utf-8')result += retreturn resultif __name__ == '__main__':host = Linux('192.168.12.155', 'root', '6663614lcx')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':breakresult = 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()