Ubuntu

如何通過 ifconfig 獲取輸入/輸出數據包

  • June 3, 2020

如何為 ifconfig 獲取單獨的輸入/輸出字節?

我檢查數據包和字節ifconfig

ens3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
   inet 153.126.***.**  netmask 255.255.254.0  broadcast 153.126.179.255
   ether 9c:a3:ba:01:df:c3  txqueuelen 1000  (Ethernet)
   RX packets 60777328  bytes 18377900528 (18.3 GB)
   RX errors 0  dropped 0  overruns 0  frame 0
   TX packets 33420428  bytes 11013732175 (11.0 GB)
   TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

我每天執行這個腳本並獲得字節。

然而,以這種方式,輸入/輸出數據包是混合的。

有沒有辦法分開輸入/輸出數據包?

或者 ifconfig 是不可能的(我需要使用其他工具???)

我想做的只是每天獲取輸入/輸出字節/數據包。

PATH="/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin"

NIC="ens3"

LOG="/var/log/transmit_bytes.log"

AT=`date '+%Y-%m-%d %H:%M:%S'`

TX=`cat /proc/net/dev | grep $NIC | sed -e 's/:/ /' | awk '{print$10}'`

echo "${AT} ${TX}" >> $LOG

exit 0

您可以使用netstat -ni在易於解析的表中獲取數據包。

例如,netstat -ni

Kernel Interface table
Iface      MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0      1500  1534430      0      0 0        605131      0      0      0 BMRU
lo       65536    20701      0      0 0         20701      0      0      0 LRU
tun0      1500   131763      0      0 0        177857      0      0      0 MOPRU
wlan0     1500        0      0      0 0             0      0      0      0 BMU

要找出接收和發送的數據包計數,這樣的事情就足夠了

netstat -ni | awk -v interface="eth0" '$1 == interface { print $3, $7 }'

結果

1534430 605131

對於具有ip但不具有 的更現代的系統netstatip -s -j link show dev eth0將提供 JSON 格式的等價物

[{"ifindex":2,"ifname":"eth0","flags":["BROADCAST","MULTICAST","UP","LOWER_UP"],"mtu":1500,"qdisc":"pfifo_fast","operstate":"UP","linkmode":"DEFAULT","group":"default","txqlen":1000,"link_type":"ether","address":"b8:27:eb:31:53:64","broadcast":"ff:ff:ff:ff:ff:ff","stats64":{"rx":{"bytes":182767514,"packets":1538635,"errors":0,"dropped":0,"over_errors":0,"multicast":0},"tx":{"bytes":268406197,"packets":606995,"errors":0,"dropped":0,"carrier_errors":0,"collisions":0}}}]

這可以用類似的東西來解析jq

ip -s -j link show dev eth0 | jq '.[].stats64 | ( .rx.packets, .tx.packets )' | xargs

輸出

1538635 606995

引用自:https://unix.stackexchange.com/questions/590581