安裝paramiko模組
/usr/local/python36/bin/pip3 install paramiko
1、獲取cpu使用率
#!/usr/bin/python #coding=utf8 #target: get the cpu's used of remote linux system import paramiko def getlinux(ssh): # get the result of executing command stdin, stdout, stderr = ssh.exec_command(r"sar 2 3|awk 'END{print (100-$NF)*100}'") # judge if there is any error err = stderr.readlines() if len(err) > 0: return err else: stdout_content = stdout.readlines() result = stdout_content if len(result) == 0: print("there is something wrong when executing sar command") else: return round(float(result[0].strip()),2) if __name__ == '__main__': # create ssh object ssh = paramiko.SSHClient() # connect target host by ssh ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname="192.168.223.136",port=22,username="root",password="redhat") # get the result of target host result = getlinux(ssh) # close ssh connection ssh.close() print(str(result)+"%s used")
2、獲取記憶體使用率
#!/usr/bin/python #coding=utf8 #target: get the memory's used of linux system import paramiko def getlinux(ssh): # executing command stdin, stdout, stderr = ssh.exec_command(r"free -m|awk 'NR==2{print (($3 - $6 - $7)/$2)*100}'") err = stderr.readlines() if len(err) > 0: return err else: stdout_content = stdout.readlines() result = stdout_content if len(result) == 0: print("there is something wrong when executing free -m") else: return round(float(result[0].strip()),2) if __name__ == '__main__': # create ssh object ssh = paramiko.SSHClient() # connect target host by ssh ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname="192.168.223.136",port=22,username="root",password="redhat") result = getlinux(ssh) ssh.close() print(str(result)+"% used")
3、獲取磁碟使用率:
#!/usr/bin/python #coding=utf8 #target: get the used of disk import paramiko def getlinux(ssh): stdin, stdout, stderr = ssh.exec_command(r"df -h|awk 'NR > 1{if($1==$NF){print $1}else{print $0}}'") err = stderr.readlines() if len(err) > 0: return err else: stdout_content = stdout.readlines() result = stdout_content if len(result) == 0: print("there is something wrong when executing command") else: return result if __name__ == '__main__': ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname="192.168.223.136",port=22,username="root",password="redhat") result = getlinux(ssh) ssh.close() for i in result: print("the used of %s has used %s" % (i.strip().split()[5],i.strip().split()[4]))