您的位置:首页 > 游戏 > 游戏 > Linux编程:使用python或者shell获取系统信息

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

2024/11/16 13:48:20 来源:https://blog.csdn.net/stallion5632/article/details/140742815  浏览:    关键词:Linux编程:使用python或者shell获取系统信息

0. 概要

在日常的系统管理和性能监控中,获取系统信息是一个非常常见的需求。
本文将介绍如何使用Python和Shell脚本来获取这些系统信息。

1. 使用Python获取系统信息

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

1.1 安装psutil库

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

sudo apt install python3-psutil
或者
pip3 install psutil

1.2 Python脚本

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

# -*- coding: utf-8 -*-import psutil
import platform
from datetime import datetimedef 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脚本:

#!/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信息、内存信息、交换分区信息、磁盘信息、网络信息以及系统启动时间。
运行输出:
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com