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

yipeiwu_com5年前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 format 格式化输出方法

0、前言 在python2.7及以上的版本,str.format()的方式为格式化提供了非常大的便利。与之前的%型格式化字符串相比,他显得更为方便与优越。下面我们就来看看format的具...

pytorch:实现简单的GAN示例(MNIST数据集)

我就废话不多说了,直接上代码吧! # -*- coding: utf-8 -*- """ Created on Sat Oct 13 10:22:45 2018 @author: w...

Python实现html转换为pdf报告(生成pdf报告)功能示例

本文实例讲述了Python实现html转换为pdf报告(生成pdf报告)功能。分享给大家供大家参考,具体如下: 1、先说下html转换为pdf:其实支持直接生成,有三个函数pdfkit....

Django实现web端tailf日志文件功能及实例详解

Django实现web端tailf日志文件功能及实例详解

这是Django Channels系列文章的第二篇,以web端实现tailf的案例讲解Channels的具体使用以及跟Celery的结合 通过上一篇 《Django使用Channels实...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...