Linux编程:使用python或者shell获取系统信息

0. 概要

在日常的系统管理和性能监控中,获取系统信息是一个非常常见的需求。

本文将介绍如何使用Python和Shell脚本来获取这些系统信息。

1. 使用Python获取系统信息

使用psutil库来获取系统的CPU、内存、磁盘和网络信息。

1.1 安装psutil库

首先,我们需要安装psutil库:

bash 复制代码
sudo apt install python3-psutil
或者
pip3 install psutil

1.2 Python脚本

以下是一个完整的Python脚本,用于获取系统信息:

python 复制代码
# -*- coding: utf-8 -*-

import psutil
import platform
from datetime import datetime

def get_system_info():
    # 获取系统信息
    uname = platform.uname()
    system_info = {
        "System": uname.system,
        "Node Name": uname.node,
        "Release": uname.release,
        "Version": uname.version,
        "Machine": uname.machine,
        "Processor": uname.processor,
    }
    
    # 获取CPU信息
    cpu_info = {
        "Physical cores": psutil.cpu_count(logical=False),
        "Total cores": psutil.cpu_count(logical=True),
        "Max Frequency": f"{psutil.cpu_freq().max:.2f}Mhz",
        "Min Frequency": f"{psutil.cpu_freq().min:.2f}Mhz",
        "Current Frequency": f"{psutil.cpu_freq().current:.2f}Mhz",
        "CPU Usage Per Core": [f"{x}%" for x in psutil.cpu_percent(percpu=True, interval=1)],
        "Total CPU Usage": f"{psutil.cpu_percent()}%",
    }
    
    # 获取内存信息
    svmem = psutil.virtual_memory()
    memory_info = {
        "Total": f"{svmem.total / (1024 ** 3):.2f}GB",
        "Available": f"{svmem.available / (1024 ** 3):.2f}GB",
        "Used": f"{svmem.used / (1024 ** 3):.2f}GB",
        "Percentage": f"{svmem.percent}%",
    }
    
    # 获取交换分区信息
    swap = psutil.swap_memory()
    swap_info = {
        "Total": f"{swap.total / (1024 ** 3):.2f}GB",
        "Free": f"{swap.free / (1024 ** 3):.2f}GB",
        "Used": f"{swap.used / (1024 ** 3):.2f}GB",
        "Percentage": f"{swap.percent}%",
    }
    
    # 获取磁盘信息
    partitions = psutil.disk_partitions()
    disk_info = {}
    for partition in partitions:
        partition_usage = psutil.disk_usage(partition.mountpoint)
        disk_info[partition.device] = {
            "Mountpoint": partition.mountpoint,
            "File system type": partition.fstype,
            "Total Size": f"{partition_usage.total / (1024 ** 3):.2f}GB",
            "Used": f"{partition_usage.used / (1024 ** 3):.2f}GB",
            "Free": f"{partition_usage.free / (1024 ** 3):.2f}GB",
            "Percentage": f"{partition_usage.percent}%",
        }
    
    # 获取网络信息
    net_io = psutil.net_io_counters()
    network_info = {
        "Total Bytes Sent": f"{net_io.bytes_sent / (1024 ** 2):.2f}MB",
        "Total Bytes Received": f"{net_io.bytes_recv / (1024 ** 2):.2f}MB",
    }
    
    # 获取启动时间
    boot_time_timestamp = psutil.boot_time()
    bt = datetime.fromtimestamp(boot_time_timestamp)
    boot_time = f"{bt.year}-{bt.month}-{bt.day} {bt.hour}:{bt.minute}:{bt.second}"
    
    return {
        "System Information": system_info,
        "CPU Information": cpu_info,
        "Memory Information": memory_info,
        "Swap Information": swap_info,
        "Disk Information": disk_info,
        "Network Information": network_info,
        "Boot Time": boot_time,
    }

def print_system_info(info):
    for key, value in info.items():
        print(f"{key}:")
        if isinstance(value, dict):
            for sub_key, sub_value in value.items():
                print(f"  {sub_key}: {sub_value}")
        else:
            print(f"  {value}")
        print()

if __name__ == "__main__":
    system_info = get_system_info()
    print_system_info(system_info)

运行下输出:

2.使用Shell脚本获取系统信息

以下是一个示例Shell脚本:

bash 复制代码
#!/bin/bash

# 获取系统信息
get_system_info() {
    echo "System Information:"
    echo "-------------------"
    echo "System: $(uname -s)"
    echo "Node Name: $(uname -n)"
    echo "Release: $(uname -r)"
    echo "Version: $(uname -v)"
    echo "Machine: $(uname -m)"
    echo "Processor: $(uname -p)"
    echo
}

# 获取CPU信息
get_cpu_info() {
    echo "CPU Information:"
    echo "----------------"
    echo "Physical cores: $(grep -c ^processor /proc/cpuinfo)"
    echo "Total cores: $(nproc)"
    echo "CPU Usage:"
    mpstat -P ALL 1 1 | awk '/^Average:/ && $2 ~ /[0-9]/ {print "Core "$2": "$3"%"}'
    echo
}

# 获取内存信息
get_memory_info() {
    echo "Memory Information:"
    echo "-------------------"
    free -h | awk '/^Mem:/ {print "Total: "$2 "\nUsed: "$3 "\nFree: "$4 "\nShared: "$5 "\nBuffers: "$6 "\nCached: "$7}'
    echo
}

# 获取交换分区信息
get_swap_info() {
    echo "Swap Information:"
    echo "-----------------"
    free -h | awk '/^Swap:/ {print "Total: "$2 "\nUsed: "$3 "\nFree: "$4}'
    echo
}

# 获取磁盘信息
get_disk_info() {
    echo "Disk Information:"
    echo "-----------------"
    df -h | awk 'NR==1 {print $0} NR>1 {print $0}'
    echo
}

# 获取网络信息
get_network_info() {
    echo "Network Information:"
    echo "--------------------"
    echo "Total Bytes Sent: $(cat /proc/net/dev | awk 'NR>2 {sent+=$10} END {print sent/1024/1024 " MB"}')"
    echo "Total Bytes Received: $(cat /proc/net/dev | awk 'NR>2 {recv+=$2} END {print recv/1024/1024 " MB"}')"
    echo
}

# 获取启动时间
get_boot_time() {
    echo "Boot Time:"
    echo "----------"
    echo "System Boot Time: $(who -b | awk '{print $3, $4}')"
    echo
}

# 运行所有信息收集函数
get_system_info
get_cpu_info
get_memory_info
get_swap_info
get_disk_info
get_network_info
get_boot_time

将上述脚本保存为system_info.sh,这个Shell脚本将获取并显示系统的基本信息、CPU信息、内存信息、交换分区信息、磁盘信息、网络信息以及系统启动时间。
运行输出:

相关推荐
在下不上天8 分钟前
Flume日志采集系统的部署,实现flume负载均衡,flume故障恢复
大数据·开发语言·python
SEVEN-YEARS11 分钟前
深入理解TensorFlow中的形状处理函数
人工智能·python·tensorflow
EterNity_TiMe_16 分钟前
【论文复现】(CLIP)文本也能和图像配对
python·学习·算法·性能优化·数据分析·clip
长弓聊编程18 分钟前
Linux系统使用valgrind分析C++程序内存资源使用情况
linux·c++
cherub.25 分钟前
深入解析信号量:定义与环形队列生产消费模型剖析
linux·c++
Suyuoa27 分钟前
附录2-pytorch yolov5目标检测
python·深度学习·yolo
梅见十柒1 小时前
wsl2中kali linux下的docker使用教程(教程总结)
linux·经验分享·docker·云原生
Koi慢热1 小时前
路由基础(全)
linux·网络·网络协议·安全
传而习乎1 小时前
Linux:CentOS 7 解压 7zip 压缩的文件
linux·运维·centos
我们的五年1 小时前
【Linux课程学习】:进程程序替换,execl,execv,execlp,execvp,execve,execle,execvpe函数
linux·c++·学习