shell脚本监视具有相同IP的多个连接

时间:2017-10-04 04:25:36

标签: linux shell netstat

我正在尝试监控进入Linux服务器的连接,这些连接具有连接到同一端口的相同IP。是否可以监控特定的IP地址,仅在它不存在2次时发出警报?

示例:

netstat -an | grep 000

101.101.101.101:2000        ESTABLISHED
101.101.101.101:2000        ESTABLISHED
101.101.101.102:3000        ESTABLISHED
101.101.101.102:3000        ESTABLISHED

我想警告101.101.101.101或101.101.102是否每次都不会退出2次。

我的剧本:

connections=('101.101.101.101' '101.101.101.102')
running=( $(netstat -an |grep 000 |awk '{print $1}') )
non_running=()
for process_name in ${connections[@]}; do
    if [[ "${running[*]}" == *$process_name* ]]; then
        echo "$process_name is running"
    else
        echo "$process_name is not running"
    fi
done

1 个答案:

答案 0 :(得分:0)

以下脚本可以帮助您。

netstat -an | awk -v s1="\"" '
function check(ip,count,email_id){
  if(count<2){
    system("echo " s1 "IP " ip " 2 count not found." s1 " |  mailx -s " s1 " Alert email IP " ip " 2 times occurence not found." s1 FS email_id)
}
  else{
    print ip " is running fine."}
}
/101.101.101.101/{
  count1++
}
/101.101.101.102/{
  count2++
}
END{
  check(101.101.101.101,count1,"test@chumma.com");
  check(101.101.101.102,count2,"test@chumma.com")
}
' 

说明: 因此它将运行命令netstat -an并将其标准输出作为awk命令的标准输入。在awk命令中,如果您看到我创建了一个名为function的{​​{1}},那么您可以为任何IP调用它(我们必须在标准输入读取时检查它的数量),在check的END块中,您可以使用传递给它的属性awk来调用此函数。它应该打印如果All is Well(表示该变量的数量大于或等于2,如果你只想要计数2然后将我的代码的条件改为eg--> check(IP,count_variable,your_email_where_you_want_to_alert)以上的函数),否则它将发送电子邮件到id,你将提供功能。