TCP 状态统计脚本
2016-02-26 by dongnan
举个栗子
通过 netstat & awk
命令 分析 tcp
连接状态,为 zabbix
采集数据提供数据支持。
使用
# 执行命令
bash -x /root/sh/tcp_stats.sh TIME_WAIT
脚本
# 执行命令
cat /root/sh/tcp_stats.sh
#!/bin/bash
#crontab
#* * * * * /bin/netstat -n | /bin/awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}' > /tmp/tcp_stat.txt
#variables
item="$1"
tmp_file='/tmp/tcp_stat.txt'
#functions
check_var() {
if grep $1 $tmp_file > /dev/null 2>&1 ;then
return 0
else
echo 0
return 1
fi
}
#main
case "$1" in
TIME_WAIT)
check_var $1 && awk '/TIME_WAIT/ {print $2}' $tmp_file
;;
FIN_WAIT1)
check_var $1 && awk '/FIN_WAIT1/ {print $2}' $tmp_file
;;
FIN_WAIT2)
check_var $1 && awk '/FIN_WAIT2/ {print $2}' $tmp_file
;;
ESTABLISHED)
check_var $1 && awk '/ESTABLISHED/ {print $2}' $tmp_file
;;
SYN_RECV)
check_var $1 && awk '/SYN_RECV/ {print $2}' $tmp_file
;;
CLOSING)
check_var $1 && awk '/CLOSING/ {print $2}' $tmp_file
;;
*)
echo "Usage: $0 {TIME_WAIT|FIN_WAIT1|FIN_WAIT2|ESTABLISHED|SYN_RECV|CLOSING}"
echo "Example: $0 CLOSING"
exit 1
;;
esac