一、安装psutil库

pip3 install psutil

二、代码

#!/usr/bin/python3 coding=utf-8
import psutil
import uuid
import socket
import os #系统与磁盘挂载
print('##########系统与磁盘信息#########') def get_mac_address():
mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
return ":".join([mac[e:e+2] for e in range(0,11,2)]) def get_host_ip():
try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.connect(('8.8.8.8',80))
ip=s.getsockname()[0]
finally:
s.close()
return ip def get_load():
f = open("/proc/loadavg")
loadstate=f.read().split()
return loadstate
load_list = get_load()[0:3]
system_load = ''
for i in load_list:
if system_load:
system_load = system_load+','+i
else:
system_load = i myname = socket.getfqdn(socket.gethostname())
print('主机名称:',myname)
print('本机ip地址:',get_host_ip())
print('本机MAC地址:',get_mac_address())
print('系统负载(1,5,15分钟):',system_load)
print('系统进程数:',len(psutil.pids())) devs = psutil.disk_partitions()
for dev in devs:
statvfs = os.statvfs(dev.mountpoint)
devs = psutil.disk_partitions()
for dev in devs:
statvfs = os.statvfs(dev.mountpoint)
total_disk_space = statvfs.f_frsize * statvfs.f_blocks
free_disk_space = statvfs.f_frsize * statvfs.f_bfree
disk_usage = int((total_disk_space - free_disk_space) * 100.0 / total_disk_space)
print('挂在设备:%s,挂载点:%s 磁盘使用率:%d%% 文件系统:%s' % (dev.device,dev.mountpoint,disk_usage,dev.fstype)) #系统负载
def get_load():
f = open("/proc/loadavg")
loadstate=f.read().split()
return loadstate
load_list = get_load()[0:3]
system_load = ''
for i in load_list:
if system_load:
system_load = system_load+','+i
else:
system_load = i print('系统负载(1,5,15分钟):',system_load) #cpu
cts = psutil.cpu_times()
cputime = 0
for item in cts:
if item != 0:
cputime = cputime + item
print('########CPU信息#########')
print('用户时间:%d%%' % (cts.user/cputime * 100))
print('内核时间:%d%%' % (cts.system/cputime * 100))
print('空闲时间:%d%%' % (cts.idle/cputime * 100))
print('逻辑CPU个数:',psutil.cpu_count())
print('物理cpu数量:',psutil.cpu_count(logical=False)) #内存
print('#########内存信息############')
mem = psutil.virtual_memory()
print('内存大小: %dM'%(int(mem.total/1024/1024)))
print('已使用内存: %dM'%(int(mem.used/1000/1000)))
print('剩余内存:%dM'%(int(mem.free/1024/1024)))
print('内存使用率: %d%%'%(int(mem.percent)))

三、运行结果

[root@localhost~]#python3   system_info.py
##########系统与磁盘信息#########
主机名称: localhost.localdomain
本机ip地址: 10.0.0.141
本机MAC地址: :0c::ca:bf:b2
系统负载(,,15分钟): 0.00,0.01,0.05
系统进程数:
挂在设备:/dev/sda2,挂载点:/ 磁盘使用率:% 文件系统:xfs
挂在设备:/dev/sda1,挂载点:/boot 磁盘使用率:% 文件系统:xfs
系统负载(,,15分钟): 0.00,0.01,0.05
########CPU信息#########
用户时间:%
内核时间:%
空闲时间:%
逻辑CPU个数:
物理cpu数量:
#########内存信息############
内存大小: 976M
已使用内存: 431M
剩余内存:201M
内存使用率: %
05-13 01:32