欢迎来到IDC91站长网!
解决服务器各种技术问题,加微信uecomzsr

Linux

当前位置: IDC91 > 服务器教程 > Linux

Linux服务器网卡流量查看方法 shell和Python各一枚

时间:2022-05-27 00:17:40|栏目:Linux|点击:

有时我们需要较为实时的查看服务器上的网卡流量,这里我写了两个小脚本,一个用shell(先写的,一次只能查看一个网卡),另一个用Python(后写的,一次可查看多个网卡)。

脚本中都用了while true“死循环”,每隔10s从“/proc/net/dev”中取一次值并根据10s内的差值计算10s内的平均带宽;按ctrl+c停止执行。脚本兼容centos6和7

两个脚本都不太复杂,而且脚本中注释也比较细致,所以我就不过多解释脚本内容了。

直接上图上脚本:

shell版–使用截图:

image

shell版代码:

#!/bin/sh
#by ljk 20160526

if [ "$1" = "" ];then  #判断后面是否有跟参数
  echo -e "n   use interface_name after the script,like "script eth0"...n"
  exit -1
fi

echo -e "n   start monitoring the $1,press "ctrl+c" to stop"
echo ----------------------------------------------------------

file=/proc/net/dev  #内核网卡信息文件
while true
  do
  RX_bytes=`cat $file|grep $1|sed 's/^ *//g'|awk -F'[ :]+' '{print $2}'`  #这里sed这一步为了同时兼容centos6和7
  TX_bytes=`cat $file|grep $1|sed 's/^ *//g'|awk -F'[ :]+' '{print $10}'`
  sleep 10
  RX_bytes_later=`cat $file|grep $1|sed 's/^ *//g'|awk -F'[ :]+' '{print $2}'`
  TX_bytes_later=`cat $file|grep $1|sed 's/^ *//g'|awk -F'[ :]+' '{print $10}'`

  #B*8/1024/1024=Mb
  speed_RX=`echo "scale=2;($RX_bytes_later - $RX_bytes)*8/1024/1024/10"|bc`
  speed_TX=`echo "scale=2;($TX_bytes_later - $TX_bytes)*8/1024/1024/10"|bc`

  printf "%-3s %-3.1f %-10s %-4s %-3.1f %-4sn" IN: $speed_RX Mb/s OUT: $speed_TX Mb/s
done

上一篇:LNMP自动安装部署脚本

栏    目:Linux

下一篇:linux下因为系统编码问题造成乱码的快速解决方法

本文标题:Linux服务器网卡流量查看方法 shell和Python各一枚

本文地址:https://www.idc91.com/fuwuqizl/2692.html

广告投放 | 联系我们 | 免责申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

Copyright © 2023 IDC91.COM 版权所有晋ICP备17006296号