目录
一、功能:
1. 收集全面的系统信息:
基本系统信息(操作系统、版本、架构等)
CPU信息(核心数、频率、使用率等)
内存信息(总量、可用量、使用率等)
磁盘信息(分区、容量、使用情况等)
网络信息(接口、连接数等)
2. 提供多种输出方式:
可以将详细信息保存为JSON文件
可以在控制台打印摘要信息
3. 信息组织清晰:
使用嵌套字典结构组织数据
包含时间戳便于跟踪
4. 错误处理:
对可能失败的操作进行异常处理
确保程序稳定运行
二、运行示例
三、完整代码
import platform
import psutil
import socket
import json
from datetime import datetime
def collect_system_info():
info = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
# 系统信息
"system": {
"os": platform.system(),
"os_version": platform.version(),
"architecture": platform.machine(),
"processor": platform.processor(),
"hostname": socket.gethostname(),
"python_version": platform.python_version()
},
# CPU信息
"cpu": {
"physical_cores": psutil.cpu_count(logical=False),
"total_cores": psutil.cpu_count(logical=True),
"cpu_freq": {
"current": psutil.cpu_freq().current,
"min": psutil.cpu_freq().min,
"max": psutil.cpu_freq().max
},
"cpu_usage_per_core": [percentage for percentage in psutil.cpu_percent(percpu=True)],
"total_cpu_usage": psutil.cpu_percent()
},
# 内存信息
"memory": {
"total": psutil.virtual_memory().total,
"available": psutil.virtual_memory().available,
"used": psutil.virtual_memory().used,
"percentage": psutil.virtual_memory().percent
},
# 磁盘信息
"disk": {
"partitions": [],
"disk_usage": {}
},
# 网络信息
"network": {
"interfaces": [],
"connections": len(psutil.net_connections())
}
}
# 获取磁盘分区信息
for partition in psutil.disk_partitions():
try:
partition_usage = psutil.disk_usage(partition.mountpoint)
info["disk"]["partitions"].append({
"device": partition.device,
"mountpoint": partition.mountpoint,
"fstype": partition.fstype,
"total": partition_usage.total,
"used": partition_usage.used,
"free": partition_usage.free,
"percentage": partition_usage.percent
})
except:
continue
# 获取网络接口信息
for interface_name, interface_addresses in psutil.net_if_addrs().items():
addresses = []
for addr in interface_addresses:
addresses.append({
"address": addr.address,
"netmask": addr.netmask,
"family": str(addr.family)
})
info["network"]["interfaces"].append({
"name": interface_name,
"addresses": addresses
})
return info
def save_system_info(filename="system_info.json"):
"""收集并保存系统信息到文件"""
info = collect_system_info()
with open(filename, 'w') as f:
json.dump(info, f, indent=4)
print(f"System information saved to {filename}")
def print_system_info():
"""打印系统信息摘要"""
info = collect_system_info()
print("\n=== System Information ===")
print(f"OS: {info['system']['os']} {info['system']['os_version']}")
print(f"Architecture: {info['system']['architecture']}")
print(f"Hostname: {info['system']['hostname']}")
print("\n=== CPU Information ===")
print(f"Physical cores: {info['cpu']['physical_cores']}")
print(f"Total cores: {info['cpu']['total_cores']}")
print(f"CPU Usage: {info['cpu']['total_cpu_usage']}%")
print("\n=== Memory Information ===")
print(f"Total: {info['memory']['total'] / (1024 ** 3):.2f} GB")
print(f"Available: {info['memory']['available'] / (1024 ** 3):.2f} GB")
print(f"Used: {info['memory']['percentage']}%")
print("\n=== Disk Information ===")
for partition in info['disk']['partitions']:
print(f"\nMount: {partition['mountpoint']}")
print(f"Total: {partition['total'] / (1024 ** 3):.2f} GB")
print(f"Used: {partition['percentage']}%")
print("\n=== Network Information ===")
print(f"Active connections: {info['network']['connections']}")
print(f"Network interfaces: {len(info['network']['interfaces'])}")
if __name__ == "__main__":
# 保存详细信息到文件
save_system_info()
# 打印摘要信息到控制台
print_system_info()
四、总结
这个工具可以用于:系统监控、故障诊断、性能分析、系统配置记录、硬件资源管理
喜欢的话记得点赞关注加收藏哦!