Linux服务器CPU、内存、磁盘空间、负载情况查看python脚本
生活随笔
收集整理的這篇文章主要介紹了
Linux服务器CPU、内存、磁盘空间、负载情况查看python脚本
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
[本文出自天外歸云的博客園]
網(wǎng)上搜,東拼西湊,組裝了一個(gè)可以查Linux服務(wù)器CPU使用率、內(nèi)存使用率、磁盤空間占用率、負(fù)載情況的python腳本。
腳本內(nèi)容如下:
# -*- coding:utf-8 -*- - import os, timelast_worktime=0 last_idletime=0def get_cpu():global last_worktime, last_idletimef=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=worktimelast_idletime=idletimeif(last_worktime==0): return 0return ratedef 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:continuef.close()except:return Nonephysical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)virtual_percent = 0if vmem_total > 0:virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)return physical_percent, virtual_percentdef usage_percent(use, total):try:ret = (float(use) / total) * 100except ZeroDivisionError:raise Exception("ERROR - zero division error")return retstatvfs = 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 = "物理內(nèi)存使用率(最大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 = "系統(tǒng)負(fù)載(三個(gè)數(shù)值中有一個(gè)超過3就是高):"+str(load_average) print(load_tip)在Linux服務(wù)器上touch一個(gè)py文件,把以上內(nèi)容粘貼進(jìn)去并保存。運(yùn)行python腳本,效果如下:
一目了然。以后再出現(xiàn)訪問后臺(tái)接口502、無返回的情況,在后臺(tái)服務(wù)器執(zhí)行一下腳本,看看是不是這方面引起的問題,是不是內(nèi)存占用過高,是不是磁盤滿了等等。方便后臺(tái)服務(wù)器環(huán)境問題的定位,以便聯(lián)系相關(guān)的開發(fā)或運(yùn)維來協(xié)助解決問題。
總結(jié)
以上是生活随笔為你收集整理的Linux服务器CPU、内存、磁盘空间、负载情况查看python脚本的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AC日记——魔方 洛谷 P2007
- 下一篇: linux 其他常用命令