习题1:批量更改文件名

要求:

  1. 找到/123目录下所有后缀名为.txt的文件

  2. 批量修改.txt为.txt.bak

  3. 把所有.bak文件打包压缩为123.tar.gz

  4. 批量还原文件的名字,即把增加的.bak再删除

参考答案:

#!/bin/bash
# date:2018年2月7日
cd /root/123
find . -type f -name "*.txt" > /tmp/txt.list
for f in `cat /tmp/txt.list`
do
   mv $f $f.bak
done
d=`date +"%Y%m%d%H%M%S"`
tar -zcf $d.tar.gz *.bak
for f in `cat /tmp/txt.list`
do
   mv $f.bak $f
done

当然你也可以把txt文件复制出来,然后打包压缩。但是还要手动删除呢

#!/bin/bash
# date:2018年2月7日
cd /root/123
for txt in `ls |grep -E ".txt$"`
do
   # echo "$txt"
   cp "$txt" /tmp/123/ 2>/dev/null
done
cd /tmp/123/
find . -name "*.txt"|xargs -i mv {} {}.bak
d=`date +"%Y%m%d%H%M%S"`
tar -zcf $d.tar.gz *.bak


习题2:监控80端口

要求:写一个脚本,判断本机的80端口(假如服务为httpd)是否开启着,如果开启着什么都不做,如果发现端口不存在,那么重启一下httpd服务,并发邮件通知你自己。脚本写好后,可以每一分钟执行一次,也可以写一个死循环的脚本,30s检测一次

参考答案:

#!/bin/bash
# date:2018年2月7日
email="your_email@163.com"
while :
do
   result=`netstat -lntp| grep ":80 "|grep LISTEN| wc -l`
   if [ $result -eq "1" ];then
        continue
   else
        python /usr/local/sbin/mail.py "$email" "check_80" "The 80 port is down."
        /usr/local/apache2.4/bin/apachectl restart >/dev/null 2>/dev/null
        n=`ps aux|grep httpd|grep -cv grep`
        if [ $n -eq 0 ];then
           /usr/local/apache2.4/bin/apachectl start 2>/tmp/apache_start.err
        fi
        if [ -s /tmp/apache_start.err ];then
           python /usr/local/sbin/mail.py "$email" "apache_start_error" "`cat /tmp/apache_start.err`"
        fi
   fi
   sleep 30
done


邮件脚本mail.py:http://blog.51cto.com/11924224/2069732