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信息、内存信息、交换分区信息、磁盘信息、网络信息以及系统启动时间。
运行输出:

相关推荐
沐多6 分钟前
波折重重:一个Linux实时系统Xenomai宕机问题的深度定位过程
linux·xenomai·实时linux·xenomai4
猿经验10 分钟前
tar.gz压缩文件在linux上解压异常问题:gzip:stdin:invalid compressed data
linux·运维·服务器
木卫二号Coding18 分钟前
宝塔-firefox(Docker应用)-构建自己的Web浏览器
linux·docker·开源
小王子102432 分钟前
数据结构与算法Python版 二叉查找树
数据结构·python·算法·二叉查找树
编程阿布41 分钟前
Python基础——多线程编程
java·数据库·python
又蓝43 分钟前
使用 Python 操作 MySQL 数据库的实用工具类:MySQLHandler
数据库·python·mysql
dundunmm1 小时前
机器学习之pandas
人工智能·python·机器学习·数据挖掘·pandas
好学近乎知o1 小时前
常用的Django模板语言
python·django·sqlite
SP八岐大兔1 小时前
Linux(Ubuntu/CentOS)配置开机自启动服务
linux·ubuntu·centos
小火炉Q1 小时前
16 循环语句——for循环
人工智能·python·网络安全