系统性能定时监控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()) # 格林尼治时间 单位秒

# ...

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











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










相关推荐
DLYSB_1 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
童槿顏丶1 小时前
GitLab部署到Linux
linux·运维·gitlab
matlabgoodboy3 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
雨田言炎3 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
用户8356290780513 小时前
Python Word 转 PDF 和 PDF 转 Word 指南
后端·python
用户8356290780513 小时前
如何使用 Python 加密和保护 Word 文档
后端·python
Fluxproxy3 小时前
AI数据集采集、批量模型推理报错频发?AI项目网络稳定性优化实战
python·ai·ai编程
程序喵大人4 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody4 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
Fanta丶4 小时前
10.Python class类的定义和魔术方法
python