案例一:批量生產隨機字符檔案名
使用for回圈在/oldboy目錄下批量創建10個html檔案,其中每個檔案需要包含10個隨機小寫字母加固定字串oldboy,名稱示例如下:xxxxxxxxxx_oldboy.html
#!/bin/bash
#
DIR=/oldboy
[ -d /oldboy ] || mkdir $DIR
for i in {1..10}
do
filename=`head /dev/urandom | md5sum |tr [0-9] [a-z] | cut -c 1-10`
touch $DIR/${filename}_oldboy.html
done
exit 0
案例二:批量改檔案名
將上面案例中結果檔案名中的oldboy字串全部改成oldgirl(最好用for回圈實作),并且將擴展名html全部改成大寫,
#!/bin/bash
#
DIR=/oldboy
cd $DIR
file_list=(`ls *oldboy.html`)
filenum=${#file_list[@]}
file=0
while [ $file -lt $filenum ]
do
newfilename=${file_list[$file]%%_*}_oldgirl.HTML
mv ${file_list[$file]} $newfilename
let "file += 1"
done
exit 0
案例三:批量創建特殊要求用戶
批量創建10個系統帳號oldboy01-oldboy10并設定密碼(密碼為亂數,要求字符和數字等混合),
#!/bin/bash
#
for i in oldboy{01..10}
do
useradd $i &> /dev/null
if [ $? -eq 0 ];then
password="`head /dev/urandom | md5sum | cut -c 1-10`"
echo $i $password >> /tmp/user_passwd.log
echo $password | passwd --stdin $i &> /dev/null
echo "$i 創建成功"
else
echo "創建用戶失敗"
fi
done
exit 0
案例四:掃描網路記憶體活主機
寫一個Shell腳本,判斷192.168.1.0/24網路里,當前在線的IP有哪些,
#!/bin/bash
#
for i in 192.168.1.{1..254}
do
ping -c 2 -w 2 $i &> /dev/null
if [ $? -eq 0 ];then
echo "$i 在線"
else
echo "$i 未在線"
fi
done
exit 0
案例五:解決DOS
請根據web日志或者或者網路連接數,監控當某個IP并發連接數或者短時內PV達到100(讀者根據實際情況設定),即呼叫防火墻命令封掉對應的IP,
防火墻命令為:iptables-I INPUT -s IP地址 -j DROP,
#!/bin/bash
#
LOG=/usr/local/nginx/logs/access.log
cat /dev/null > /tmp/rizhi.log
awk '{print $1}' $LOG | sort -nr | uniq -c > /tmp/rizhi.log
num=(`awk '{print $1}' /tmp/rizhi.log`)
IPADDR=(`awk '{print $2}' /tmp/rizhi.log`)
i=0
while [ $i -lt "${#num[@]}" ]
do
if [ "${num[$i]}" -gt 100 ];then
echo "存在惡意攻擊ip: "${IPADDR[$i]}""
#iptables-I INPUT -s "$IPADDR" -j DROP
fi
let "i += 1"
done
exit 0
案例六:MySQL資料庫分庫分表備份
#!/bin/bash
#
Mycmd="mysql -uroot -pZHHS_root11"
Mydump="mysqldump $Mycmd --all-databases "
DBlist=`$Mycmd -e "show databases;" | sed '1d' | egrep -v "_schema|mysql"`
[ -d /tmp/mysql_bak/ ] || mkdir -p /tmp/mysql_bak
for database in $DBlist
do
TableList=`$Mycmd -e "show tables from $database;" | sed 1d`
for table in $TableList
do
[ -d /tmp/mysql_bak/${database} ] || mkdir -p /tmp/mysql_bak/${database}
$Mydump $database $table > /tmp/mysql_bak/${database}/${table}_$(date +%F).sql
done
echo -e "\033[32m mysqldump $database is ok !!! \033[0m"
done
exit 0
案例七:篩選符合長度的單詞
利用bash for回圈列印下面這句話中字母數不大于6的單詞
I am oldboy teacher welcome to oldboy trainingclass
#!/bin/bash
#
str_list=(I am oldboy teacher welcome to oldboy trainingclass)
num=${#str_list[@]}
i=0
while [ $i -lt $num ]
do
if [ ${#str_list[$i]} -le 6 ];then
echo ${str_list[$i]}
fi
let "i += 1"
done
exit 0
案例八:比較整數大小
開發shell腳本分別實作以腳本傳參及read讀入的方式比較2個整數大小,
注意:一共是開發2個腳本,當用腳本傳參以及read讀入的方式需要對變數是否為數字、并且傳參個數不對給予提示,
傳參腳本
#!/bin/bash
#
E_ARG=65
if [ $# -eq 2 ];then
true
else
echo "用法:`basename $0` number1 number2"
exit $E_ARG
fi
a=`let "$1 * $2"` &> /dev/null
if [ $? -eq 0 ];then
if [ $1 -gt $2 ];then
echo "$1 大于 $2"
elif [ $1 -eq $2 ];then
echo "$1 等于 $2"
else
echo "$1 小于 $2"
fi
else
echo "用法:`basename $0` number1 number2"
exit 66
fi
exit 0
read腳本
#!/bin/bash
#
read -t 10 -p "請輸入第一個數字(您有10秒的時間) " num1
if [ -z $num1 ];then
echo;echo"超時"
exit 65
fi
read -t 10 -p "請輸入第二個數字(您有10秒的時間) " num2
if [ -z $num2 ];then
echo;echo"超時"
exit 65
fi
a=`let "$num1 * $num2"` &> /dev/null
if [ $? -eq 0 ];then
if [ $num1 -gt $num2 ];then
echo "$num1 大于 $num2"
elif [ $num1 -eq $num2 ];then
echo "$num1 等于 $num2"
else
echo "$num1 小于 $num2"
fi
else
echo "請輸入阿拉伯數字"
exit 66
fi
exit 0
案例九:選單自動化軟體部署
列印選擇選單,按照選擇一鍵安裝不同的Web服務
要求:
1、當用戶輸入1時,輸出“startinstalling lamp.提示”然后執行/tmp/lamp.sh,腳本內容輸出"lampis installed"后退出腳本,作業中就是正式lamp一鍵安裝腳本,
2、當用戶輸入2時,輸出“startinstalling lnmp.提示” 然后執行/tmp/lnmp.sh輸出"lnmpis installed"后退出腳本,作業中就是正式lnmp一鍵安裝腳本,
3、當輸入3時,退出當前選單及腳本,
4、當輸入任何其它字符,給出提示“Input error”后退出腳本,
5、要對執行的腳本進行相關的條件判斷,例如:腳本檔案是否存在,是否可執行等判斷,盡量用上前面講解的知識點,
#!/bin/bash
#
echo "1.[install lamp]
2.[install lnmp]
3.[exit]
"
read -t 10 -p "請選擇要操作的步驟(1/2/3),您有10秒的時間 " num
if [ -z "$num" ];then
echo;echo "超時"
exit 63
fi
case $num in
1)
if [ -e /tmp/lamp.sh ];then
if [ -x /tmp/lamp.sh ];then
/tmp/lamp.sh
echo "lampis installed"
else
echo "/tmp/lamp.sh 沒有權限"
fi
else
echo "/tmp/lamp.sh 不存在"
fi
;;
2)
if [ -e /tmp/lnmp.sh ];then
if [ -x /tmp/lnmp.sh ];then
/tmp/lnmp.sh
echo "lnmpis installed"
else
echo "/tmp/lnmp.sh 沒有權限"
fi
else
echo "/tmp/lnmp.sh 不存在"
fi
;;
3)
exit 64;;
*)
echo "Input error"
exit 65
esac
exit 0
案例十:Web及MySQL服務例外監測
用if條件陳述句實作對Nginx服務是否正常進行檢測,如果服務未啟動,則啟動相應服務,
#!/bin/bash
#
NGINX=`ss -natpul | grep nginx | wc -l`
if [ $NGINX -gt 0 ];then
echo "nginx is running!"
exit 0
else
echo "nginx is not running!"
fi
echo "
1.[start]
2.[exit]
"
read -t 10 -p "是否啟動nginx(1/2)?您有10秒的時間考慮 " action
if [ -z "$action" ];then
echo "超時,默認啟動nginx"
/usr/local/nginx/sbin/nginx start
fi
case $action in
1)
echo "即將啟動nginx"
/usr/local/nginx/sbin/nginx start
;;
2)
exit;;
*)
echo "Input error"
exit 65
esac
exit 0
案例十一:防篡改檢測與報警
監控web站點目錄(/var/html/www)下所有檔案是否被惡意篡改,如果有就列印改動的檔案名(發郵件),
#!/bin/bash
#
html_file=(`find /var/html/www -type f`)
html_file_sum=${#html_file[@]}
md5_dir=/tmp/checkdir
[ ! -d $md5_dir ] && mkdir -p $md5_dir
i=0
while [ $i -lt $html_file_sum ]
do
md5sum ${html_file[$i]} >> $md5_dir/o.txt
let "i += 1"
done
md5sum -c $md5_dir/o.txt | grep FAILED >> $md5_dir/n.txt
if [ -s $md5_dir/n.txt ];then
echo "`cat $md5_dir/n.txt | uniq`" | mail -s "`date +"%F %H:%M:S"` WEB 被篡改" wpf_buhei@163.com
#echo "`awk -F ":" '{print $1}' $md5_dir/n.txt | uniq ` : 被篡改"
else
true
#echo "正常"
fi
exit 0
案例十二:開發nginx服務啟動腳本
要求:
1.要使用系統函式庫技巧,
2.要用函式,不能一坨command的方式,
3.可被chkconfig管理,
#!/bin/bash
#/etc/init.d/nginx
#
#:如果需要被chkconfig管理,就必須添加一下面兩行
# chkconfig: - 88 35
# description: nginx is a World Wide Web server. It is used to serve
#
NGINXBIN=/usr/local/nginx/sbin/nginx
TIMEOUT=5
NginxStart()
{
NGINXPID=`ss -natpul | grep nginx`
STARTTIME=0
if [ -z "$NGINXPID" ];then
echo "soon start is NGINX"
$NGINXBIN
while [ $STARTTIME -le $TIMEOUT ]
do
NginxPid=`ss -natpul | grep nginx`
if [ ! -z "$NginxPid" ];then
echo "NGINX start OK"
break
else
sleep 1
let "STARTTIME += 1"
fi
done
elif [ $STARTTIME -gt $TIMEOUT ];then
echo "ERROR:nginx start timeout"
exit 66
else
echo "NGINX is running"
fi
}
NginxStop()
{
NGINXPID=`ss -natpul | grep nginx`
STOPTIME=0
if [ ! -z "$NGINXPID" ];then
echo "soon stop is NGINX"
$NGINXBIN -s stop
while [ $STOPTIME -le $TIMEOUT ]
do
NginxPid=`ss -natpul | grep nginx`
if [ -z "$NginxPid" ];then
echo "NGINX stop OK"
break
else
let "STOPTIME += 1"
sleep 1
fi
done
elif [ $STOPTIME -gt $TIMEOUT ];then
echo "ERROR:nginx stop timeout"
exit 67
else
echo "nginx is not running"
fi
}
case $1 in
start)
NginxStart
;;
stop)
NginxStop
;;
restart)
NginxStop
NginxStart
;;
*)
echo "USAGE: `basename $0` [start|stop|restart]"
esac
exit 0
chmod + x /etc/init.d/nginx
chkconfig --add nginx
案例十三:學生抓鬮
1、執行腳本后,想去的同學輸入英文名字全拼,產生亂數1-99之間的數字,數字大的去參加專案實踐,前面已經抓到的數字,下次不能再出現相同數字,
2、第一個輸入名字后,螢屏輸出資訊,并將名字和數字記錄到檔案里,程式不能退出繼續等待別的學生輸入,
#!/bin/bash
#
FILE=/tmp/temp.txt #保存記錄的檔案
[ -f $FILE ] || touch $FILE
STUDENT=3 #被選中的人數
input()
{
while true
do
read -p "請輸入你名字的全拼(輸入q/Q退出):" name
check_name=`awk '{print $1}' $FILE |grep ^"$name"$`
let "$name / 1" &> /dev/null
if [ $? -eq 0 ];then #這里判斷輸入的名字不能為一個整數(小數的判斷還未實作)
echo "您輸入的有誤,"$name"不是一個名字,"
continue
fi
if [ -z "$name" ];then
echo "您輸出的為空,請重新輸入"
continue
fi
if [ ! -z "$check_name" ];then
echo "sorry,您已經輸入過了!"
continue
fi
number=$((RANDOM%100))
check_number=`awk '{print $3}' $FILE |grep ^"$number"$`
if [ "$name" == q -o "$name" == Q ];then
break
elif [ -z "$check_number" ];then
echo "$name ===> $number" >> $FILE
else
echo "出現相同的大小,請重新輸入您的名字"
continue
fi
done
}
output()
{
full_list=`sort -nr -k 3 $FILE`
select_list=`sort -nr -k 3 $FILE | head -"$STUDENT"`
echo "+-------++-------++-------+"
echo "被選中的同學為:"
echo "$select_list"
echo "+-------++-------++-------+"
echo;echo "所有參與學生的串列:"
echo "$full_list"
}
main()
{
input
output
}
main
exit 0
案例十四:破解RANDOM亂數案例
已知下面的字串是通過RANDOM亂數變數md5sum后,再截取一部分連續字串的結果,請破解這些字串對應的使用md5sum處理前的RANDOM對應的數字,
21029299
00205d1c
a3da1677
1f6d12dd
890684b
#!/bin/bash
#
for i in {0..50000}
do
echo "$i:$(echo $i | md5sum)" >> /tmp/passbook.txt
done
egrep '21029299|00205d1c|a3da1677|1f6d12dd|890684b' /tmp/passbook.txt
exit 0
案例十五:批量檢查多個網站地址是否正常
要求:
1、使用shell陣列方法實作,檢測策略盡量模擬用戶訪問,
2、每10秒鐘做一次所有的檢測,無法訪問的輸出報警,
3、待檢測的地址如下
http://blog.oldboyedu.com
http://blog.etiantian.org
http://oldboy.blog.51cto.com
http://10.0.0.7
#!/bin/bash
#
url_list=(
http://blog.oldboyedu.com
http://blog.etiantian.org
http://oldboy.blog.51cto.com
http://10.0.0.7
)
for i in ${url_list[@]}
do
prot=`curl -I -s -w "%{http_code}\n" "$i" -o /dev/null`
#STATUS=`curl -s -I "$i" | sed -n '/HTTP/p' | awk '{print $2}'` #這個也可以
if [ $port -eq 200 ];then
#if [ $STATUS -eq 200 ];then
echo "$i is OK"
else
echo "warning: $i breakdown"
fi
done
exit 0
案例十六:單詞及字母去重排序
要求:
1、按單詞出現頻率降序排序!
2、按字母出現頻率降序排序!
the squid project provides a number ofresources to assist users design,implement and support squid installations.Please browse the documentation and support sections for more infomation,byoldboy training.
#!/bin/bash
#
STRING="the squid project provides a number ofresources to assist users design,implement and support squid installations.Please browse the documentation and support sections for more infomation,byoldboy training."
words()
{
echo "$STRING" | sed 's/[^a-zA-Z]/\n/g' | grep -v "^$" | sort | uniq -c | sort -rn -k 1
}
letters()
{
echo "$STRING" | grep -o . | egrep -v "^$|[^a-z|A-Z]" | sort | uniq -c | sort -nr -k 1
}
#grep -o :只顯示行匹配模式的一部分
#grep -o . :匹配任意一個字符
#grep -o .. :會發生什么?
#grep -o ... :多試試就會理解
case $1 in
word)
words
;;
letter)
letters
;;
*)
echo "USAGE:`basename $0` [word|letter]"
esac
exit 0
案例十七:撰寫正或長方形圖形案例
#!/bin/bash
#
read -p "Please Enter a number:" num
for ((i=1;$i<=$num;i++))
do
for ((j=1;j<=$((2*$num));j++))
do
echo -n "+"
done
echo
done
exit 0
案例十八:撰寫等腰三角形圖形字符案例
#!/bin/bash
#
read -p "Please Enter a number:" num
for ((i=1;i<=$num;i++))
do
for ((h=$((2*$num-2*$i));h>=0;h--))
do
echo -n " "
done
for ((j=1;j<=$((2*$i-1));j++))
do
echo -n " *"
done
echo
done
exit 0
案例十九:撰寫直角梯形圖形字符案例
#!/bin/bash
if [[ -n $1 ]] && [[ -n $2 ]];then
for ((i=$1;$i<=$2;i++))
do
for ((j=1;j<=$i;j++))
do
echo -e "*\c" #不換行
done
echo
done
else
echo "No given two int arguments, please use $0 5 6|6 8!"
fi
exit 0
參考的文章鏈接:https://blog.51cto.com/13520779/2093146
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/216210.html
標籤:其他
上一篇:Shell編程正則運算式sed
