
服务器硬件监控是确保服务器高效运行和及时发现潜在问题的重要手段,通过使用Python,我们可以方便地编写脚本来监控各种硬件指标,如CPU、内存、磁盘和网络等,本文将介绍如何使用Python进行服务器硬件监控,并提供一些实用的代码示例。
1. 安装必要的库
我们需要安装一些Python库,以便进行硬件监控,常用的库包括psutil和py-cpuinfo,你可以使用以下命令安装这些库:
pip install psutil py-cpuinfo
2. CPU监控
获取CPU信息
使用py-cpuinfo库可以获取详细的CPU信息:
import cpuinfo cpu_info = cpuinfo.get_cpu_info() print(cpu_info)
获取CPU使用率
使用psutil库可以获取实时的CPU使用率:
import psutil
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU Usage: {cpu_percent}%")3. 内存监控
获取内存信息

使用psutil库可以获取详细的内存信息:
memory_info = psutil.virtual_memory() print(memory_info)
获取内存使用率
memory_percent = memory_info.percent
print(f"Memory Usage: {memory_percent}%")4. 磁盘监控
获取磁盘分区信息
disk_partitions = psutil.disk_partitions()
for partition in disk_partitions:
print(f"Device: {partition.device}, Mountpoint: {partition.mountpoint}")获取磁盘使用情况
disk_usage = psutil.disk_usage('/')
print(disk_usage)5. 网络监控
获取网络接口信息
net_io = psutil.net_io_counters() print(net_io)
获取每个网络接口的使用情况
net_if_addrs = psutil.net_if_addrs()
for interface, addrs in net_if_addrs.items():
for addr in addrs:
print(f"Interface: {interface}, Address: {addr.address}")6. 综合监控示例
以下是一个综合监控示例,定期打印CPU、内存、磁盘和网络的使用情况:
import time
import psutil
def print_system_info():
cpu_percent = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
disk_usage = psutil.disk_usage('/')
net_io = psutil.net_io_counters()
print(f"CPU Usage: {cpu_percent}%")
print(f"Memory Usage: {memory_info.percent}%")
print(f"Disk Usage: {disk_usage.percent}%")
print(f"Bytes Sent: {net_io.bytes_sent}")
print(f"Bytes Recv: {net_io.bytes_recv}")
print("="*40)
while True:
print_system_info()
time.sleep(5)7. 日志记录和报警机制
为了长期监控并及时发现问题,可以将监控数据记录到日志文件中,并设置报警机制,当CPU使用率超过80%时发送邮件报警,以下是一个简单的示例:

import logging
from logging.handlers import TimedRotatingFileHandler
import smtplib
from email.mime.text import MIMEText
配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
handler = TimedRotatingFileHandler('system_monitor.log', when='midnight', interval=1, backupCount=7)
logger.addHandler(handler)
def send_email(subject, body):
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = 'your_email@example.com'
msg['To'] = 'admin@example.com'
with smtplib.SMTP('smtp.example.com') as server:
server.login('your_username', 'your_password')
server.sendmail(msg['From'], [msg['To']], msg.as_string())
def check_system():
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > 80:
logger.warning(f"High CPU usage detected: {cpu_percent}%")
send_email("High CPU Usage Alert", f"CPU usage is at {cpu_percent}%")
else:
logger.info(f"CPU usage: {cpu_percent}%")
while True:
check_system()
time.sleep(60)相关问题与解答
问题1:如何更改日志文件的轮转周期?
解答:在TimedRotatingFileHandler中,可以通过修改when参数来更改日志文件的轮转周期,将when='midnight'改为when='H'可以实现每小时轮转一次,还可以通过修改interval参数来设置时间间隔,将interval=1改为interval=2可以实现每两小时轮转一次。
问题2:如何扩展监控项以包括GPU使用情况?
解答:要监控GPU使用情况,可以使用gpustat库,安装gpustat库:
pip install gpustat
可以使用以下代码获取GPU使用情况:
import gpustat gpu_stats = gpustat.new_query() print(gpu_stats)
通过将上述代码集成到现有的监控系统中,可以实现对GPU使用情况的监控。
各位小伙伴们,我刚刚为大家分享了有关“服务器硬件监控python”的知识,希望对你们有所帮助。如果您还有其他相关问题需要解决,欢迎随时提出哦!
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/23304.html<
