我想在网站上显示 Debian 机器的一个接口的当前网络利用率(带宽使用情况)。它不应该非常复杂或精确,只是一个简单的数字,例如“52 Mbit/s”。
典型的网络带宽监视器,例如iftop让我无法简单地提取这样的值。
我怎样才能最好地检索它?
例如,我想我可能会/proc/net/dev每隔几分钟解析一次。不确定这是否真的是最好的方法。
做到这一点的最好方法可能是解析/proc/net/dev(请注意,这/proc是不可移植的)。这是bash我快速整理的一个脚本,应该能够计算它:
#!/bin/bash
_die() {
printf '%s\n' "$@"
exit 1
}
_interface=$1
[[ ${_interface} ]] || _die 'Usage: ifspeed [interface]'
grep -q "^ *${_interface}:" /proc/net/dev || _die "Interface ${_interface} not found in /proc/net/dev"
_interface_bytes_in_old=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { sub(/^.*:/, "") ; print $1 } else { print $2 } }' /proc/net/dev)
_interface_bytes_out_old=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { print $9 } else { print $10 } }' /proc/net/dev)
while sleep 1; do
_interface_bytes_in_new=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { sub(/^.*:/, "") ; print $1 } else { print $2 } }' /proc/net/dev)
_interface_bytes_out_new=$(awk "/^ *${_interface}:/"' { if ($1 ~ /.*:[0-9][0-9]*/) { print $9 } else { print $10 } }' /proc/net/dev)
printf '%s: %s\n' 'Bytes in/sec' "$(( _interface_bytes_in_new - _interface_bytes_in_old ))" \
'Bytes out/sec' "$(( _interface_bytes_out_new - _interface_bytes_out_old ))"
# printf '%s: %s\n' 'Kilobytes in/sec' "$(( ( _interface_bytes_in_new - _interface_bytes_in_old ) / 1024 ))" \
# 'Kilobytes out/sec' "$(( ( _interface_bytes_out_new - _interface_bytes_out_old ) / 1024 ))"
# printf '%s: %s\n' 'Megabits in/sec' "$(( ( _interface_bytes_in_new - _interface_bytes_in_old ) / 131072 ))" \
# 'Megabits out/sec' "$(( ( _interface_bytes_out_new - _interface_bytes_out_old ) / 131072 ))"
_interface_bytes_in_old=${_interface_bytes_in_new}
_interface_bytes_out_old=${_interface_bytes_out_new}
done
Run Code Online (Sandbox Code Playgroud)
请记住,sleep这不考虑在 while 循环中执行操作所需的时间,因此这(非常轻微)不准确。在我的 600mhz 铜矿上,循环需要 0.011 秒——对于大多数用途来说,这个误差可以忽略不计。还请记住,在使用(注释掉的)千字节/兆位输出时,bash 只理解整数算术。