方法一:

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:20show Windows or Linux network Nic status, such as MAC address, Gateway, IP address, etc
"""import os
import systry: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 netifacesroutingGateway = 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:passdisplay_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 structdef 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, netifacesdef 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.currentcpu_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 = 1z = 0data = []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 + 1data.append(list)if i+1 == cpucore_num*y:cpu1["data"] = datacpu1["cpuname"] = "cpu "+str(y-1)y = y + 1cpu.append(cpu1)cpu1 = {}data = []z = 0return cpudef 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 nettotal = 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_eachused_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, sensorslast_worktime=0
last_idletime=0sensors.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:continuef.close()except:return Nonephysical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)virtual_percent = 0if vmem_total > 0:virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)return physical_percent, virtual_percentdef usage_percent(use, total):try:ret = (float(use) / total) * 100except ZeroDivisionError:raise Exception("ERROR - zero division error")return retdef disk_use():statvfs = os.statvfs('/')total_disk_space = statvfs.f_frsize * statvfs.f_blocksfree_disk_space = statvfs.f_frsize * statvfs.f_bfreedisk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
#    disk_tip = "硬盘空间使用率:"+str(disk_usage)+"%"
#    print(disk_tip)return disk_usagedef mem_use():mem_usage = get_mem_usage_percent()mem_usage = mem_usage[0]
#    mem_tip = "物理内存使用率:"+str(mem_usage)+"%"
#    print(mem_tip)return mem_usagedef cpu_use():global last_worktime, last_idletimef=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*100last_worktime=worktimelast_idletime=idletimeif(last_worktime==0): return 0
#    cpu_tip = "CPU使用率:"+str(cpu_t)+"%"
#    print(cpu_tip)return cpu_tdef cpu_temperature():for chip in sensors.ChipIterator("coretemp-*"):i = 0sum = 0for 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/idisk = 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

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

  1. Linux下获取cpu温度

    大致strace跟踪了下sensors命令,发现是读取类似/sys/class/hwmon/hwmon1/temp1_input中的值,再结合google下的如下几篇文章: https://www.k ...

  2. Linux系统获取CPU温度

    Linux系统获取CPU温度 摘自:https://jingyan.baidu.com/article/cbf0e500407d072eab289343.html 各位好,本篇将简单介绍如何在不同系列 ...

  3. linux 温度控制软件,linux下的cpu温度监控软件 lm-sensors

    linux下的cpu温度监控软件 lm-sensors 发布时间:2008-09-05 00:27:46来源:红联作者:PCHCO 现在购买主机板时都会有厂商提供的监控软体可以使用,而最常使用到到功能 ...

  4. Ubuntu16.04安装(个鬼鬼)linux下的cpu温度监控软件 lm-sensors,设置cpupower

    感觉好惨,毕设一波三折换了两回题目--进度条显示为∞.还能怎么办,继续做啊--现在是先做这个比较稳的简单的把实验先搞完.准备工作一安装im-sensors 安装linux下的cpu温度监控软件 lm- ...

  5. s-tui:在 Linux 中监控 CPU 温度、频率、功率和使用率的终端工具

    一般每个 Linux 管理员都会使用 lm_sensors 监控 CPU 温度.lm_sensors (Linux 监控传感器)是一个自由开源程序,它提供了监控温度.电压和风扇的驱动和工具. 如果你正 ...

  6. suse linux查看CPU温度,Ubuntu下查看CPU温度风扇转速和硬盘温度

    夏天到了,这几天本本的温度也飙升起来,在WinXP下玩了会CS,结果CPU一下就到了80度,吓得我赶紧关了. 下午Win7 64位旗舰版也下载完了,准备体验一下,就装个系统,网页都不浏览的情况下CPU ...

  7. linux下监测cpu温度,linux下CPU温度监测

    1.安装相关软件 sudo apt-get install lm-sensors sensors-applet [root@localhost ~]# sensors No sensors found ...

  8. linux下的cpu温度监控软件 lm-sensors

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 原贴:h ...

  9. linux shell下获取cpu温度

    cpu0:cat /sys/class/thermal/thermal_zone0/temp cpu1:cat /sys/class/thermal/thermal_zone1/temp 就会获取到c ...

最新文章

  1. python操作excel表格写入多行和多列_python多处理:写入同一excel-fi
  2. Windows破解逆向-CrackMe_1实例(使用OpenProcess修改内存中的值)
  3. 活力四射的Windows Embedded Standard 7
  4. 换手机的等等!什么时候能用上1000元级5G手机?中国移动公布时间表
  5. linux 可定义信号数,Linux系统编程(20)——信号基本概念
  6. python 笔记 之 线程锁
  7. java语言程序设计(梁勇)
  8. 黑群晖linux删除文件夹命令,不拆机直接修改黑群晖的SN和MAC
  9. LFW pairs.txt解释
  10. TCP,IP,UDP等各种报文格式
  11. Linux文件夹设置共享
  12. 通用权限管理概要设计说明书
  13. Windows系统磁盘清理C盘扩容
  14. pascal过程与函数
  15. 球坐标系下的两点距离公式
  16. 教你识别QQ匿名聊天的人是谁
  17. 2019年,React 开发者应该掌握的 22 种神奇工具
  18. 在Linux下掌握arm和操作系统(1)--stm32和arm
  19. 用友系统服务器坏了怎么恢复数据,如何恢复用友账套数据?
  20. datetime日期、时间的计算

热门文章

  1. C语言常见复试面试问题
  2. 基于改进逆透视变换的智能车测距技术_车路协同技术的演进与嬗变
  3. 用Keil写一个8路流水灯,两侧各一个LED同时亮起,之后依次向中间聚拢,然后在展开,接着,在8个灯闪三次,为一次循环...
  4. 毕业设计遇到的一些问题与总结
  5. linux怎么释放cached中内存,Linux 释放cached内存
  6. DHCP分配ip地址。0.0.0.0与255.255.255.255
  7. C#绩效管理系统(二)导航栏和用户管理窗口的基本实现
  8. 回调函数到底有什么好处
  9. 计算机类在职博士学科,武汉理工大学计算机专业在职博士招生简章
  10. 凶猛现金贷背后的欲望深渊:女子网上撸81只猫,欠下70万元债