网卡流量统计脚本

创建脚本文件vim net_traffic.sh


#!/bin/bash

# 将字节转换为可读单位的函数
function convert_to_readable_units() {
    value=$1
    units=('Bytes' 'KB' 'MB' 'GB')
    unit_index=0

    while (( $(echo "$value >= 1024" | bc -l) )) && (( unit_index < ${#units[@]} - 1 )); do
        value=$(echo "scale=2; $value / 1024" | bc)
        unit_index=$((unit_index + 1))
    done

    echo "${value} ${units[$unit_index]}"
}

# 从输入中读取网络统计数据
while read -r line; do
    if [[ "$line" == *"eth0:"* ]]; then
        receive_bytes=$(echo "$line" | awk '{print $2}')
        transmit_bytes=$(echo "$line" | awk '{print $10}')
    fi
done

# 将接收和发送字节转换为可读单位
receive_readable=$(convert_to_readable_units "$receive_bytes")
transmit_readable=$(convert_to_readable_units "$transmit_bytes")

# 打印转换后的值

echo "接收: $receive_readable"
echo "发送: $transmit_readable"

通过cat /proc/net/dev| bash  net_traffic.sh 获取网卡流量统计脚本

评论

此博客中的热门博文

容器技术所涉及Linux内核关键技术

MySQL8.X安装&基本使用

部署ELK日志平台集群(Elasticsearch, Logstash, Kibana)实验记录