系统性能定时监控Python&Linux

系统性能定时监控

1.系统监控概述

⽤Python来编写脚本简化⽇常的运维⼯作是Python的⼀个重要⽤途。在Linux下,有许多系统命令可以让我们时刻监控系统运⾏的状态,如 ps , top , free 等等。要获取这些系统信息,Python可以通过 subprocess 模块调⽤并获取结果。但这样做显得很麻烦,尤其是要写很多解析代码。

2. psutil

在Python中获取系统信息的另⼀个好办法是使⽤ psutil 这个第三⽅模块。
psutil ,是 python system and process utilities 的缩写,意思python的系统监控及进程的管理的⼯具,是⼀个功能很强⼤的跨平台的系统管理库。可以实现命令⾏中类似ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop等等命令的功能,并且以python内置的数据结构形式返回,官⽅⽂档(https://pythonhosted.org/psutil/) ⽬前psutil⽀持的系统有linuxwindow os X 和freeBSD等.

1.1. psutil 安装

psutil是⼀个第三⽅的开源项⽬,因此,需要先安装才能够使⽤。

pip3 install psutil

1.2 psutil 版本查看

使⽤python3 进⼊交互模式,查看版本

1.3 常⻅功能

获取CPU信息

psutil.cpu_xxx()







python 复制代码
# 1.导入psutil 模块
import psutil

# 2.获取CPU信息
# 2.1 获取CPU的核心数
print(psutil.cpu_count()) # 12
# 获取物理的核心数
print(psutil.cpu_count(logical=False)) # 8
# 2.2 获取CPU的使用率
print(psutil.cpu_percent(interval=0.5)) # 5.2
# 获取每个核心的使用率
print(psutil.cpu_percent(interval=0.5,percpu=True))
# [3.1, 0.0, 0.0, 0.0, 3.1, 0.0, 0.0, 0.0, 0.0, 0.0, 21.9, 43.8]

# 3.获取内存信息
# 3.1 内存的整体信息
print(psutil.virtual_memory())
# svmem(total=16890322944, available=373940224, percent=97.8, used=16516382720, free=373940224)
# 3.2 内存的使用率
print(psutil.virtual_memory().percent)

# 4.获取硬盘信息
# 4.1 获取硬盘的分区信息
print(psutil.disk_partitions())
# 4.2 可以获取指定目录的磁盘信息
print(psutil.disk_usage('/'))
# 4.3硬盘的使用率
print(psutil.disk_usage('/').percent)

# 5.获取网络信息
# 5.1 获取受到的数据包数量
print(psutil.net_io_counters().bytes_recv) #字节为单位
# 5.2 获取发送的数据包数量
print(psutil.net_io_counters().bytes_sent)

# 6.获取开机时间
print(psutil.boot_time()) # 格林尼治时间 单位秒

# ...

实战 - 系统性能监控 基础版











注意: 这个意思是只有都当程序独立运行才会执行这个监控










相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
CYRUS_STUDIO1 天前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python