shell脚本

 

shell练习题:nc后台监听

 【题目要求】

写一个脚本,每分钟检查一次nc是否在监听168168端口,如果没有监听则启动它

【核心要点】

1.crontab

/n,  n 代表数字,“每隔 n 单位间隔”的意思,例如每五分钟进行一次,则: * /5  *  *  *  *  command

2. pgrep

pgrep是首字母缩略词,代表“Process-ID Global Regular Expressions Print”。pgrep查看当前正在运行的进程,并将与选择条件匹配的进程ID列出到stdout(屏幕)。

-l,  列出进程名以及进程ID。  (pgrep only.)

-x,  仅匹配名称与模式完全匹配的进程(如果指定了-f则匹配命令行)

3. grep

-w  只选择那些包含构成整个单词的匹配项的行。

 【脚本】

! /bin/bash

if [ $(netstat -luntp | egrep ":168168\s" | wc -l) -eq 0 ]; then
        echo "start nc again!"
        nc -lvvp 168168  
fi

 

 

 参考 https://www.cnblogs.com/dingzp/category/1451837.html?page=2

 

shell习题第6题:监听80端口

【题目要求】

写一个脚本,判断本机的80端口(加入服务为httpd)是否开启,如果开启就什么都不做,如果发现端口不存在,那么重启一下httpd服务,并发邮件通知相关人员

【核心要点】

检测80端口使用nmap -p 80 127.0.0.1 或者 netstat -lntp | grep -w 80

重启httpd的相关命令

发邮件脚本依然使用mail.py

【脚本】

#!/bin/bash

m=123@123.com
while :
do
    n=`netstat -lntp | grep ':80 ' | wc -l`
    if [ $n -eq 0 ]; then
        /usr/local/apache2/bin/apachectl -k restart 2> /tmp/apache.err
        python mail.py $m "80端口关闭" "已经重启httpd服务"
        pn=`pgrep -l httpd | wc -l`

        if [ $pn -eq 0 ]; then
            python mail.py $m "httpd重启失败" "`head -1 /tmp/apache.err`"
        fi

    fi
    sleep 30 
done

 

posted @ 2021-03-04 19:13  信德维拉  阅读(83)  评论(0)    收藏  举报