当前位置: > shell编程 >

实时查看Linux网卡流量的shell脚本分享(图文)

时间:2014-10-01 08:49来源:linux.it.net.cn 作者:it

实时查看linux下的网卡流量,脚本内容如下:
 

复制代码代码示例:

#!/bin/bash
#filename interface.sh

eth=eth0
RXpre=$(ifconfig ${eth} | grep bytes | awk  '{print $2}'| awk -F":" '{print $2}')
TXpre=$(ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')
sleep 1
RXnext=$(ifconfig ${eth} | grep bytes | awk  '{print $2}'| awk -F":" '{print $2}')
TXnext=$(ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')

echo RX ----- TX
echo "$(((${RXnext}-${RXpre})/1024))KB/s   $(((${TXnext}-${TXpre})/1024))KB/s"

代码说明:
1、默认监视eth0流量,换算成KB所以精度不高,需要精确数据时可以不除以1024。 
2、限于sleep命令的间隔最小为秒,本脚本检测到的数据实时性仅作参考。

调用方法:
 

复制代码代码示例:
watch -n 1 ./interface.sh

即可开始监看流量,按ctrl+c中断监测,退出。

以上用到了watch命令,可以实时显示监测结果到屏幕上。

 

以上代码,只能监测在eth0上,且间隔只能为1秒,因为脚本中固定了这些参数值。
下面是此脚本的改进版,可以接收二个参数值,一是要监测的网卡接口,比如eth0,另一个参数是监测的间隔时间。

代码如下:
 

复制代码代码示例:

#!/bin/bash
#filename interface.sh

usage() {
  echo "Useage : $0"
  echo "eg. sh $0 eth0 3"
  exit 1
}

if [ $# -lt 2 ]
then
   usage
fi

eth=$1
timer=$2

eth=eth0
RXpre=$(ifconfig ${eth} | grep bytes | awk  '{print $2}'| awk -F":" '{print $2}')
TXpre=$(ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')
sleep $timer
RXnext=$(ifconfig ${eth} | grep bytes | awk  '{print $2}'| awk -F":" '{print $2}')
TXnext=$(ifconfig ${eth} | grep bytes | awk '{print $6}' | awk -F":" '{print $2}')

echo RX ----- TX
echo "$(((${RXnext}-${RXpre})/1024))KB/s   $(((${TXnext}-${TXpre})/1024))KB/s"

调用示例:
 

watch

 

watch

以上多次用到watch命令,它主要用来实时监测命令的运行结果。

下面补充下watch命令的用法。

watch命令。

Usage: watch [-dhntv] [--differences[=cumulative]] [--help] [--interval=] [--no-title] [--version] 
  -d, --differences[=cumulative]        highlight changes between updates
                (cumulative means highlighting is cumulative)
  -h, --help                            print a summary of the options
  -n, --interval=              seconds to wait between updates
  -v, --version                         print the version number
  -t, --no-title                        turns off showing the header

watch -- 监测命令的运行结果

watch是一个非常实用的命令,基本所有的Linux发行版都带有这个小工具,watch可以实时监测一个命令的运行结果。

在Linux下,watch是周期性的执行下个程序,并全屏显示执行结果。

-d, --differences[=cumulative] 高亮显示变动
-n, --interval= 周期(秒)

如:

复制代码代码示例:
watch -n 1 -d netstat -ant
 

其它操作:
切换终端: Ctrl+x
退出watch:Ctrl+g
 

复制代码代码示例:
watch -n 1 -d 'pstree|grep http'

每隔一秒高亮显示http链接数的变化情况。
后面接的命令若带有管道符,需要加''将命令区域归整。

在查看攻击时,经常使用的方式如下:
实时查看模拟攻击客户机建立起来的连接数,使用:
 

复制代码代码示例:
watch 'netstat -an | grep:21 | \ grep<模拟攻击客户机的IP>| wc -l'  

查看模拟攻击客户机被 DROP 的数据包数:
 

复制代码代码示例:
watch 'iptables -L -n -v | \grep<模拟攻击客户机的IP>'
(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容