day 14 11-15
例题11
#!/bin/bash echo "*cmd meau** 1 - date 2 - ls 3 - who 4 - pwd" read -p "Please input a number: " n if [ -z "$n" ] then echo "请输入一个纯数字,范围1-4." exit fi n1=`echo $n|sed 's/[0-9]//g'` if [ -n "$n1" ] then echo "请输入一个纯数字,范围1-4." exit fi case $n in 1) date ;; 2) ls ;; 3) who ;; 4) pwd ;; *) echo "请输入1-4的数字" ;; esac
例题12
[root@iZwz96qzfgxh9l2rk7esxnZ xiti]# vim 12.sh #添加user_00 – user_09 10个用户,并且给他们设置一个随机密码,密码要求10位包含大小写字母以及数字 #!/bin/bash for i in `seq -w 00 09` do useradd user_$i p=`mkpasswd -l 10 -s 0 ` echo "user_$i $p" >> /tmp/pass.tmp echo $p |passwd --stdin user_$i done ~ ~ ~
例题13
[root@iZwz96qzfgxh9l2rk7esxnZ xiti]# vim 15.sh #输出后面的十个数字。10 31 53 77 105 141 ……. #!/bin/bash x=10 y=21 for i in `seq 0 15` do echo $x x=$[$x+$y] z=$[2**$i] y=$[$y+$z] done ~
[root@iZwz96qzfgxh9l2rk7esxnZ xiti]# vim 13.sh #每隔10s去检测一次服务器上的httpd进程数,如果大于等于500的时候,就需要自动重启#一下apache服务,并检测启动是否成功若没有正常启动还需再一次启动,最大不成功数#超过5次则需要立即发邮件通知管理员,并且以后不需要再检测!如果启动成功后,1分钟后#再次检测httpd进程数,若正常则重复之前操作(每隔10s检测一次),若还是大于等于#500,那放弃重启并需要发邮件给管理员,然后自动退出该脚本。 #!/bin/bash check_service() { n=0 for i in `seq 1 5` do /usr/local/apache2/bin/apachectl restart 2>/tmp/apache.err if [ $? -ne 0 ] then n=$[$n+1] else break fi done if [ $n -eq 5 ] then python mai.py "123@qq.com" "httpd service down" `cat /tmp/apache.err` exit fi } while true do t_n=`ps -C httpd --no-heading |wc -l` if [ $t_n -ge 500 ] then /usr/local/apache2/bin/apachectl restart if [ $? -ne 0 ] then check_service fi sleep 60 t_n=`ps -C httpd --no-heading |wc -l` if [ $t_n -ge 500 ] then python mai.py "123@qq.com" "wrong" "the httpd process is busy." exit fi fi sleep 10 done
例题14
[root@iZwz96qzfgxh9l2rk7esxnZ xiti]# vim 14.sh #统计ip访问次数,排序,如何标记每隔半小时,iptables计数器是一个重要的判断指标,函数(封IP、解封IP) #!/bin/bash block_ip() { t1=`date -d "-1 min" +%Y:%H:%M` log=/data/logs/access_log egrep "$t1:[0-9]+" $log > /tmp/tmp_last_min.log awk '{print $1}' /tmp/tmp_last_min.log |sort -n |uniq -c|sort -n |awk '$1>100 {print $2}' > /tmp/bad_ip.list n=`wc -l /tmp/bad_ip.list|awk '{print $1}'` if [ $n -ne 0 ] then for ip in `cat /tmp/bad_ip.list` do iptables -I INPUT -s $ip -j REJECT done fi } unblock_ip() { iptables -nvL INPUT|sed '1d' |awk '$1<5 {print $8}' > /tmp/good_ip.list n=`wc -l /tmp/good_ip.list|awk '{print $1}'` if [ $n -ne 0 ] then for ip in `cat /tmp/good_ip.list` do iptables -D INPUT -s $ip -j REJECT done fi iptables -Z } t=`date +%M` if [ $t == "00" ] || [ $t == "30" ] then unblock_ip block_ip else block_ip fi
例题15