统计特定网络接口上的传入数据包



我想统计一段特定时间内(直到执行脚本后5分钟)网络接口(例如eth0)上传入数据包的数量,如何通过shell或python脚本来完成?哪一个更准确?

我知道像iptraf这样的网络工具,但我希望它通过脚本完成,最好将计数值打印在屏幕上或文件中。

如果您使用的是linux shell,您可以使用tcpdump来完成任务。shell中使用的大多数命令都预先安装在大多数linux发行版中。

#!/bin/sh
# # # Run this as sudo
# # # Pass an argument of your IP address
# # $ Usage: sudo ./<nameOfTheScript> <IPofYourMachine>
# Parameters
captureTime=300

# Capture packets for X Seconds
tcpdump -i eth0 dst host $1 >> /dev/null 2> out &
pid=$!
sleep $captureTime
kill $pid
# Extract relevant data
cat out | tail -2 | head -1 | cut -d " " -f 1
# Cleaning up!
rm out

shell运行tcpdump 300秒并终止它。tcpdump将您需要的数据输出到stderr。这就是将该流重定向到文件(2> out)的原因。shell的最后一秒命令从tcpdump抛出的完整消息中提取我们想要的数据。它需要作为sudo运行!另外,不要忘记根据需要修改监听界面。

如果还不清楚我为什么要这么做,请告诉我!

退房https://github.com/dugsong/pypcap它使用libpcap,看起来支持linux/win/mac

>>> import pcap
>>> for ts, pkt in pcap.pcap():
...     print ts, `pkt`

有人在这里发布了一个更长的脚本示例:http://pylibpcap.sourceforge.net

如果您使用的是Linux内核(我不知道BSD,…内核),则可以使用/sys/class/net/INTERFACE/statistics/rx_packets

capture.sh接口time_in_seconds

#!/bin/sh
pcksFile="/sys/class/net/$1/statistics/rx_packets"
nbPcks=`cat $pcksFile`
sleep $2
echo $(expr `cat $pcksFile` - $nbPcks)

输出:

$ ./capture.sh eth0 2
7

最新更新