Linux主機網絡流量監控ifstat
本監測方案是用ifstat。安裝方法參考:
http://man.linuxde.net/ifstat
1、下載
http://gael.roualland.free.fr/ifstat/ (官網) wget http://gael.roualland.free.fr/ifstat/ifstat-1.1.tar.gz
來自: http://man.linuxde.net/ifstat
也可以通過浏覽器下載,然後用secureCRT上傳;
2、安裝
tar -xzvfifstat-1.1.tar.gz,configure、make、make install
3、編寫腳本
- [root@localhost tools]# cat nic.sh
- #!/bin/bash
- start(){
- /opt/tools/ifstat_install/bin/ifstat -i eth1 -t >/opt/tools/nic.log &
- while [ 1 -eq 1 ]
- do
- date +%F\ %T >>/opt/tools/nic.log
- sleep 86400
- done
- }
- stop(){
- # if stay here,kill ifstat,sleep not execute.
- #echo 'kill nic.sh:'
- #ps -ef |grep nic |grep -v grep |awk '{print $2}' |while read pid1
- #do
- #kill -9 $pid1
- #echo $pid1
- #done
- echo 'kill ifstat:'
- ps -ef |grep ifstat |grep -v grep |awk '{print $2}' |while read pid2
- do
- kill -9 $pid2
- echo $pid2
- done
- echo 'kill sleep:'
- ps -ef |grep sleep |grep -v grep |awk '{print $2}' |while read pid3
- do
- kill -9 $pid3
- echo $pid3
- done
- echo 'kill nic.sh:'
- ps -ef |grep nic |grep -v grep |awk '{print $2}' |while read pid1
- do
- kill -9 $pid1
- echo $pid1
- done
- }
- case $1 in
- start)
- start
- ;;
- stop)
- stop
- ;;
- *)
- printf 'please input start|stop!\n'
- exit 1
- ;;
- esac
- #select process:
- #ps -ef |awk '/nic/||/ifstat/||/sleep/{print}'
- [root@localhost tools]#./nic.sh start &
執行了三次,查看進程:
- [mcbadm@loophole-scan ~]$ ps -ef |awk '/nic/||/ifstat/||/sleep/{print}'
- mcbadm 13472 12803 0 15:08 pts/1 00:00:00 /bin/bash ./nic.sh start
- mcbadm 13473 13472 0 15:08 pts/1 00:00:00 /opt/proxy_security/ifstat_install/bin/ifstat -i eth0 -t
- mcbadm 13475 13472 0 15:08 pts/1 00:00:00 sleep 8640
- mcbadm 13476 12803 0 15:08 pts/1 00:00:00 /bin/bash ./nic.sh start
- mcbadm 13477 13476 0 15:08 pts/1 00:00:00 /opt/proxy_security/ifstat_install/bin/ifstat -i eth0 -t
- mcbadm 13479 13476 0 15:08 pts/1 00:00:00 sleep 8640
- mcbadm 13480 12803 0 15:08 pts/1 00:00:00 /bin/bash ./nic.sh start
- mcbadm 13481 13480 0 15:08 pts/1 00:00:00 /opt/proxy_security/ifstat_install/bin/ifstat -i eth0 -t
- mcbadm 13483 13480 0 15:08 pts/1 00:00:00 sleep 8640
- mcbadm 13485 12803 0 15:08 pts/1 00:00:00 awk /nic/||/ifstat/||/sleep/{print}
- [mcbadm@loophole-scan ~]$
不知道為啥,需要執行兩次stop,才能關閉所有進程,不然會剩下幾個sleep進程,這些sleep的父進程id與ifstat的一樣。
#一天是86400秒,因為默認的ifstat -t 只能顯示時、分、秒,不能顯示日期,因為我想看到具體的時間所以就這麼弄了。
然後定期可以去分析nic.log文件,查看該網卡的流量情況。
關於kill也可以寫while的方式:#ps -ef |grep nic |grep -v grep |awk '{print $2}' |xargs -i kill -9 {}
有一個很怪的現象:當我把kill nic的語句寫在前面的時候,執行stop就只能執行kill nic的語句塊,後面兩個kill ifstat和kill sleep就無法執行,如果刪除了kill nic,後面兩個就可以正常執行,通過打印pid發現,kill nic放前面的話,輸出的有兩個無效的pid,最後選擇把kill nic放到了kill ifstat和kill sleep後面就可以。