shell实例

一、if选择分支的应用

1、按不同的数字选择喜欢的女生

#!/bin/bash
cat<<EOF
1.lili
2.zhang
3.iuiu
EOF
read -p "which do you like?pls input the num: " n
if [ $n -eq 1 ];then
    echo "i guess you like lili"
    exit 0
elif [ $n -eq 2 ];then
    echo "i guess you like zhang"
    exit 0
elif [ $n -eq 3 ];then
    echo "i guess you like iuiu"
    exit 0
else
    echo "i guess you are not man"
fi

2、按不同的数字安装不同的软件

#!/bin/bash
path=/server/scripts
if [ ! -d "$path" ];then
    mkdir -p $path
fi
cat<<EOF
1.[install lamp]
2.[install lnmp]
3.[exit]
EOF
read -p "pls input the number you want: " n
expr $n + 1 &> /dev/null
if [ $? -ne 0 ];then
    echo "the num you inout must be [1|2|3]"
    exit1
fi
if [ $n -eq 1 ];then
    echo "start installing lamp"
    sleep 2;
    [ -x "$path/lamp.sh" ] || {
    echo "$path/lamp.sh is not exits or can not be exec"
    exit 1
}
$path/lamp.sh
exit $?
elif [ $n -eq 2 ];then
    echo "start installing lnmp"
    sleep 2;
    [ -x $path/lnmp.sh ] || {
    echo "$path/lnmp.sh is not exits or can not be exec"
    exie 1 
}
$path/lnmp.sh
exit $?
elif [ $n -eq 3 ];then
    echo "bye"
    exit 3
else [[ ! $n =~ [1-3] ]]
    echo "the num you input must be {1|2|3}"
    echo "error"
    exit 4
fi

3、判断nginx服务是否活着,若没活就邮件报警,每三分钟执行一次(思路:用netstat过滤端口然后统计行数)

#!/bin/bash
port=`netstat -tupln|grep nginx|wc -l`
if [ $port -ne 1 ];then
    echo "nginx is dead" | tee /tmp/nginx.log
    mail -s "$(date) nginx is dead" 51254945@qq.com < /tmp/nginx.log
else
    echo "nginx is up"
fi


定时任务
crontab -e
*/3 * * * *    /bin/bash /server/scripts/nginx_exit.sh

二、函数结合if语句的应用

4、检测网站url是否正常

#!/bin/bash
usage(){
    if [[ ! $1 =~ http://.* ]];then
        echo "Usage:$0 http://www.xx.com"
        exit 1
    fi
}

checkurl(){
    wget -q $1 &> /dev/null
    if [ $? -ne 0 ];then
        echo "url is not ok"
    else
        echo "url is ok"
    fi
}

main(){
    usage $1
    check_url $1
}
main $*   ($*为命令行传入的参数)

5、用数组判断网站是否正常

#!/bin/bash
arr=(
    http://blog.oldboyedu.com
    http://blog.etiantian.org
    http://oldboy.blog.51cto.com
    http://10.0.0.7
    )
usage(){
    if [[ ! $1 =~ http://.* ]];then
        echo "Usage:$0 http://www.xx.com"
        exit 1
    fi
}
check_url(){
    wget -q -o /dev/null --spider -T 5 --tries=1 $1 &> /dev/null
    retval=$?
    if [ $retval -ne 0 ];then
        echo "$1 is not ok"
    else
        echo "$1 is ok"
    fi
}

piliang(){
    for url in ${arr[*]}
    do
        usage $url
        check_url $url
    done
}
main(){
    while true
    do
        piliang
        echo ==============
        sleep 5
    done
}
main

结果为

[root@k8s-master scripts]# sh url.sh
http://blog.oldboyedu.com is not ok
http://blog.etiantian.org is not ok
http://oldboy.blog.51cto.com is ok
http://10.0.0.7 is not ok
==============
http://blog.oldboyedu.com is ok

6、判断10.0.0.0/24网络里,当前在线的ip有哪些?(ping,nmap)
用ping实现

#!/bin/bash
for n in {1..254}
do
  {
  ping -W -c 2 10.0.0.$n &> /dev/null
  if [ $? -eq 0 ];then
      echo "10.0.0.$n is alive"
   else
       echo "10.0.0.$n is dead"
   fi
   }&   放在后台并发执行,速度更快
done

用nmap实现

nmap -sP 10.0.0.0/24|awk '/Nmap scan report for/ {print $NF}'
这样可以扫描存活的主机
-sP参数: Ping Scan - go no further than determining if host is online(Ping扫描-仅确定主机是否联机)

#!/bin/bash
cmd=`namp -sP`
ip="10.0.0.0/24"
$cmd $ip|awk '/Nmap scan report for/ {print $NF}'

三、函数与case语句的应用

7、选择你喜欢的水果并为其设置颜色

#!/bin/bash
color(){
red_color='\E[1;31m'
green_color='\E[1;32m'
yellow_color='\E[1;33m'
blue_color='\E[1;34m'
res='\E[0m'
}

menu(){
cat<<EOF
1.apple
2.pear
3.banana
4.cherry
EOF
}

chose(){
read -p "pls chose the fruit you like: " n
case "$n" in 
  1)
    echo -e "your chose is:${red_color}apple${res}"
  ;;
  2)
    echo -e "your choseis:${yellow_color}pear${res}"
    ;;
  3)
    echo -e "your chose is:${blue_color}banana${res}"
    ;;
  4)
    echo -e "your chose is:${green_color}cherry${res}"
    ;;
  *)
    echo -e "${red_color}your input is error${res}"
esac
}

main(){
  color
  menu
  chose
}
main 

8、充值话费,话费不够就提示,若要发送短信,余额不足就提示,发送短信0.15/次

#!/bin/bash
i=0.15
sum=10
menu(){
echo "当前余额为$sum元,发送短信费用为$i元"
cat <<EOF
==========
1.充值
2.发送短信
3.退出
==========
EOF
}

chongzhi(){
read -p "请输入你想要充值的金额(单位为元): " a
expr $a + 1 &> /dev/null
if [ $? -eq 0 ] && [ $a -gl 0 ];then
    ((sum=sum+a))
    echo "充值成功,当前余额为$sum元"
else
    echo "请输入非0整数金额"
fi
}

send_message(){
if [ $sum -lt $i ];then
    echo "当前余额不足,为$sum元,请充值"
    return 1
else
    while true
    do
        read -p "请输入你想要发的短信内容"
        ((sum=sum-i))
        echo "短信发送成功"
        if [ $sum -lt $i ];then
            echo "余额不足,剩余$sum,请充值"
            return 1
        fi
    done
fi
}

main(){
    while true
    do
        menu
        send_message
    done
}
main

四、利用while的应用

9、while循环 :实现1加到100

#!/bin/bash
sum=0
i=0
while ((i<100))
do
    let sum=sum+i
    let i++
done
echo $sum

算法实现:(推荐)

echo $((100*(100+1)/2))

awk实现:

awk “BEGIN{for (i=1;i<100;i++) sum=sum+i;print sum}”

10、解决dos攻击生产案例,写一个shell脚本解决ddos攻击,根据web日志,监控当某个IP并发连接数,当短时内PV达到100,即调用防火墙命令封掉对应的IP,防火墙命令为:iptables -I INPUT -s ip -j DROP

jisuan(){
awk -F "[ :]+" '/ESTABLISHED/print{ $(NF-3)}' netstat.log|sort|uniq -c|sort -rn|head -10 > /tmp/ip.log
while read line
do
    ip=`echo $line|awk '{print $2}'`
    count=`echo $line|awk '{print $1}'`
    if [ $count -gl 100 ] && [ `iptables -nL|grep "$ip"|wc -l` -lt 1 ];then     (当出现多个相同IP时只统计一个)
        echo "$ip is serious"
        iptables -I input -s $ip -j DROP
    else
        echo "$ip is ok"
    fi
done < /tmp/ip.log
}

main(){
    while true
    do
        jisuan
        sleep 5
    done
}
main 

五、排序问题

11、统计每个域名出现的次数,并且按照从多到少排序(面试概率极高)

文本如下:wangye.txt
www.etiantian.org
bbs.etiantian.org
www.etiantian.org
blog.etiantian.org
www.etiantian.org
www.etiantian.org
blog.etiantian.org
命令如下:
1、sort wangye.txt|uniq -c|sort -rn 
  4 www.etiantian.org
  2 blog.etiantian.org
  1 bbs.etiantian.org

2、awk '{S[$0]++}END{for(key in S) print S[key],key}' wangye.txt |sort -rn
  4 www.etiantian.org
  2 blog.etiantian.org
  1 bbs.etiantian.org

12、企业面试题:单词及字母去重排序案例
1、按单词出现频率降序排序
2、按字母出现频率降序排序

the squid project provides a number of resources to assist users design,implement and support squid installations.Please browse the document and support sections for more information,by oldboy training.

答案1(1) tr " ,." "\n" < mianshi.txt |awk '{S[$0]++}END{for (key in S) print S[key],key}'|sort -rn  

(2) tr " ,." "\n" < mianshi.txt|sort|uniq -c|sort -rn   tr命令,将,.以及空格转换为换行,让它呈现出一行一行的效果,然后再对其进行排序去重  

(3)awk -F "[ ,.]+" '{for(i=1;i<=NF;i++) S[$i]++}END{for(i in S) print S[i],i}' mianshi.txt |sort -rn 

答案2(1) awk -F "" '{for(i=1;i<=NF;i++)S[$i]++}END{for(key in S) print S[key],key}' mianshi.txt |sort -rn
这个答案的不同之处在于它以空为分隔符,相当于将字母打散

(2) grep -o "[^ ]" mianshi.txt |sort|uniq -c|sort -rn
以非空进行过滤,只要不是空的都会被匹配

(3) grep -o "[^ ]" mianshi.txt |awk '{S[$0]++}END{for(key in S) print S[key],key}'|sort -rn

六、生成随机数以及改名的应用

13、生成随机数

(1)
[root@k8s-master scripts]# openssl rand -base64 10|cut -c 1-5
6LWqe
(2)
[root@k8s-master scripts]# echo $RANDOM
8025
(3)
[root@k8s-master scripts]# date +%N
519159686

14、利用for循环批量创建10个html文件,其中每个文件需要包含10个随机小写字母加上固定字符串oldboy

#!/bin/bash
path=/data
[ -e $path ] || mkdir $path
for i in {1..10}
do
    suiji=`openssl rand -base64 30|sed 's/[^a-z]//g'|cut -c 1-10`
    touch $path/${suiji}_oldboy.html
done

在这里补充改名的两个命令

1.自定义变量,利用${变量/old/new}

[root@k8s-master data]# file=meqrbdpwkp_oldboy.html
[root@k8s-master data]# echo "${file/oldboy.html/oldgirl.HTML}"
meqrbdpwkp_oldgirl.HTML

2.利用命令rename,rename “old” “new” *.html

[root@k8s-master data]# rename "oldboy.html" "oldgirl.HTML" *.html
[root@k8s-master data]# ls
ahcvibjxiq_oldgirl.HTML  hwioxevowu_oldgirl.HTML  piwybaexey_oldgirl.HTML
flqfnuefqq_oldgirl.HTML  index.html               thwwvrbqxm_oldgirl.HTML
func                     meqrbdpwkp_oldgirl.HTML  ubjglhpddj_oldgirl.HTML
gwemhsfeuw_oldgirl.HTML  onsreedryd_oldgirl.HTML  wdmoftnmid_oldgirl.HTML

将上述题目中的oldboy替换为oldgirl,将扩展名html换为HTML

#!/bin/bash
path=/data
cd $path
for file in `ls`
do
    mv $file ${file/oldboy.html/oldgirl.HTML}
done

也可以利用awk进行计算

 ls *.html|awk -F "_" '{print "mv",$0,$1"_oldgirl.HTML"}'|bash

15、利用for循环批量创建10个html文件,其中每个文件需要包含固定字符串oldboy加上10个随机小写字母

#!/bin/bash
path=/liyu
[ -e $path ] || mkdir $path
for i in {1..10}
do
    suiji=`openssl rand -base64 30|sed 's/[^a-z]//g'|cut -c 1-10`
    touch $path/oldboy_${suiji}.html
done

再将oldboy改为oldgirl,将html改为HTML
第一种办法

[root@k8s-master liyu]# ls *.html|awk -F "[_.]+" '{print "mv",$0,"oldgirl_"$2".HTML"}'|bash
[root@k8s-master liyu]# ls
oldgirl_bvlrdwfpir.HTML  oldgirl_guvtbuxmun.HTML  

第二种办法

#!/bin/bash
path=/liyu
cd $path
for oldname in `ls`
do
    newname=$(echo $oldname|awk -F "[_.]" '{print "oldboy_"$2".html"}')
    mv $oldname $newname
done

在命令行测试

[root@k8s-master liyu]# echo oldgirl_xgmlxmjywk.HTML|awk -F "[_.]" '{print "oldboy_"$2".html"}'
oldboy_xgmlxmjywk.html

第三种办法,也可以用两次rename

rename "oldboy" "oldgirl" *.HTML
rename "HTML" "html" *.HTML
[root@k8s-master liyu]# ls
oldboy_bvlrdwfpir.html  oldboy_guvtbuxmun.html  

16、批量创建oldboy1-10个用户,并随机生成密码

#!/bin/bash
for user in oldboy{1..10}
do
    passwd=`echo $user|md5sum|cut -c 1-8`
    useradd $user &> /dev/null && {
    echo ${passwd}|passwd --stdin $user &> /dev/null
    echo -e "$user\t$passwd" >> /data/useradd.txt   将用户及密码记录到文件里
    }
    if [ $? -eq 0 ];then
        echo "$user is ok"
    else
        echo "$user is not ok"
    fi
done

17、已知下面的字符串是通过将RANDOM随机数采用md5sum加密后任意取出连续10位的结果,请破解这些字符串对应的md5sum前的数字

4fe8bf20ed

#!/bin/bash
for n in {0..32767}   random随机数的范围是0-32767
do
    echo -n "$n " >> /tmp/md5sum.txt
    echo $n|md5sum >> /tmp/md5sum.txt    将所有的数字进行加密
done
grep "4fe8bf20ed" /tmp/md5sum.txt     最后再进行过滤
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值