仅使用 netstat 的网络带宽利用率 bash 脚本

network bandwith utilization bash script using only netstat

我在计算网卡上的带宽使用时遇到问题。 我在 FreeBSD 上这样做,我只能使用 netstat,无法安装额外的模块。

就是不知道怎么算。这时我想到了一个想法,在脚本中执行命令

netstat -i -b -n -I INTERFACE 写入文件第 8 和 11 列,即 Ibytes + Obytes

然后再次执行此命令并读取相同的列

这里我有一个问题怎么办?有没有计算带宽消耗的数学公式?

正在处理 netstat 输出以获得给定接口与 awk 的 Ibytes 总和和 Obytes 总和:

netstat -i -b -n -I IFACE |
awk 'BEGIN { getline } { i += ; o +=  } END { print i, o }'

现在一个简单的监控脚本:

#!/bin/sh

iface=
seconds=

while :
do
    read curr_Ibytes curr_Obytes < <(
        netstat -i -b -n -I "$iface" |
        awk 'BEGIN { getline } { i += ; o +=  } END { print i, o }'
    )

    if [ -n "$prev_Ibytes" ]
    then
        printf 'in: %d B/s\tout: %d B/s\n' \
            $(( (curr_Ibytes - prev_Ibytes) / seconds )) \
            $(( (curr_Obytes - prev_Obytes) / seconds ))
    fi

    prev_Ibytes=$curr_Ibytes
    prev_Obytes=$curr_Obytes

    sleep "$seconds"
done

示例:

./netmon.sh em0 5
in: 520 B/s out: 3040 B/s
in: 325 B/s out: 1648 B/s
in: 95 B/s  out: 130 B/s
in: 1380 B/s    out: 23629 B/s
in: 232 B/s out: 146 B/s
...