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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/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()

  

posted @   joechenyao  阅读(415)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示