Python脚本实现对Linux服务器CPU、内存、磁盘空间以及负载情况的监测

一、前言
通常情况下,为了知悉服务器的相关信息,如果只是靠人为去挨个查询服务器相关性能的话,会比较耗时,一般情况下,我们可以通过编写Python脚本来实现对服务器性能的实时检测,每次想要查询服务器性能的时候,可以通过执行该脚本,即可知晓。

注:也可以通过设置定时任务来执行该脚本,实现在不同时间段对服务器性能的检测

二、Python实现方式
1、脚本编写

# -*- coding:utf-8 -*- - 
import os, time

last_worktime=0
last_idletime=0

def get_cpu():
        global last_worktime, last_idletime
        f=open("/proc/stat","r")
        line=""
        while not "cpu " in line: line=f.readline()
        f.close()
        spl=line.split(" ")
        worktime=int(spl[2])+int(spl[3])+int(spl[4])
        idletime=int(spl[5])
        dworktime=(worktime-last_worktime)
        didletime=(idletime-last_idletime)
        rate=float(dworktime)/(didletime+dworktime)
        last_worktime=worktime
        last_idletime=idletime
        if(last_worktime==0): return 0
        return rate

def get_mem_usage_percent():
    try:
        f = open('/proc/meminfo', 'r')
        for line in f:
            if line.startswith('MemTotal:'):
                mem_total = int(line.split()[1])
            elif line.startswith('MemFree:'):
                mem_free = int(line.split()[1])
            elif line.startswith('Buffers:'):
                mem_buffer = int(line.split()[1])
            elif line.startswith('Cached:'):
                mem_cache = int(line.split()[1])
            elif line.startswith('SwapTotal:'):
                vmem_total = int(line.split()[1])
            elif line.startswith('SwapFree:'):
                vmem_free = int(line.split()[1])
            else:
                continue
        f.close()
    except:
        return None
    physical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
    virtual_percent = 0
    if vmem_total > 0:
        virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)
    return physical_percent, virtual_percent

def usage_percent(use, total):
    try:
        ret = (float(use) / total) * 100
    except ZeroDivisionError:
        raise Exception("ERROR - zero division error")
    return ret

statvfs = os.statvfs('/')

total_disk_space = statvfs.f_frsize * statvfs.f_blocks
free_disk_space = statvfs.f_frsize * statvfs.f_bfree
disk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
disk_usage = int(disk_usage)
disk_tip = "硬盘空间使用率(最大100%):"+str(disk_usage)+"%"
print(disk_tip)

mem_usage = get_mem_usage_percent()
mem_usage = int(mem_usage[0])
mem_tip = "物理内存使用率(最大100%):"+str(mem_usage)+"%"
print(mem_tip)

cpu_usage = int(get_cpu()*100)
cpu_tip = "CPU使用率(最大100%):"+str(cpu_usage)+"%"
print(cpu_tip)

load_average = os.getloadavg()
load_tip = "系统负载(三个数值中有一个超过3就是高):"+str(load_average)
print(load_tip)

2、Linux服务器文件创建
可通过在Linux服务器上touch创建一个py文件,然后为该文件附上权限。即可执行
效果如下:

python test.py

在这里插入图片描述
这样可以即时快速的判断服务器的相关性能,定位服务器环境问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值