如何为 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
答案1
您可以使用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
对于具有但不具有 的更现代系统netstat
,ip -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