Python在Linux下获取CPU温度、使用率、内存使用率、硬盘使用率

方法一:

        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    #内存的占用率
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 '/Cpus:/ {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

原文:https://blog.csdn.net/m0_37739193/article/details/78836827
 

猜你喜欢

转载自blog.csdn.net/boyemachao/article/details/89445311