python 监测内存和cpu的使用率实例

yipeiwu_com6年前Python基础

我就废话不多说了,直接上代码吧!

import paramiko
import pymysql
import time

linux = ['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 ssh
def 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 db
def sqlDML(sql, db):
  cr = db.cursor()
  cr.execute(sql)
  db.commit()
  cr.close()

  #
if __name__ == '__main__':

  MainCheck()

以上这篇python 监测内存和cpu的使用率实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解Python字典的操作

详解Python字典的操作

本篇介绍Python字典的常见操作。 修改字典元素,如图。 添加字典元素,如图。 删除字典元素del方法,如图。 删除字典元素clear方法,如图。 len(),keys(),...

Django基础知识 URL路由系统详解

Django基础知识 URL路由系统详解

MVC和MTV框架 MVC Web服务器开发领域里著名的MVC模式,所谓MVC就是把Web应用分为模型(M),控制器(C)和视图(V)三层,他们之间以一种插件式的、松耦合的方式连接在...

python安装requests库的实例代码

requests是python实现的简单易用的HTTP库,使用起来比urllib简洁很多 因为是第三方库,所以使用前需要cmd安装 pip install requests 安装完...

Python地图绘制实操详解

Python地图绘制实操详解

网上有很多地图绘制的教程,更多趋向于全国地图或者省级地图,但有时我们需要到县级。闲得慌,今天以贵州省毕节市为例,分享一篇Python县级地图的绘制(遥想当时差点把百度翻了个底朝天),希望...

python 获取图片分辨率的方法

pil版: from PIL import Image filename = r'E:\data\yangben\0.jpg' img = Image.open(filename)...