修改代码RemoteShell.app部分,执行对应的Shell命令。
#!/usr/bin/env python3
# _*_ coding:utf8 _*_
from paramiko import SSHClient,AutoAddPolicy #pip3 install paramiko -i https://pypi.tuna.tsinghua.edu.cn/simple/
class RemoteShell():
def __init__(self,host,port,user,pswd):
self.host,self.port = host,port
self.user,self.pswd = user,pswd
self.ssh_client = None
#执行shell
def remote_shell(self,shell,title=""): #命令,标题
stdin, stdout, stderr = self.ssh_client.exec_command(shell)
for i in stdout.readlines():
print("%s\t%s\t%s"%(self.host,title,str(i).strip()))
def app(self):
self.remote_shell("uptime", '运行时长 ')
self.remote_shell('cat /etc/redhat-release ',"系统版本")
self.remote_shell("crontab -l","定时任务")
def run(self):
try:
#创建连接
self.ssh_client = SSHClient()
key = AutoAddPolicy()
self.ssh_client.set_missing_host_key_policy(key)
self.ssh_client.connect(self.host, self.port, self.user, self.pswd, timeout=3)
self.app()
self.ssh_client.close()
except Exception as e:
print(self.host,str(e))
RemoteShell("192.168.1.105",22,"root","123456").run()
class RemoteShell():
def __init__(self, host, port, user, pswd,shells,error_break=True):
self.host, self.port = host, port
self.user, self.pswd = user, pswd
self.shells = shells
self.error_break = error_break
self.ssh_client = None
self.msgs = []
def execute(self, shell):
stdin, stdout, stderr = self.ssh_client.exec_command(shell)
return {"shell":shell,"result":list(stdout),"error":" ; ".join(list(stderr))}
def run(self):
self.ssh_client = SSHClient()
key = AutoAddPolicy()
self.ssh_client.set_missing_host_key_policy(key)
self.ssh_client.connect(self.host, int(self.port), self.user, self.pswd, timeout=3)
for shell in self.shells:
msg = self.execute(shell)
self.msgs.append(msg)
if self.error_break and msg.get("error",None):
break
self.ssh_client.close()
return self.msgs