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

相关推荐
coberup6 分钟前
django Forbidden (403)错误解决方法
python·django·403错误
山河君9 分钟前
ubuntu使用DeepSpeech进行语音识别(包含交叉编译)
linux·ubuntu·语音识别
鹏大师运维13 分钟前
【功能介绍】信创终端系统上各WPS版本的授权差异
linux·wps·授权·麒麟·国产操作系统·1024程序员节·统信uos
筱源源15 分钟前
Elasticsearch-linux环境部署
linux·elasticsearch
龙哥说跨境37 分钟前
如何利用指纹浏览器爬虫绕过Cloudflare的防护?
服务器·网络·python·网络爬虫
小白学大数据1 小时前
正则表达式在Kotlin中的应用:提取图片链接
开发语言·python·selenium·正则表达式·kotlin
flashman9111 小时前
python在word中插入图片
python·microsoft·自动化·word
菜鸟的人工智能之路1 小时前
桑基图在医学数据分析中的更复杂应用示例
python·数据分析·健康医疗
pk_xz1234562 小时前
Shell 脚本中变量和字符串的入门介绍
linux·运维·服务器
懒大王爱吃狼2 小时前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍