程序员的资源宝库

网站首页 > gitee 正文

python3 运维脚本:使用psutil模块监控linux系统

sanyeah 2024-04-01 11:24:41 gitee 5 ℃ 0 评论

使用python编写一个监控脚本,放在Linux系统运行。监控要求如下:
1.显示当前时间
2.脚本运行之后监控10s,每隔一秒钟输出一次信息
3.显示当前系统CPU逻辑核数、平均使用率
4.显示总内存大小(单位G),内存使用率
5.显示根目录大小(单位G),根目录使用率
6.本机IP地址是多少,网络使用情况,收发了多少M数据

#!/usr/bin/env python3

import psutil
import datetime
import time

def sys_monitor():
    start_time = time.time()
    # system current time
    # %F as %Y-%m-%d, %T as %H:%M:%S
    current_time = datetime.datetime.now().strftime("%F %T")
    print(f'current time: {current_time}')

    # CPU logical cores number
    cpu_count = psutil.cpu_count()
    # cpu usage rate, refresh frequency is 0.5s
    cup_per = psutil.cpu_percent(interval=0.5)
    print(f'cpu logical cores number is {cpu_count}, cpu usage rate is {cup_per}%')

    # memory info
    memory_info = psutil.virtual_memory()
    # total memory GB
    memory_total = round(memory_info.total / 1024 / 1024 / 1024, 2)
    # memory usage rate
    #memory_per = (memory_total - memory_info.available) / memory_total * 100
    memory_per = memory_info.percent
    print(f'total memory is {memory_total}G, memory usage rate is {memory_per}%')

    # disk info
    # root (/) related disk info
    disk_info = psutil.disk_usage("/")
    #print(disk_info)
    # root (/) size
    disk_total = disk_info.total
    # root (/) usage rate
    disk_per = float(disk_info.used / disk_total * 100)
    print(f'size of root(/) is {round(disk_total / 1024 /1024 /1024, 2)}G, usage rate of root(/) is {round(disk_per,2)}%')

    # network info
    # network io
    net = psutil.net_io_counters()
    #print(net)
    # nic(network interface card) ip
    net_ipy = psutil.net_if_addrs()
    #print(f"net_ipy {net_ipy}")
    net_ip = net_ipy['ens33'][0][1]
    print(f'local ip on ens33 is {net_ip}')
    # received data
    net_recv = float(net.bytes_recv / 1024 /1024)
    # send data
    net_sent = float(net.bytes_sent /1024 /1024)
    print(f'network received data {round(net_recv,2)}M Bytes, network send data {round(net_sent,2)}M Bytes')

    # output every 1s
    end_time = time.time()
    time.sleep(1- (end_time - start_time))

count = 0
# run in 10s
while count < 10:
    count += 1
    print(f'execute times: {count}'.center(50,'*'))
    sys_monitor()

  

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表