shell脚本---linux定时检查ip端口

一、创建文本 port_scan4.txt ,写入需要检查的端口名称及IP PORT(注意格式):

#cat port_scan4.txt
edfh      172.16.120.4 7660  
ngd      172.16.120.5 7100  
14ds      172.16.120.2 9304  
ISdsf      172.16.120.4 7031  
oadf      172.16.121.66 9999 
oasd      172.16.121.66 9090

二、新建脚本 port_scan4.sh

#!/bin/bash
declare -i d=1

#获取文本数据并检查端口
function database()
{
data=`sed -n ''$1'p' /home/hik/port_scan4.txt | tr -s ' ' | cut -d " " -f 2,3`
name=`sed -n ''$1'p' /home/hik/port_scan4.txt | cut -d " " -f 1`
nc -w 2 -z $data 
if [ $? -ne 0 ] && [ -n $name ] ;
then
 printf "%s\n" $name异常
fi
}

#发送邮件函数
function send_mail()
{
    cat /home/hik/port_scan.txt | mail -s "端口告警" 614367859@qq.com
}

#循环执行database函数,port_scan4.txt有多少行执行多少次
function pd()
{
s=`cat /home/hik/port_scan4.txt | wc -l`
while [ $d -lt $s ] 
do
database $d >>/home/hik/port_scan.log 
let d++
done
nu=`cat -n /home/hik/port_scan.log | grep 时间 | awk 'END{printf "%s\n",$1}'`
number=`sed -n ''$nu',$p' /home/hik/port_scan.log | wc -l`
}

#剪切本次检查log内容到文本供邮件发送
function txt()
{
        nu=`cat -n /home/hik/port_scan.log | grep 时间 | awk 'END{printf "%s\n",$1}'`
        sed -n ''$nu',$p' /home/hik/port_scan.log > /home/hik/port_scan.txt
}

#主函数,判断端口是否有异常,无异常将端口正常写入log,有异常发送异常文本
function main()
{
printf "时间:$(date +"%Y-%m-%d %H:%M:%S")\n" >> /home/hik/port_scan.log
    pd
if [ $number -eq 1 ] ;
then
    printf "端口正常\n" >> /home/hik/port_scan.log
else
    txt
    send_mail
fi
}

#执行主函数
main

三、设置定时运行脚本

crontab -e

#每小时第29分钟运行
29 * * * * sh /home/hik/web_scan.sh

注意:脚本及文本都在目录/home/hik,引用记得修改文件目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值