1. 服务器信息采集脚本
任务目标
编写一个Python脚本,使用psutil库采集当前服务器的CPU、内存、磁盘、网络等核心系统信息,并将采集结果序列化为JSON格式输出到标准输出,便于后续被其他程序或监控平台消费。
环境与依赖
- Python 3.6+
- 安装依赖:
pip install psutil
关键完整代码
import json
import time
import psutil
def get_basic_info():
"""采集CPU、内存、磁盘、网络等系统基础信息"""
# CPU信息
cpu_percent = psutil.cpu_percent(interval=1) # 1秒采样,避免首次调用返回0
cpu_count_physical = psutil.cpu_count(logical=False)
cpu_count_logical = psutil.cpu_count(logical=True)
# 内存信息
mem = psutil.virtual_memory()
mem_total = mem.total
mem_available = mem.available
mem_percent = mem.percent
# 磁盘信息(根分区)
disk = psutil.disk_usage('/')
disk_total = disk.total
disk_used = disk.used
disk_free = disk.free
disk_percent = disk.percent
# 网络信息(所有网卡汇总)
net_io = psutil.net_io_counters()
bytes_sent = net_io.bytes_sent
bytes_recv = net_io.bytes_recv
# 系统运行时间
boot_time = psutil.boot_time()
uptime_seconds = int(time.time() - boot_time)
# 组装为字典结构
info = {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"hostname": psutil.cpu_percent.__self__.__class__.__name__ if False else __import__("socket").gethostname(),
"cpu": {
"percent": cpu_percent,
"physical_cores": cpu_count_physical,
"logical_cores": cpu_count_logical
},
"memory": {
"total": mem_total,
"available": mem_available,
"percent": mem_percent
},
"disk": {
"mountpoint": "/",
"total": disk_total,
"used": disk_used,
"free": disk_free,
"percent": disk_percent
},
"network": {
"bytes_sent": bytes_sent,
"bytes_recv": bytes_recv
},
"uptime_seconds": uptime_seconds
}
return info
if __name__ == "__main__":
data = get_basic_info()
print(json.dumps(data, indent=2, ensure_ascii=False))
运行方式
python server_info.py
验证方法与判定标准
- 运行无报错:脚本正常退出,退出码为0。
- 输出为合法JSON:将输出重定向到文件后,执行
python -m json.tool output.json能成功解析。 - 字段完整性:JSON中包含
timestamp、hostname、cpu、memory、disk、network、uptime_seconds七个顶层键。 - 数值合理性:
cpu.percent在0~100之间;memory.percent与disk.percent均在0~100之间;memory.total与disk.total大于0。 - 与系统命令交叉验证(可选):执行
free -m查看内存总量(单位MiB),与脚本输出的memory.total除以1048576后的值基本一致;执行df -h /查看根分区使用率,与脚本输出的disk.percent基本一致。
常见问题
- 首次调用
cpu_percent()返回0:psutil首次调用无历史数据,本脚本已通过interval=1参数等待1秒采样,确保返回真实值。 - 磁盘信息仅采集根分区:如需采集所有分区,可遍历
psutil.disk_partitions()并过滤opts中不含cdrom的挂载点。 - 网络计数为累计值:
bytes_sent/bytes_recv是自开机以来的累计字节数,非实时速率。若需实时速率,可间隔1秒两次采样后计算差值。