Shell脚本 (三)

1、菜单自动化软件部署

#!/bin/bash
path=/test
[ ! -d "$path" ] && mkdir $path #如果目录不存在,则创建目录

cat <<END
        1.[install lamp]
        2.[install lnmp]
        3.[exit]
        please input your want num:
END
read num       #接收用户选择的数字
expr $num + 1 &>/dev/null      #判断是否为整数
[ $? -ne 0 ] &&{               #根据返回值进行判断
        echo "the num you input must be {1|2|3}"
        exit 1
}

[ $num -eq 1 ] &&{          #如果用户选择1,则执行lamp安装的命令
        echo "start installing lamp."
        sleep 2;

        [ -x "$path/lamp.sh" ]||{    #判断脚本是否可执行,若不可执行则给予提示.
        echo "$path/lamp.sh does not exits or can not be exec."
        exit 1
}

$path/lamp.sh     #执行安装脚本,工作中建议用source $path/lamp.sh 替代
# source $path/lamp.sh    # 脚本中执行脚本,使用source 比 sh 或不加解释器更好一些
exit $?
}

[ $num -eq 2 ] &&{          #如果用户选择1,则执行lnmp安装的命令
        echo "start installing lnmp."
        sleep 2;

        [ -x "$path/lnmp.sh" ]||{    #判断脚本是否可执行,若不可执行则给予提示.
        echo "$path/lnmp.sh does not exits or can not be exec."
        exit 1
}

$path/lnmp.sh     #执行安装脚本,工作中建议用source $path/lnmp.sh 替代
# source $path/lnmp.sh    # 脚本中执行脚本,使用source 比 sh 或不加解释器更好一些
exit $?
}

[ $num -eq 3 ] && {      #用户输入3,则退出脚本
        echo bye.
        exit 3
}

# 有三种用户的输入不等于1、2或3的综合用法
[[ ! $num =~ [1-3] ]] && {       # <==[[]]的正则匹配方法
        echo "the num you input must be [1|2|3]"
        echo "Input error"
        exit 4
}

2、监控 Web 和 数据库 实例

  • 监控 Web 服务 和 Mysql 数据库服务师傅异常的常见方法 

端口监控

  1. 在服务器本地监控服务端口的常见命令   netstat 、ss 、lsof
  2. 从远端监控服务器本都端口的命令有 telnet 、nmap 、nc 

监控服务进程或进程数

  1. ps -ef | grep nginx | wc -l
  2. ps -ef | grep mysql | wc -l

在客户端模拟用户访问

  • 使用 wget 或 curl 命令进行测试
  1. 利用返回值 (echo $?) 进行判断
  2. 获取特殊字符串进行判断
  3. 根据HTTP响应 header 的情况进行判断

登陆 MySql 数据库判断

  • 通过 MySql 客户端连接数据库,根据返回值或返回内容判断
  1. mysql -uroot -p123 -e "select version();" &>/dev/null;echo $?
[root@zh shell]# wget --spider --timeout=10 --tries=2 www.baidu.com &>/dev/null
[root@zh shell]# echo $?
0
#在 wget 后面加 url 的检测方法, &>/dev/null 表示不输出,只看返回值  --spider 的意思是模拟爬取, --timeout=10的意思是 10秒钟, --tries=2 表示不成功,则重复2次.

[root@zh shell]# wget -T 10 -q --spider http://www.baidu.com >&/dev/null
[root@zh shell]# echo $?
0
# 用法同上, -q 表示安静的 

[root@zh shell]# curl -s -o /dev/null http://www.baidu.com 
[root@zh shell]# echo $?
0
# 利用 curl 进行检测,  -s 为沉默模式 , -o /dev/null 表示输出定向到空
  • 根据执行命令获取到的字符串进行判断,开发PHP或 Java 程序从数据库里取出指定的字符串,看和期待的值是否相等.
<?php
        //$link_id=mysql_connect{'主机名','用户','密码'};
        $link_id=mysql_connect{'zh','root','1'} or mysql_error();
        //$link_id=mysql_connect{'localhost','test',''}
        if ($link_id){

                echo "mysql successful by test !"
        }
                else{
                echo mysql_error();
        }
?>
  • 开发监控 MySql 数据库的脚本
方法一
#!/bin/bash 

if [ `netstat -lnt | grep 3306|awk -F ":::" '{print $2}'` -eq 3306 ]
# 这里的判断不是很好
# 1) 最好不要用整数进行比较,因为一旦端口不存在,取值就会为空,进行整数比较会报错
# 2) 不要根据列取具体的值,而是要过滤关键字,通过 wc 转成行数判断
        then
                echo "Mysql is Running !"
        else
                echo "Mysql is Stopped !"
        systemctl start mysqld
fi

方法二
#!/bin/bash 

if [ `netstat -lnt | grep 3306|awk -F ":::" '{print $2}'` = "3306" ]
# 这里的判断不是很好
# 1) 最好不要用整数进行比较,因为一旦端口不存在,取值就会为空,进行整数比较会报错
# 2) 不要根据列取具体的值,而是要过滤关键字,通过 wc 转成行数判断
        then
                echo "Mysql is Running !"
        else
                echo "Mysql is Stopped !"
        systemctl start mysqld
fi

方法三
#!/bin/bash
if [ `netstat -lnp | grep mysqld | wc -l` -gt 0 ] #过滤进称名,转成数字,不错.
        then
                echo "Mysql is running!"
        else
                echo "Mysql is stopped!"
        systemctl start mysqld
fi

方法四
#!/bin/bash 
[ `rpm -qa nmmp|wc -l` -lt 1 ] && yum install nmap -y &>/dev/null
# 防止 nmap 没有安装 而导致的错误
if [ `nmap 127.0.0.1 -p 3306 2>/dev/null | grep open|wc -l` -gt 0 ]
#远端的端口检查,过滤出open ,再转换成数字最佳
        then
                echo "Mysql is running !"
        else
                echo "Mysql is stopped"
        systemctl start mysqld
fi

方法五
#!/bin/bash 
[ `rpm -qa nc|wc -l` -lt 1 ] && yum -y install nc &>/dev/null
#防止没有安装 nc 而导致的错误
if [ `nc -w 2 127.0.0.1 3306 &>/dev/null && echo ok| grep ok|wc -l` -gt 0 ]
# 若 nc 执行成功,则输出和之后的过滤都没有问题,最后转换成数字
        then
                echo "Mysql is running ."
        else
                echo "Mysql is stopped."
        systemctl start mysqld
fi

方法六
#!/bin/bash 
if [ `ps -ef | grep -v grep|grep mysql|wc -l` -gt 0 ]  #grep -v grep 是排除此命令本身
	then 
		echo "Mysql is running."
	else
		echo "Mysql is stopped."
	systemctl start mysqld 
fi
  • 监控 Nginx web 服务的脚本
方法一
#!/bin/bash 

if [ `netstat -tulnp | grep nginx | awk -F "[  :]+" '{print $5}'` -eq 80 ]
#取端口数字表,有 Bug ,不建议使用,如果非用 取端口,则改为字符串比较的语法
        then
                echo "Nginx is running."
        else
                echo "Nginx is stopped."
        nginx
fi

方法二
#!/bin/bash 
if [ "`netstat -lnt| grep 80| awk -F "[ :]+" '{print $5}'`" = "80" ]
#字符串比较语法,取值太麻烦,不如过滤后转为行数再比较的方法好.
        then
                echo "Nginx is running."
        else
                echo "Nginx is stopped."
        nginx
fi

方法三
#!/bin/bash 

if [ `netstat -lntup | grep nginx | wc -l` -gt 0 ]
        then
                echo "Nginx is running."
        else
                echo "Nginx is stopped."
        nginx
fi

方法四
#!/bin/bash 

if [ `lsof -i tcp:80|wc -l` -gt 0 ]
        then
                echo "Nginx is running ."
        else
                echo "Nginx is stopped."
        nginx
fi

方法五
#!/bin/bash 
[ `rpm -qa nmap | wc -l` -lt 1 ] && yum -y install nmap &>/dev/null
	if [ `nmap 127.0.0.1 -p 80 2>/dev/null| grep open | wc -l` -gt 0 ]
# nmap 检测方法,优势是适合从远端进行检查,推荐
	then
		echo "Nginx is running."
	else
		echo "Nginx is stopped."
	nginx
fi

方法六
#!/bin/bash 
[ `rpm -qa nc | wc -l` -lt 1 ] && yum install nc -y &>/dev/null
if [ `nc -w 2 127.0.0.1 80 &>/dev/null&&echo ok| grep ok|wc -l` -gt 0 ]
        then
                echo "Nginx is Running."
        else
                echo "Nginx is Stopped."
        nginx
fi

方法七
#!/bin/bash 
if [ `ps -ef| grep -v grep|grep nginx|wc -l` -ge 1 ]
        then
                echo "Nginx is running."
        else
                echo "Nginx is stopped."
        nginx
fi

方法八
#!/bin/bash 
if [[ `curl -I -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1` =~ [23]0[012] ]]
#获取状态码,然后做正则数字匹配。目标是200.301.302.
	then
		echo "Nginx is running."
	else
		echo "Nginx is stopped."
	nginx
fi

方法九
#!/bin/bash 

if [ `curl -I http://127.0.0.1 2>/dev/null|head -1 | egrep "200|302|301"|wc -l` -eq 1 ]
#通过扩展的egrep 过滤正确的状态码,然后利用 wc 转成数字
        then
                echo "Nginx is running."
        else
                echo "Nginx is stopped."
        nginx
fi

方法十
#!/bin/bash 
if [ "`curl -s http://127.0.0.1`" = "Welcome to nginx!"]
# 根据访问网站URL,将返回值和期待的值进行比较,适用于更深层次额对网站集群的应用检测
        then
                echo "Nginx is running."
        else
                echo "Nginx is stopped."
        nginx
fi

3、监控 Memcached 缓存服务

[root@zh ~]# memcached -d -m 64M -u root -l 192.168.1.5 -p 11211
#!/bin/bash 
if [ `netstat -tulnp | grep 11211| wc -l` -lt 1 ]
# 若端口对应的行数小于1.则说明服务未启动
        then
                echo "Memcached service is error"
        exit 1
fi
printf "del key\r\n"| nc 192.168.1.5 11211 &>/dev/null #删除缓存中的key对应的值
printf "set key 0 0 10 \r\zhcool1234\r\n"| nc 192.168.1.5 11211 &>/dev/null
# 添加新值
McValues=`printf "get key\r\n" | nc 192.168.1.5 11211 | grep zhcool1234|wc -l`
#查看新值,如果查到了,则进入判断

if [ $McValues -eq 1 ] 
        then
                echo "Memcached status is ok"
        else
                echo "Memcached status is bad"
fi 

4、开发脚本实现入侵检测与报警

  • 建立测试数据
[root@zh ~]# mkdir -p /var/html/www
[root@zh ~]# cp -a /etc/a* /var/html/www/
[root@zh ~]# cp -a /etc/b* /var/html/www/
[root@zh ~]# ls /var/html/www/
abrt     aliases     alternatives  asound.conf  audisp  bash_completion.d  binfmt.d
adjtime  aliases.db  anacrontab    at.deny      audit   bashrc
  • 建立初始文件指纹库
[root@zh ~]# find /var/html/www/ -type f | xargs md5sum > /opt/zhiwen.db.ori
[root@zh ~]# tail /opt/zhiwen.db.ori 
5268b3307afca1caef0dd41d66fb6a6b  /var/html/www/bash_completion.d/rhn-migrate-classic-to-rhsm
147093de19a776b8f6934dbfec73101a  /var/html/www/bash_completion.d/rhsm-debug
5e59b229b31798d00b1edcc3fc4eff85  /var/html/www/bash_completion.d/rhsm-icon
0be9e35cd7cf6776dd7823c68fd99c37  /var/html/www/bash_completion.d/rhsmcertd
804d340ad77e74202b7b6499de91797d  /var/html/www/bash_completion.d/subscription-manager
1215cec8b7cc508972f66f19e46f65b1  /var/html/www/bash_completion.d/iprutils
7ca61969ad2fbb5fe8ce81f0be130f13  /var/html/www/bash_completion.d/yum-utils.bash
68dfd9d60030637f9bb986352e36208c  /var/html/www/bash_completion.d/redefine_filedir
21db8284487c215d141e51bb5eb6669e  /var/html/www/bash_completion.d/scl.bash
3f48a33cc1fce59ff2df86429151c0e0  /var/html/www/bashrc
  • 建立初始的文件库
[root@zh ~]# find /var/html/www/ -type f > /opt/wenjian.db.ori
[root@zh ~]# tail /opt/wenjian.db.ori 
/var/html/www/bash_completion.d/rhn-migrate-classic-to-rhsm
/var/html/www/bash_completion.d/rhsm-debug
/var/html/www/bash_completion.d/rhsm-icon
/var/html/www/bash_completion.d/rhsmcertd
/var/html/www/bash_completion.d/subscription-manager
/var/html/www/bash_completion.d/iprutils
/var/html/www/bash_completion.d/yum-utils.bash
/var/html/www/bash_completion.d/redefine_filedir
/var/html/www/bash_completion.d/scl.bash
/var/html/www/bashrc
  • 检测文件内容变化
[root@zh ~]# echo zhcool >> /var/html/www/audisp/plugins.d/af_unix.conf 
[root@zh ~]# export LANG=en
[root@zh ~]# md5sum -c --quiet /opt/zhiwen.db.ori 
/var/html/www/audisp/plugins.d/af_unix.conf: FAILED
md5sum: WARNING: 1 computed checksum did NOT match
  • 检测文件数量变化
[root@zh ~]# echo test.txt > /var/html/www/qq.txt
[root@zh ~]# find /var/html/www/ -type f > /opt/wenjian.db_curr.ori 
[root@zh ~]# diff /opt/wenjian.db*
34d33
< /var/html/www/qq.txt
  • 开发检查指纹识别的脚本
[root@zh ~]# find /var/html/www/ -type f | xargs md5sum > /opt/zhiwen.db.ori
[root@zh ~]# find /var/html/www/ -type f > /opt/wenjian.db.ori
#!/bin/bash 
RETVAL=0     #状态初始化
export LANG=en        #调整字符集
CHECK_DIR=/var/html/www     #定义要检测的站点目录
[ -e $CHECK_DIR ]|| exit 1     #如果目录不存在则退出脚本
zhiwendbori="/opt/zhiwen.db.ori"    #定义原始指纹库路径
filecountdbori="/opt/wenjian.db.ori"         #定义原始文件库路径
errorlog="/opt/err.log"          #定义检测后的内容日志

[ -e $zhiwendbori ] || exit 1    #如果原始指纹库不存在则退出脚本
[ -e $filecountdbori ] || exit 1  #如果原始文件库不存在则退出脚本

echo "[root@zh shell]# md5sum -c --quiet /opt/zhiwen.db.ori">$errorlog

md5sum -c --quiet /opt/zhiwen.db.ori &>>$errorlog   #实际执行命令
RETVAL=$?

find $CHECK_DIR -type f >/opt/wenjian.db.ori
echo "[root@zh shell]# diff /opt/wenjian.db*" &>>$errorlog  #打印检测命令
diff /opt/wenjian.db* &>>$errorlog

if [ $RETVAL -ne 0 -o `diff /opt/wenjian.db*|wc -l` -ne 0 ]
	then 
	mail -s "`uname -n` $(date +%F) err" 23416415662@qq.com < $errorlog
	else
	echo "Sites dir is ok"| mail -s "`uname -n` $(date +%F) is ok"
fi

开发 Rsync 服务启动脚本

#!/bin/bash
# chkconfig: 2345 20 80   # 2345 服务的运行级别,20是开机的启动顺序,80是脚本的停止顺>序,这两个数字不超过99,一般情况下,可以根据服务的启动需求来选择,应用服务一般要靠后启动为准,越早停止越好.
# desscription: Saves and restors system entropy pool

if [ $# -ne 1 ]
        then
                echo $"usage:$0{start|stop|restart}"
        exit 1
fi
if [ "$1" = "start" ]
        then
        rsync --daemon
        if [ `netstat -tulnp | grep rsync|wc -l` -ge 1 ]
                then
                echo "rsync is started."
        exit 0
        fi
elif [ "$1" = "stop" ]   
        then
        pkill rsync      
        if [ `netstat -tulnp | grep rsync | wc -l` -eq 0 ]
        then
                echo "rsync is stoped."
        exit 0
        fi
elif [ "$1" = "restart" ]
        then
        pkill rsync
        sleep 2
        rsync --daemon
else
        echo $"usage:$0{start|stop|restart}"
        exit 1
fi

[root@zh shell]# chkconfig --add rsync
[root@zh shell]# chkconfig --list | grep rsync

注意:该输出结果只显示 SysV 服务,并不包含原生 systemd 服务。SysV 配置数据可能被原生 systemd 配置覆盖。 
      如果您想列出 systemd 服务,请执行 'systemctl list-unit-files'。
      欲查看对特定 target 启用的服务请执行
      'systemctl list-dependencies [target]'。

rsync          	0:关	1:关	2:开	3:开	4:开	5:开	6:关

这个脚本一定要放在 /etc/init.d/下面才可以添加

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值