python 监测内存和cpu的使用率实例
Python  /  管理员 发布于 7年前   261
我就废话不多说了,直接上代码吧!
import paramikoimport pymysqlimport timelinux = ['192.168.0.179']def connectHost(ip, uname='shenyuming', passwd='ajiongqqq'): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=uname, password=passwd,port=22) return sshdef MainCheck(): try: while True: time.sleep(1) for a in range(len(linux)): ssh = connectHost(linux[a]) # 查询主机名称 cmd = 'hostname' stdin, stdout, stderr = ssh.exec_command(cmd) host_name = stdout.readlines() host_name = host_name[0] # 查看当前时间 csj = 'date +%T' stdin, stdout, stderr = ssh.exec_command(csj) curr_time = stdout.readlines() curr_time = curr_time[0] # 查看cpu使用率,并将信息写入到数据库中(取三次平均值) cpu = "vmstat 1 3|sed '1d'|sed '1d'|awk '{print $15}'" stdin, stdout, stderr = ssh.exec_command(cpu) cpu = stdout.readlines() cpu_usage = str(round((100 - (int(cpu[0]) + int(cpu[1]) + int(cpu[2])) / 3), 2)) + '%' # 查看内存使用率,并将信息写入到数据库中 mem = "cat /proc/meminfo|sed -n '1,4p'|awk '{print $2}'" stdin, stdout, stderr = ssh.exec_command(mem) mem = stdout.readlines() mem_total = round(int(mem[0]) / 1024) mem_total_free = round(int(mem[1]) / 1024) + round(int(mem[2]) / 1024) + round(int(mem[3]) / 1024) mem_usage = str(round(((mem_total - mem_total_free) / mem_total) * 100, 2)) + "%" sql = "insert into memory_and_cpu values('%s','%s','%s','%s')" % ( host_name, curr_time, cpu_usage, mem_usage) db = connectDB() sqlDML(sql, db) except: print("连接服务器 %s 异常" % (linux[a]))def connectDB(dbname='test11'): if dbname == 'test11': db = pymysql.connect("localhost", "root", "shen123", "test11") return dbdef sqlDML(sql, db): cr = db.cursor() cr.execute(sql) db.commit() cr.close() #if __name__ == '__main__': MainCheck()
以上这篇python 监测内存和cpu的使用率实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号