1. 程式人生 > >day 14 11-15

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

[[email protected] 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

[[email protected] 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
~             

 

[[email protected] 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 "[email protected]" "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 "[email protected]" "wrong" "the httpd process is busy."
            exit
        fi
    fi
    sleep 10
done

例題14

[[email protected] 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