import psutil
import datetime
import os
# 获取 CPU 使用率,interval=1 表示计算过去 1 秒内的平均 CPU 使用率
cpuprecent = psutil.cpu_percent(interval=1)
# 获取内存使用情况
mem_info = psutil.virtual_memory()
available_memory = mem_info.available # 可用内存
memory_usage_percent = mem_info.percent # 内存使用率
# 获取磁盘使用情况
disk_usage = psutil.disk_usage('/')
used_disk_space = disk_usage.used
used_precent = disk_usage.percent
# 打印 CPU 和内存的使用情况
print(f"1、当前主机 CPU 使用率为 {cpuprecent:.1f}%, 当前主机内存使用率为 {memory_usage_percent:.1f}%, 当前主机磁盘使用率为 {used_precent:.1f}%")
# 网卡数据包发送和接收数据包
def network():
net_io = psutil.net_io_counters()
print(f"2、网卡发送出去的字节总数为{net_io.bytes_sent}")
print(f"3、网卡接收到的字节总数为{net_io.bytes_recv}")
print(f"4、网卡本机发送出去的数据包为{net_io.packets_sent}")
print(f"5、网卡本机接收到的数据包总数为{net_io.packets_recv}")
#调用函数
network()
users_info = psutil.users()
for user in users_info:
print(f"6、系统用户信息为{str(user.name)},系统主机名为{str(user.host)}")
# boottime = psutil.boot_time()
# print(f"系统开机时间为{str(boottime)}")
boottime = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d-%H:%M:%S")
print(f"7、本次系统开机时间为{str(boottime)}")
# 打印前10行内存占用最高的pid进程
print('8.打印前10行内存占用最高的pid进程')
os.system('sleep 5')
os.system('ps -eo pid,ppid,cmd,%mem --sort=-%mem | head')
print('9.打印前10行cpu占用最高的pid进程')
os.system('sleep 5')
os.system('ps -eo pid,ppid,cmd,%cpu --sort=-%cpu | head -n 10')
首先确保python环境,我这里是python3.6环境,首先安装模块psutil。
pip install psutil
创建以xx.py结尾的python文件,将代码粘贴进去,然后执行python xx.py就可以了。不定期更新此脚本。