温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用shell和Python查看Linux服务器的网卡流量

发布时间:2022-05-09 10:19:46 来源:亿速云 阅读:253 作者:iii 栏目:大数据

这篇文章主要讲解了“怎么用shell和Python查看Linux服务器的网卡流量”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用shell和Python查看Linux服务器的网卡流量”吧!

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

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

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

直接上图上脚本:

shell版–使用截图:

怎么用shell和Python查看Linux服务器的网卡流量 

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 %-4s\n" in: $speed_rx mb/s out: $speed_tx mb/s
done

python版–使用截图:

怎么用shell和Python查看Linux服务器的网卡流量

怎么用shell和Python查看Linux服务器的网卡流量

怎么用shell和Python查看Linux服务器的网卡流量

python版代码:

#!/bin/env python3 
#by ljk 20160526 

import os,re,sys,time 

if len(sys.argv) == 1: 
  print('\n使用方法:请跟上网卡名称,可接"单个网卡"/"多个网卡,以空格分开".\n') 
  sys.exit(100) 
else: 
  print('start monitoring,press "ctrl+c" to stop\n') 

  for arg in sys.argv[1:]:  #输出标头 
    header = '------{} bandwidth(mb/s)------'.format(arg) 
    print(header.ljust(35),end='') 
  print() 

  #global values_dic 
  values_dic = {}  #定义空字典,用来在下面函数中存放各网卡的各项需要用到的值 

  def get_values(orders): 
    try: 
      with open('/proc/net/dev') as f: 
        lines=f.readlines()  #内容不多,一次性读取较方便 
        for arg in sys.argv[1:]: 
          for line in lines: 
            line=line.lstrip()  #去掉行首的空格,以便下面split 
            if re.match(arg,line): 
              values = re.split("[ :]+",line)  #以空格和:作为分隔符 
              values_dic[arg+'r'+orders]=values[1]  #1为接收值 
              values_dic[arg+'t'+orders]=values[9]  #9为发送值 
              #return [values[1],values[9]]  #可返回列表 
    except (fileexistserror,filenotfounderror,permissionerror): 
      print('open file error') 
      sys.exit(-1) 

  try: 
    while true: 
      get_values('first')  #第一次取值 
      time.sleep(10) 
      get_values('second')  #10s后第二次取值 

      for arg in sys.argv[1:]: 
        r_bandwidth = (int(values_dic[arg+'r'+'second']) - int(values_dic[arg+'r'+'first']))/1024/1024/10*8 
        t_bandwidth = (int(values_dic[arg+'t'+'second']) - int(values_dic[arg+'t'+'first']))/1024/1024/10*8 
        print('in: '+str(round(r_bandwidth,2)).ljust(8)+' out: '+str(round(t_bandwidth,2)).ljust(16),end='') 

      print() 
      values_dic = {}  #清空本次循环后字典的内容 
  except keyboardinterrupt: 
    print("\n-----bye-----")

感谢各位的阅读,以上就是“怎么用shell和Python查看Linux服务器的网卡流量”的内容了,经过本文的学习后,相信大家对怎么用shell和Python查看Linux服务器的网卡流量这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI