【系统监控程序】

用python编写一个系统监控程序,需要每隔一秒钟记录系统每个进程的资源占用和整体的资源占用情况,并输出成json,保存到文本文件。

python 复制代码
import psutil
import json
import time

def get_process_usage():
    process_list = []
    for proc in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent', 'memory_percent']):
        process_info = proc.info
        process_list.append({
            'pid': process_info['pid'],
            'name': process_info['name'],
            'username': process_info['username'],
            'cpu_percent': process_info['cpu_percent'],
            'memory_percent': process_info['memory_percent']
        })
    return process_list

def get_system_usage():
    cpu_percent = psutil.cpu_percent()
    memory_percent = psutil.virtual_memory().percent
    return {
        'cpu_percent': cpu_percent,
        'memory_percent': memory_percent
    }

def main():
    while True:
        system_usage = get_system_usage()
        process_usage = get_process_usage()
        data = {
            'system': system_usage,
            'processes': process_usage
        }
        json_data = json.dumps(data, indent=4)

        # 输出JSON数据
        print(json_data)

        # 保存JSON数据到文件
        with open('system_monitor.json', 'w') as file:
            file.write(json_data)

        time.sleep(1)

if __name__ == "__main__":
    main()
相关推荐
梦想画家18 天前
OpenMetrics 和 Prometheus 数据规范
云原生·prometheus·系统监控·openmetrics
知白守黑V9 个月前
企业IT故障应急响应:四大关键控制点的精细管理
系统监控·系统运维·it管理·it事故应急处理·it事件响应·数据运营·安全运维
Rainbow_Technology10 个月前
深入了解 ReadDirectoryChangesW 并应用其监控文件目录
系统监控·监视文件系统