Python Linux系统监控脚本编写

发布时间:2024-09-11 21:32:34 作者:小樊
来源:亿速云 阅读:79

在Linux系统中,可以使用Python编写一个简单的系统监控脚本

import os
import time

def get_cpu_usage():
    with open('/proc/stat', 'r') as f:
        cpu_data = f.readline()
    cpu_data = cpu_data.split()
    total_cpu_time = sum(map(int, cpu_data[1:]))
    idle_cpu_time = int(cpu_data[4])
    return 100 * (total_cpu_time - idle_cpu_time) / total_cpu_time

def get_memory_usage():
    with open('/proc/meminfo', 'r') as f:
        mem_data = f.readlines()
    total_mem = int(mem_data[0].split()[1])
    free_mem = int(mem_data[1].split()[1])
    return 100 * (total_mem - free_mem) / total_mem

def main():
    while True:
        cpu_usage = get_cpu_usage()
        mem_usage = get_memory_usage()
        print(f"CPU Usage: {cpu_usage:.2f}%")
        print(f"Memory Usage: {mem_usage:.2f}%")
        time.sleep(1)

if __name__ == "__main__":
    main()

这个脚本会每隔一秒钟获取系统的CPU使用率和内存使用率,并打印出来。你可以根据需要修改时间间隔或者添加其他功能,例如将监控数据写入日志文件等。

注意:这个脚本只适用于Linux系统,因为它使用了/proc文件系统来获取系统信息。在其他操作系统上运行此脚本可能会导致错误。

推荐阅读:
  1. linux运维一定要学python吗?
  2. python编写json脚本监控端口

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linux

上一篇:Linux Python处理文件权限问题

下一篇:Linux Python网络通信库选择

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》