一、模块
这里使用的是
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', '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':
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()