ubuntu

如何用Ubuntu inotify监控网络流量

小樊
46
2025-08-31 22:32:15
栏目: 智能运维

在Ubuntu系统中,inotify是一个用于监控文件系统事件的Linux内核子系统。然而,inotify本身并不直接支持监控网络流量。要监控网络流量,你可以使用其他工具,如tcpdumpiftopnload等。

如果你想通过编程方式使用inotify来间接监控网络流量,你可以考虑监控与网络相关的文件或目录的变化,例如/proc/net/dev(显示网络接口的统计信息)或/sys/class/net/<interface>/statistics(显示特定网络接口的统计信息)。以下是一个简单的Python脚本示例,它使用inotify来监控/proc/net/dev文件的变化,并解析出网络接口的接收和发送字节数:

import os
import time
from inotify_simple import INotify, flags

# 监控的文件路径
FILE_TO_WATCH = '/proc/net/dev'

def parse_net_dev(file_path):
    with open(file_path, 'r') as f:
        lines = f.readlines()[2:]  # 跳过前两行标题
        interfaces = {}
        for line in lines:
            parts = line.split()
            interface = parts[0].rstrip(':')
            received_bytes = int(parts[1])
            transmitted_bytes = int(parts[9])
            interfaces[interface] = (received_bytes, transmitted_bytes)
        return interfaces

def main():
    inotify = INotify()
    watch_flags = flags.MODIFY | flags.MOVE_SELF | flags.CREATE_SELF
    wd = inotify.add_watch(FILE_TO_WATCH, watch_flags)

    try:
        while True:
            for event in inotify.read():
                if event.name == FILE_TO_WATCH:
                    print("File modified, parsing network stats...")
                    stats = parse_net_dev(FILE_TO_WATCH)
                    for interface, (received, transmitted) in stats.items():
                        print(f"Interface: {interface}, Received: {received} bytes, Transmitted: {transmitted} bytes")
            time.sleep(1)
    except KeyboardInterrupt:
        inotify.rm_watch(wd)
    finally:
        inotify.close()

if __name__ == '__main__':
    main()

请注意,这个脚本只是一个简单的示例,实际使用时可能需要根据你的需求进行调整。此外,由于inotify的限制,如果文件变化非常频繁,可能会导致大量的事件被触发,因此可能需要进一步优化处理逻辑。

如果你需要更详细的网络流量监控,建议使用专门的网络监控工具。

0
看了该问题的人还看了