用Python写一个脚本,提供完整的系统信息

目录

一、功能:

1. 收集全面的系统信息:

2. 提供多种输出方式:

3. 信息组织清晰:

4. 错误处理:

二、运行示例

三、完整代码

四、总结


一、功能:

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()

四、总结

这个工具可以用于:系统监控、故障诊断、性能分析、系统配置记录、硬件资源管理

喜欢的话记得点赞关注加收藏哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

穿梭的编织者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值