#导入paramiko库 import paramiko
创建SSHClient实例对象
ssh = paramiko.SSHClient()
调用方法,标识没有远程机器的公钥,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
连接远程机器 地址端口用户名密码
ssh.connect("192.168.10.7",22,"root","12")
#定义Compute类 class Cunputer: def init(self,ip,passwd): self.ip = ip #ip为远程主机的ip self.passwd = passwd #passwd为远程主机的密码
#调用远程主机的内存使用率 def free(self): # ssh.exec_command 使用Linux命令 stdin, stdout, stderr = ssh.exec_command("free -m |awk '/Mem/{print $2}'") stdin, used, stderr = ssh.exec_command("free -m |awk '/Mem/{print $3}'") stdin, free, stderr = ssh.exec_command("free -m |awk '/Mem/{print $4}'") # 获取命令执行的结果 print("内存总量:", stdout.read(), "\n", "已使用内存:", used.read(), "\n", "内存剩余:", free.read(),)
#调用远程主机的CPU使用率
def cpu(self): # ssh.exec_command 使用Linux命令 stdin, cpu, stderr = ssh.exec_command("sar -u 1 1 | awk 'NR==4{print $4}'") # 获取命令执行的结果 print("cpu使用率", cpu.read())
#调用远程主机的disk使用率 def disk(self): # ssh.exec_command 使用Linux命令 stdin, disk, stderr = ssh.exec_command("df | awk 'NR==2{print $5}'") # 获取命令执行的结果 print("disk使用率:",disk.read())
aa = Cunputer("10.0.111.77","1") aa.cpu() aa.free() aa.disk() #关闭连接 ssh.close()