1. 程式人生 > >shell訓練營Day14

shell訓練營Day14

練習11
寫一個指令碼實現如下功能: 
輸入一個數字,然後執行對應的一個命令。

顯示命令如下:

*cmd meau**  1 - date 2 - ls 3 - who 4 - pwd
當輸入1時,會執行date, 輸入2時執行ls, 以此類推。

核心要點

  • case判斷

#!/bin/bash
read -p "Please input a number: " n
echo "*cmd meau**  1 - date 2 - ls 3 - who 4 - pwd"

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

練習十二
用shell指令碼實現如下需求:

新增user_00 – user_09 10個使用者,並且給他們設定一個隨機密碼,密碼要求10位包含大小寫字母以及數字,注意需要把每個使用者的密碼記錄到一個日誌檔案裡。
 
提示:

  1. 隨機密碼使用命令 mkpasswd

  2. 在指令碼中給使用者設定密碼,可以使用echo 然後管道passwd命令

核心要點

  • seq實現數字遞增
  • mkpasswd產生隨機字元

#!/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

練習十三
在伺服器上,寫一個監控指令碼,要求如下:

  1. 每隔10s去檢測一次伺服器上的httpd程序數,如果大於等於500的時候,就需要自動重啟一下apache服務,並檢測啟動是否成功?

  2. 若沒有正常啟動還需再一次啟動,最大不成功數超過5次則需要立即發郵件通知管理員,並且以後不需要再檢測!

  3. 如果啟動成功後,1分鐘後再次檢測httpd程序數,若正常則重複之前操作(每隔10s檢測一次),若還是大於等於500,那放棄重啟並需要發郵件給管理員,然後自動退出該指令碼。假設其中發郵件指令碼為之前使用的mail.py

核心要點

  • pgrep -l httpd或者ps -C httpd --no-heading檢查程序
  • for迴圈5次計數器

#!/bin/bash
check_service()
{
n=0
for i in seq 1 5
do
/usr/local/apache2/bin/apachectl restart 2>/tmp/hpptd.err
if [ $? -ne 0 ]
then
n=$[$n+1]
else
break
fi
done
if [ $n -eq 5 ]
then
python mai.py "[email protected]" "httpd down" cat /tmp/httpd.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]" "httpd somth wrong" "the httpd process is busy."
exit
fi
fi
sleep 10
done

練習十四
需求: 根據web伺服器上的訪問日誌,把一些請求量非常高的ip給拒絕掉!並且每隔半小時把不再發起請求或者請求量很小的ip給解封。
 

核心要點

  • 統計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

練習十五
請仔細檢視如下幾個數字的規律,並使用shell指令碼輸出後面的十個數字。

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