方法一:
psutil是一個跨平台庫(http://code.google.com/p/psutil/),能夠輕松實作擷取系統運作的程序和系統使用率(包括CPU、記憶體、磁盤、網絡等)資訊。它主要應用于系統監控,分析和限制系統資源及程序的管理。它實作了同等指令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等。目前支援32位和64位的Linux、Windows、OS X、FreeBSD和Sun Solaris等作業系統(參考https://www.cnblogs.com/liu-yao/p/5678157.html)
[email protected]:~# python
Python 2.7.9 (default, Jun 29 2016, 13:08:31)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psutil
>>> psutil.virtual_memory().percent #記憶體的占用率
54.9
>>> psutil.disk_partitions(all=False) #磁盤分區資訊
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro,data=ordered'), sdiskpart(device='/dev/sda7', mountpoint='/tmp', fstype='ext4', opts='rw,relatime,data=ordered'), sdiskpart(device='/dev/sda8', mountpoint='/home', fstype='ext4', opts='rw,relatime,data=ordered'), sdiskpart(device='/dev/sda5', mountpoint='/var', fstype='ext4', opts='rw,relatime,data=ordered')]
>>> psutil.disk_usage("/").percent #磁盤sda1在"/"目錄下的使用率
30.7
>>> psutil.cpu_percent(0) #本機cpu的總占用率
0.6
>>> psutil.cpu_percent(percpu=True) #每個CPU每核的使用率,我這裡的虛拟機是雙CPU雙核
[0.1, 0.2, 0.0, 0.0]
>>> psutil.sensors_temperatures()
{'coretemp': [shwtemp(label='Physical id 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 1', current=100.0, high=100.0, critical=100.0), shwtemp(label='Physical id 1', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 0', current=100.0, high=100.0, critical=100.0), shwtemp(label='Core 1', current=100.0, high=100.0, critical=100.0)]}
疑惑:在指令行中執行以上指令CPU使用率都正常,可是寫入py腳本(print(psutil.cpu_percent(0)))檔案後執行卻不是0.0就是100.0,奇了怪了
解決:雖然在指令行中psutil.cpu_percent(0)能出正常結果,但是上面那個疑惑在腳本裡還必須不能使用0,比如寫成psutil.cpu_percent(1)才能解決上面的問題,這個參數是時間間隔多少秒擷取CPU使用率。
注:在使用psutil子產品時要注意版本大小,一開始我在Debian8.6下用apt-get install pustil直接裝後咋也擷取不了CPU溫度,雖然按官方網站https://pypi.python.org/pypi/psutil#downloads在指令行下執行psutil.sensors_temperatures()卻報錯,後來我才意識到了有可能是版本過低的問題,于是去下載下傳了較新的psutil 5.4.2才解決了問題(也可以不去官網下載下傳psutil 5.4.2tar包,應該用pip安裝,它就會去自動下載下傳最新了psutil版本了,挺省事的倒是。先執行apt-get install python-pip安裝pip,用pip install psutil之前可能還需要重要的一步apt-get install python-dev,否則會報錯:
psutil/_psutil_common.c:9:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
)
補充(代碼來自http://blog.51cto.com/dgd2010/1868851):Python擷取網卡資訊(名稱、MAC、IP、網關等)
Python pypi庫中一個子產品名字叫“netifaces”,使用C語言寫的一個第三方子產品。可以:
1.擷取本機的所有網關
2.擷取本機所有的接口Interface(網卡NIC)
3.擷取本機指定接口的詳細資訊,包括IP位址、子網路遮罩、廣播位址、MAC位址等
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:getNetworkStatus.py
User: Guodong
Create Date: 2016/11/2
Create Time: 16:20
show Windows or Linux network Nic status, such as MAC address, Gateway, IP address, etc
"""
import os
import sys
try:
import netifaces
except ImportError:
try:
command_to_execute = "pip install netifaces || easy_install netifaces"
os.system(command_to_execute)
except OSError:
print "Can NOT install netifaces, Aborted!"
sys.exit(1)
import netifaces
routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1]
for interface in netifaces.interfaces():
if interface == routingNicName:
# print netifaces.ifaddresses(interface)
routingNicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']
try:
routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']
# TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in 'netifaces' module.
routingIPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']
except KeyError:
pass
display_format = '%-30s %-20s'
print display_format % ("Routing Gateway:", routingGateway)
print display_format % ("Routing NIC Name:", routingNicName)
print display_format % ("Routing NIC MAC Address:", routingNicMacAddr)
print display_format % ("Routing IP Address:", routingIPAddr)
print display_format % ("Routing IP Netmask:", routingIPNetmask)
運作結果:
# python getNetworkStatus.py
Routing Gateway: 10.6.28.254
Routing NIC Name: eth0
Routing NIC MAC Address: 06:7f:12:00:00:15
Routing IP Address: 10.6.28.28
Routing IP Netmask: 255.255.255.0
擷取ip還有種寫法:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
get_ip_address('lo')
get_ip_address('eth0')
運作結果:
127.0.0.1
10.6.28.28
>>> import netifaces
>>> netifaces.interfaces()
[u'lo', u'eth0', u'eth1', u'eth2']
>>> psutil.net_io_counters(pernic=True)
{'lo': snetio(bytes_sent=141053, bytes_recv=141053, packets_sent=1411, packets_recv=1411, errin=0, errout=0, dropin=0, dropout=0), 'eth2': snetio(bytes_sent=74862, bytes_recv=16424, packets_sent=920, packets_recv=81, errin=0, errout=0, dropin=0, dropout=0), 'eth1': snetio(bytes_sent=126292, bytes_recv=34980, packets_sent=1515, packets_recv=174, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=21560891, bytes_recv=1316735948, packets_sent=164194, packets_recv=1119225, errin=0, errout=0, dropin=0, dropout=0)}
>>> print(netifaces.interfaces()[2])
eth1
>>> print(psutil.net_io_counters(pernic=True)["lo"][0])
141053
小綜合:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json, os, time, psutil, netifaces
def GetCPUorDiskTemper(type='Core'):
dict_cpu_temp = {}
if hasattr(psutil, "sensors_temperatures"):
temps = psutil.sensors_temperatures()
else:
temps = {}
cpu_each = []
names = list(temps.keys())
for name in names:
if name in temps:
for entry in temps[name]:
if type in entry.label:
dict_cpu_temp[entry.label] = entry.current
cpu_each.append(dict_cpu_temp[entry.label])
cpu_top = sorted(dict_cpu_temp.items(),key=lambda d:d[0])[0][1]
return {"cpu_top":cpu_top,"cpu_each":cpu_each}
def GetCPUInfo():
cpu_t = GetCPUorDiskTemper()["cpu_each"]
cpu_num = int(os.popen("cat /proc/cpuinfo| grep 'physical id'| sort| uniq| wc -l").readline().strip())
numb = os.popen("cat /proc/cpuinfo| grep 'cpu cores'| uniq").readline()
cpucore_num = int(numb[12:-1])
cpu_u = psutil.cpu_percent(percpu=True,interval=1)
cpu = []
cpu1 = {}
list = {}
y = 1
z = 0
data = []
for i in range(0,len(cpu_u)):
list = {"corename":"Core "+str(z),"cpu_u":cpu_u[i],"cpu_t":cpu_t[i]}
z = z + 1
data.append(list)
if i+1 == cpucore_num*y:
cpu1["data"] = data
cpu1["cpuname"] = "cpu "+str(y-1)
y = y + 1
cpu.append(cpu1)
cpu1 = {}
data = []
z = 0
return cpu
def GetNetwork():
net = []
for i in range(1,len(netifaces.interfaces())):
netname = str(netifaces.interfaces()[i])
bytes_sent = int(psutil.net_io_counters(pernic=True)[netname][0])
bytes_recv = int(psutil.net_io_counters(pernic=True)[netname][1])
eth_status = os.popen('sudo ethtool '+netname).readlines()[-1][16:-1]
x = {"name":netname,"eth_status":eth_status,"bytes_sent":bytes_sent,"bytes_recv":bytes_recv}
net.append(x)
return net
total = 0
used = 0
disk_partitions = psutil.disk_partitions(all=False)
for i in range(0,len(disk_partitions)):
partition = disk_partitions[i][1]
total_each = psutil.disk_usage(partition)[0]
total = total + total_each
used_each = psutil.disk_usage(partition)[1]
used = used + used_each
disk_u = used/float(total)*100
cpu_u = psutil.cpu_percent(1)
cpu_t = GetCPUorDiskTemper()["cpu_top"]
memory_u = psutil.virtual_memory().percent
boot_time = psutil.boot_time()
runtime = os.popen('cat /proc/uptime').readlines()[0].split(" ")[0]
data = {"a":{"disku":disk_u,"memu":memory_u,"cpuu":cpu_u,"cput":cpu_t,"boot_time":boot_time,\
"runtime":runtime},"b":GetNetwork(),"c":GetCPUInfo()}
print(data)
運作結果:
{'a': {'cput': 100.0, 'cpuu': 0.2, 'disku': 29.98913391327393, 'memu': 40.5, 'boot_time': 1514893852.0, 'runtime': '89424.57'}, 'c': [{'cpuname': 'cpu 0', 'data': [{'corename': 'Core 0', 'cpu_t': 100.0, 'cpu_u': 1.0}, {'corename': 'Core 1', 'cpu_t': 100.0, 'cpu_u': 0.0}]}, {'cpuname': 'cpu 1', 'data': [{'corename': 'Core 0', 'cpu_t': 100.0, 'cpu_u': 0.0}, {'corename': 'Core 1', 'cpu_t': 100.0, 'cpu_u': 0.0}]}], 'b': [{'eth_status': 'yes', 'bytes_sent': 404589707, 'name': 'eth0', 'bytes_recv': 200725324}, {'eth_status': 'yes', 'bytes_sent': 71170, 'name': 'eth1', 'bytes_recv': 50232}, {'eth_status': 'yes', 'bytes_sent': 80868, 'name': 'eth2', 'bytes_recv': 48402}]}
方法二:(不建議使用,方法一完全就夠用而且還好。而且算的結果還和方法一不一樣,我感覺方法一更準确一些吧)
直接上代碼:hui.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os, time, re, sensors
last_worktime=0
last_idletime=0
sensors.init()
def get_mem_usage_percent():
try:
f = open('/proc/meminfo', 'r')
for line in f:
if line.startswith('MemTotal:'):
mem_total = int(line.split()[1])
elif line.startswith('MemFree:'):
mem_free = int(line.split()[1])
elif line.startswith('Buffers:'):
mem_buffer = int(line.split()[1])
elif line.startswith('Cached:'):
mem_cache = int(line.split()[1])
elif line.startswith('SwapTotal:'):
vmem_total = int(line.split()[1])
elif line.startswith('SwapFree:'):
vmem_free = int(line.split()[1])
else:
continue
f.close()
except:
return None
physical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
virtual_percent = 0
if vmem_total > 0:
virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)
return physical_percent, virtual_percent
def usage_percent(use, total):
try:
ret = (float(use) / total) * 100
except ZeroDivisionError:
raise Exception("ERROR - zero division error")
return ret
def disk_use():
statvfs = os.statvfs('/')
total_disk_space = statvfs.f_frsize * statvfs.f_blocks
free_disk_space = statvfs.f_frsize * statvfs.f_bfree
disk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
# disk_tip = "硬碟空間使用率:"+str(disk_usage)+"%"
# print(disk_tip)
return disk_usage
def mem_use():
mem_usage = get_mem_usage_percent()
mem_usage = mem_usage[0]
# mem_tip = "實體記憶體使用率:"+str(mem_usage)+"%"
# print(mem_tip)
return mem_usage
def cpu_use():
global last_worktime, last_idletime
f=open("/proc/stat","r")
line=""
while not "cpu " in line: line=f.readline()
f.close()
spl=line.split(" ")
worktime=int(spl[2])+int(spl[3])+int(spl[4])
idletime=int(spl[5])
dworktime=(worktime-last_worktime)
didletime=(idletime-last_idletime)
rate=float(dworktime)/(didletime+dworktime)
cpu_t = rate*100
last_worktime=worktime
last_idletime=idletime
if(last_worktime==0): return 0
# cpu_tip = "CPU使用率:"+str(cpu_t)+"%"
# print(cpu_tip)
return cpu_t
def cpu_temperature():
for chip in sensors.ChipIterator("coretemp-*"):
i = 0
sum = 0
for feature in sensors.FeatureIterator(chip):
sfi = sensors.SubFeatureIterator(chip, feature)
vals = [sensors.get_value(chip, sf.number) for sf in sfi]
sum = sum + vals[0]
i = i + 1
# cpu_tmp = "CPU溫度:"+sum/i+"℃"
# print(cpu_tmp)
return sum/i
disk = disk_use()
print(disk)
print(type(disk))
mem = mem_use()
print(mem)
print(type(mem))
cpua = cpu_use()
print(cpua)
print(type(cpua))
cpub = cpu_temperature()
print(cpub)
print(type(cpub))
sensors.cleanup()
注意:CPU使用率、記憶體使用率、硬碟使用率都還好說,但是CPU溫度就比較麻煩一些了,得使用sensors來整,lm_sensors的軟體可以幫助我們來監控主機闆、CPU的工作電壓、風扇轉速、溫度等資料。這些資料我們通常在主機闆的BIOS也可以看到。當我們可以在機器運作的時候通過lm_sensors随時來監測着CPU的溫度變化,可以預防呵保護因為CPU過熱而會燒掉。如果你沒有這個子產品,使用apt-get install lm-sensors指令來安裝即可(我這裡使用的是Debian8.6 64位)。
還得和上面的同一目錄下再來這麼一個檔案(https://github.com/paroj/sensors.py/blob/master/sensors.py)
運作代碼:python hui.py
32.1816127961
<type 'float'>
37.7943290638
<type 'float'>
0.251490181586
<type 'float'>
100.0
<type 'float'>
疑惑:網上還有一種計算CPU使用率的方法,那就是用top指令來擷取
def cpu_use():
cpu_usage = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())
cpu_tip = "CPU使用率:"+cpu_usage+"%"
print(cpu_tip)
但是和我上面的代碼結果卻不一樣,用/proc/stat檔案(http://server.51cto.com/sCollege-188250.htm)來計算得到0.252413215089,而用top指令得到的卻是0.1
注:你可能會對這裡的CPU溫度是100而困惑,執行sensors指令
[email protected]:~# sensors
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0: +100.0°C (high = +100.0°C, crit = +100.0°C)
Core 0: +100.0°C (high = +100.0°C, crit = +100.0°C)
為什麼會都是100呢?這不科學啊!我這裡用的是VMware虛拟機下裝的Debian,後來問别人說是這個讀不出虛拟機的CPU溫度來,至于原因我也不明白,隻能讀出真實實體機的溫度,我試了下的确如此。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90EVPh3a610MjpXTmJEViZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39jM1IjNxUzM2ETMxEDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
參考:
http://www.rojtberg.net/836/introducing-sensors-py/
https://www.cnblogs.com/xuaijun/p/7985147.html