【问题标题】:network bandwith utilization bash script using only netstat [closed]仅使用 netstat 的网络带宽利用率 bash 脚本 [关闭]
【发布时间】:2022-01-22 03:16:47
【问题描述】:

我在计算网卡上的带宽使用量时遇到问题。 我在 FreeBSD 上执行此操作,我只能使用 netstat 而无法安装其他模块。

我只是不知道如何计算它。这时我想出了一个想法,在脚本中执行命令

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

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

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

【问题讨论】:

  • 带宽以比特/秒为单位,因此您需要字节 * 8 来获取比特,然后以某种方式获取行中的时间戳并计算时间戳中的比特/差异。人类可读的形式将除以 10(不是 2)的幂。

标签: bash unix networking freebsd


【解决方案1】:

使用 awk 处理netstat 输出以获得给定接口的Ibytes sum 和Obytes sum:

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

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

#!/bin/sh

iface=$1
seconds=$2

while :
do
    read curr_Ibytes curr_Obytes < <(
        netstat -i -b -n -I "$iface" |
        awk 'BEGIN { getline } { i += $8; o += $11 } 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
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-29
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2016-03-21
    • 2018-05-17
    • 1970-01-01
    相关资源
    最近更新 更多