Linux服务器CPU、内存、磁盘空间、负载情况查看python脚本
生活随笔
收集整理的這篇文章主要介紹了
Linux服务器CPU、内存、磁盘空间、负载情况查看python脚本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
[本文出自天外歸云的博客園]
網上搜,東拼西湊,組裝了一個可以查Linux服務器CPU使用率、內存使用率、磁盤空間占用率、負載情況的python腳本。
腳本內容如下:
# -*- 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 = "物理內存使用率(最大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)在Linux服務器上touch一個py文件,把以上內容粘貼進去并保存。運行python腳本,效果如下:
一目了然。以后再出現訪問后臺接口502、無返回的情況,在后臺服務器執行一下腳本,看看是不是這方面引起的問題,是不是內存占用過高,是不是磁盤滿了等等。方便后臺服務器環境問題的定位,以便聯系相關的開發或運維來協助解決問題。
總結
以上是生活随笔為你收集整理的Linux服务器CPU、内存、磁盘空间、负载情况查看python脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AC日记——魔方 洛谷 P2007
- 下一篇: 中文分词中的战斗机-jieba库