最近在学习psutil模块,就写一个监控Linux系统信息的脚本来试试看…
1、创建监控Linux系统信息脚本
[root@kkk myPython]# cat monSystem.py
#!/usr/bin/python3
import psutil
"""Monitor Memory"""
def monMem():
memInfo = psutil.virtual_memory()
#print(memInfo)
totalMem = memInfo.total
freeMem = memInfo.free
avaMem = memInfo.available
bufMem = memInfo.buffers
cachedMem = memInfo.cached
print("Memory Info(Byte):")
print("\tTotalMem: \t" + str(totalMem))
print("\tFreeMem: \t" + str(freeMem))
print("\tAvaMem: \t" + str(avaMem))
print("\tBufMem: \t" + str(bufMem))
print("\tCachedMem: \t" + str(cachedMem))
#监控CPU
def monCpu():
physical_cpu_count = psutil.cpu_count(logical=False)
logical_cpu_count = psutil.cpu_count()
use_cpu_percent = psutil.cpu_percent(interval=1)
print("Cpu Info: ")
print("\tPhysical_cpu_count: \t" + str(physical_cpu_count))
print("\tLogical_cpu_count: \t" + str(logical_cpu_count))
print("\tUse_cpu_percent: \t" + str(use_cpu_percent))
#监控磁盘
def monDisk():
#select partiton of disk
diskInfo = psutil.disk_partitions()
mountPoint = []
for disk in diskInfo:
mountPoint.append(disk.mountpoint)
#print(mountPoint)
for mp in mountPoint:
print(mp + "'s usage info is: ")
print("\t Total: \t" + str(psutil.disk_usage(mp).total))
print("\t Used: \t\t" + str(psutil.disk_usage(mp).used))
print("\t Free: \t\t" + str(psutil.disk_usage(mp).free))
print("\t Percent: \t" + str(psutil.disk_usage(mp).percent) + "%")
if __name__ == '__main__':
monMem()
monCpu()
monDisk()
#print("The total Mem is: " + str(round(memInfo.total/1024/1024,2)) + 'M')
2、查看监控结果
[root@kkk myPython]# python3 monSystem.py
Memory Info(Byte):
TotalMem: 3966767104
FreeMem: 2371059712
AvaMem: 3372048384
BufMem: 206479360
CachedMem: 1098854400
Cpu Info:
Physical_cpu_count: 1
Logical_cpu_count: 1
Use_cpu_percent: 2.0
/'s usage info is:
Total: 52710309888
Used: 5861019648
Free: 44148158464
Percent: 11.7%
/media/cdrom's usage info is:
Total: 4058890240
Used: 4058890240
Free: 0
Percent: 100.0%
/boot's usage info is:
Total: 1023303680
Used: 155193344
Free: 797646848
Percent: 16.3%
/u01's usage info is:
Total: 126692687872
Used: 14498979840
Free: 105734479872
Percent: 12.1%
/home's usage info is:
Total: 10434662400
Used: 43388928
Free: 9837625344
Percent: 0.4%
/var's usage info is:
Total: 10434662400
Used: 450154496
Free: 9430859776
Percent: 4.6%
/soft's usage info is:
Total: 52710309888
Used: 1368326144
Free: 48640851968
Percent: 2.7%
这个脚本弄完后还可以做后续处理,比如将监控的信息使用jinja2模块渲染成html的格式定时发送到自己的邮箱…
参考博客:https://blog.csdn.net/qq_38684504/article/details/87956015