ubuntu 查看cpu_Python 实时监控CPU使用率

Python查看cpu使用率的好处还是很多的,可以实时预警告警安全问题,全面的监控与管理进程;发现CPU占用大的时候,用大数据分析技术对安全数据进行分析,发现安全事件并及时告警,对安全防护python运维方面的帮助还是很大的。

开发工具

测试系统:

Win10、Ubuntu和MacOS

Python版本:3.5+

相关模块:

matplotlib模块;

psutil模块。

参考文档

psutil文档:

https://psutil.readthedocs.io/en/latest/

matplotlib文档:

https://matplotlib.org/users/index.html

源代码

# CPU实时监控
# 作者:木子君羡
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import psutil as p
​
POINTS = 300
fig, ax = plt.subplots()
ax.set_ylim([0, 100])
ax.set_xlim([0, POINTS])
ax.set_autoscale_on(False)
ax.set_xticks([])
ax.set_yticks(range(0, 101, 10))
ax.grid(True)
# 执行用户进程的时间百分比
user = [None] * POINTS
# 执行内核进程和中断的时间百分比
sys = [None] * POINTS
# CPU处于空闲状态的时间百分比
idle = [None] * POINTS
l_user, = ax.plot(range(POINTS), user, label='User %')
l_sys, = ax.plot(range(POINTS), sys, label='Sys %')
l_idle, = ax.plot(range(POINTS), idle, label='Idle %')
ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10))
bg = fig.canvas.copy_from_bbox(ax.bbox)
​
def cpu_usage():
    t = p.cpu_times()
    return [t.user, t.system, t.idle]
​
before = cpu_usage()
​
def get_cpu_usage():
    global before
    now = cpu_usage()
    delta = [now[i] - before[i] for i in range(len(now))]
    total = sum(delta)
    before = now
    return [(100.0*dt)/(total+0.1) for dt in delta]
​
​
def OnTimer(ax):
    global user, sys, idle, bg
    tmp = get_cpu_usage()
    user = user[1:] + [tmp[0]]
    sys = sys[1:] + [tmp[1]]
    idle = idle[1:] + [tmp[2]]
    l_user.set_ydata(user)
    l_sys.set_ydata(sys)
    l_idle.set_ydata(idle)
    while True:
        try:
            ax.draw_artist(l_user)
            ax.draw_artist(l_sys)
            ax.draw_artist(l_idle)
            break
        except:
            pass
    ax.figure.canvas.draw()
​
​
def start_monitor():
    timer = fig.canvas.new_timer(interval=100)
    timer.add_callback(OnTimer, ax)
    timer.start()
    plt.show()
    plt.savefig("a.png")
​
​
if __name__ == '__main__':
    start_monitor()
​

使用演示

在cmd窗口运行cpu.py即可

(1) Ubuntu

87620edf6dd37034003d1261c5c06376.png

(2) Window10

f796a130da27857d8cb968590398b997.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值