python 服务器监控

这是一个使用Python编写的服务器监控脚本,包括CPU利用率(vmstat)、负载平均值和磁盘空间监控。通过os模块调用系统命令获取数据,计算并返回监控指标。
摘要由CSDN通过智能技术生成

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#####################################
##    created by basededato        ##
##    2018-01-02                   ##
##    监控
#####################################

import os
import json

class Monitor(object):

    def __init__(self , Cmd):
        self.Cmd = Cmd


    # vmstat cpu监控
    def cpuVmstat(self):
        fn_data = os.popen(self.Cmd).read().strip()
        lines = fn_data.split('\n')

        us = 0
        sy = 0
        wa = 0
        idle = 0

        for i in lines[3:]:  # 从第4行循环取数据
            line = i.split()
            us = us + int(line[-5])
            sy = sy + int(line[-4])
            wa = wa + int(line[-2])
            idle = idle + int(line[-3])

        us = us / len(lines[3:])
        sy = sy / len(lines[3:])
        wa = wa / len(lines[3:])
        idle = idle / len(lines[3:])
        # used=100-wa-idle

        cpuused_info = {'CPU_WA': wa, 'CPU_IDLE': idle, 'CPU_US': us, 'CPU_SY': sy}
        return cpuused_info


    # cpu_load_average监控
    def cpuLoadAvreage(self):

        fn_data = os.popen(self.Cmd).read().strip()
        lines = fn_data.split('\n')
        for i in lines[0:]:
            line = i.split()
            load1mins = line[-3].replace(',', '')
            load5mins = line[-2].replace(',', '')
            load15mins = line[-1].replace(',', '')

            if line[3].replace(',', '') == 'days':
                uptime = (line[2] + line[3] + line[4]).replace(',', '')
            elif line[3].replace(',', '') == 'min':
                uptime = (line[2] + line[3]).replace(',', '')
            else:
                uptime = line[2].replace(',', '')

            cpuload_info = {'POWER_UPTIME': uptime, 'LOAD_AVERAGE_1MINS': load1mins, 'LOAD_AVERAGE_5MINS': load5mins, 'LOAD_AVERAGE_15MINS': load15mins}
            return cpuload_info


    # 磁盘空间监控
    def diskFree(self):
        fn_data = os.popen(self.Cmd).read().strip()
        lines = fn_data.split('\n')

        for i in lines[0:]:
            line = i.split()

            if str(line) != '[]':
                used = line[4]
                list = line[5]

                diskused_info = {'DISKURL': list, 'DISK_USED': used}
                return diskused_info

            else:
                diskused_info = {'DISKURL': 'config error,please check cfg file'}
                return diskused_info


   
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值