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)

root@h36:~# 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	#内存的占用率
>>> 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在"/"目录下的使用率
>>> psutil.cpu_percent(0)	#本机cpu的总占用率
>>> 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
    import netifaces
except ImportError:
        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']
            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:
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])
>>> 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():
        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):
        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命令
root@h36:~# 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温度来,至于原因我也不明白,只能读出真实物理机的温度,我试了下的确如此。

http://www.rojtberg.net/836/introducing-sensors-py/

https://www.cnblogs.com/xuaijun/p/7985147.html

方法一:        psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。它实现了同等命令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、i
本文定位:想通过python调用top命令获取cpu使用率但暂时没有思路的情况。 如果单纯为了获得cpu的利用率,通过top命令重定向可以轻松实现,命令如下: 复制代码 代码如下: top -bi > cpuHistory.log 复制代码 代码如下: top -bi | tee  cpuHistory.log 这个就不解释了,不懂的朋友查询下top的帮助文档。这里要实现的是通过python调用top命令,并获得cpu的利用率信息。 用过popen的朋友很快就能想到类似如下的代码(这个是我第一次写的代码,*_*): 复制代码 代码如下: #! /usr/bin/python import
不同的linux发行版可能获取CPU温度文件的目录不所不同,可自行百度。 # fedora filepath :'/sys/class/hwmon/hwmon0/device/hwmon/hwmon0/temp2_input' # respberrypi filepath : '/sys/class/thermal/thermal_zone0/temp' with open('/sys/clas...
疫情卡在宿舍,无奈笔记本灰太多缺少清灰工具,电脑散热太拉,开着cad一天之后经常蓝屏:( 因此借鉴该网站资料:Python使用pynvml查看GPU信息,写了一份监控电脑gpu的温度的小程序,在此做为摸鱼记录。 官网文档文件:需要翻墙才能查阅 import pynvml import time while 1: pynvml.nvmlInit() # 初始化 # 获取GPU i的handle,后续通过handle来处理 handle = pynvml.nvmlDevi
首先确保系统是否存在安装包, 系统没有上连接:Debian -- Package Download Selection -- lm-sensors_3.6.0-7_amd64.debhttps://packages.debian.org/sid/amd64/lm-sensors/download安装 apt-get install lm-sensors 查看安装路径:whereis sensors 查找后授权/opt/secSdtXa/sdt-Trust 2 1 /.
Linux操作系统中,可以通过操作系统内核提供的API获取CPU使用率。下面是一些常用的API和工具: 1. top命令:top命令可以查看系统的进程信息和CPU使用率,可以通过参数-t来控制输出信息的格式。 2. ps命令:ps命令可以查看系统进程,包括进程的ID、名称、状态和CPU使用率等信息,可以通过参数-p来指定进程ID。 3. /proc/stat文件:/proc/stat文件是Linux操作系统中一个包含系统状态信息的虚拟文件系统,可以通过该文件获取CPU使用率的信息。 4. sysinfo()函数:sysinfo()函数是Linux系统提供的一个获取系统信息的API,可以通过该函数获得系统的CPU使用率内存使用情况等信息。 5. getloadavg()函数:getloadavg()函数是一个获取系统负载(load average)的API,通过该函数获取系统的平均负载,可以粗略地得到系统的CPU使用率。 以上这些API和工具都可以获取Linux系统的CPU使用率,可以根据具体需求选择合适的方法来实现。在实际应用中,可以通过编写Shell脚本或者使用高级编程语言如C语言或Python来调用以上API,实现获取CPU使用率的功能。