2.判断10.0.0.0/24网络里,当前在线的IP有哪些?

#!/bin/bash
CMD="ping -W 2 -c 2"
Ip="10.0.0."
for n in $(seq 254)
do
   {
   $CMD $Ip$n &> /dev/null
   if [ $? -eq 0 ]
     then
        echo "$Ip$n is ok" /bin/true
     else
        echo "$Ip$n is not ok" /bin/false
   fi
   }&
done

方法2:---------------------------------
#!/bin/sh
CMD="nmap -sP "
Ip="10.0.0.0/24"
CMD2="nmap -sS"
$CMD $Ip|awk '/Nmap scan report for/ {print $NF}'

2.解决类DDOS***的生产案例

#!/bin/bash
file=$1
while true
do
   awk '{print $1}' $1|grep -v "^$"|sort|uniq -c >/tmp/tmp.log
   exec >/tmp/droplist_$(date +%F).log
        fi
    done
    sleep 3600
done    

方法2:------------------------------
#!/bin/sh
file=$1
judgeExt(){
        if expr "$1" : ".*\.log" &>/dev/null
           then
               :
        fi       
               }
IpCount(){
    grep "ESTABLISHED" $1|awk -F "[ :]+" '{ ++S[$(NF-3)]}END {for(key in S) print S[key], key}'|sort -nr -k1|head -5 >/tmp/tmp.log
}     
ipt(){
     local ip=$1
     if [ `iptables -L -n|grep "$ip"|wc -l` -lt 1 ]
        then
            iptables -I INPUT -s $ip -j DROP
            echo "$line is dropped" >>/tmp/droplist_$(date +%F).log
    fi        
}
main(){
judgeExt $file
while true
do 
   IpCount $file
   while read line
   do
       ip=`echo $line|awk '{print $2}'`
       count=`echo $line|awk '{print $1}'`
       if [ $count -gt 3 ];then
           ipt $ip
       fi
    done

3.mysql分库备份

#!/bin/bash
PATH="/application/mysql/bin:$PATH"
DBPATH=/server/backup
MYUSER=root
MYPASS=hao123
SOCKET=/data/3306/mysql.sock
MYCMD="mysql -u$MYUSER -p$MYPASS -S $SOCKET"
MYDUMP="mysqldump -u$MYUSER -p$MYPASS -S $SOCKET"
[ ! -d "$DBPATH" ] && mkdir $DBPATH
for dbname in `$MYCMD -e "show databases;"|sed '1,2d'|egrep -v "mysql|schema"`
    do
        mkdir $DBPATH/${dbname}_$(date +%F) -p
    for table in `$MYCMD -e "show tables from $dbname;"|sed '1d'`
      do
        $MYDUMP $dbname $table|gzip >$DBPATH/${dbname}_$(date +%F)/${dbname}_${table}.sql.gz
    done
done

4.利用bash for循环打印下面这句话中字母不大于6的单词

I am oldboy teacher welcome to oldboy training class
#!/bin/sh
arr=(I am oldboy teacher welcome to oldboy training class)
for ((i=0; i<${#arr[*]};i++))
do
    if [ ${#arr[$i]} -lt 6 ]
        then
           echo "${#arr[$i]}"
    fi
  done
  echo --------------
  for word in ${arr[*]}
  do
      if [ `expr length $word` -lt 6 ];then
            echo $word
      fi
  done    

  awk方法---------------------------------
  arr="I am oldboy teacher welcome to oldboy training class"
  echo $arr|awk '{for(i=1;i<=NF;i++) if(length($i)<=6) print $i}'
[root@localhost tmp]# vim arr.sh 
  1 #!/bin/bash
  2 for a in li hao is bad boy
  3 do
  4    if [ `echo $a|wc -L` -gt 2 ]
  5         then
  6           echo $a
  7    fi
  8 done

5.开发一个守护进程脚本,每30秒监控一次MySQL主从复制是否异常(包括不同步及延迟),如果有异常,则发送短信报警,并发送邮件给管理员存档。

#!/bin/bash
########################################
# this script function is :
# check_mysql_slave_replication_status
# USER      YYYY-MM-DD - ACTION
# hao       2019/1/5   - Created
########################################
path=/server/scripts
MAIL_GROUP="[email protected] [email protected]"
PAGER_GROUP="13592760747 11111111"
LOG_FILE="/tmp/web_check.log"
USER=root
PASSWORD=hao123
PORT=3306
MYSQLCMD="mysql -u$USER -p$PASSWORD -S /data/$PORT/mysql.sock"
error=(1008 1007 1062)
RETVAL=0
[ ! -d "$path" ] && mkdir -p $path
function judgeError(){
    for((i=0;i<${#error[*]};i++))
    do
        if [ "$1" == "${error[$i]}" ]
            then
                echo "MySQL slave errorno is $1,auto repairing it."
                $MYSQLCMD -e "stop slave;set global sql_slave_skip_counter=1;start salve;"
        fi
    done
    return $1
}
function CheckDb(){
    status=($(awk -F ":" '/_Running|Last_Errno|_Behind/{print $NF}' slave.log))
    expr ${status[3]} + 1 &>/dev/null
    if [ $? -ne 0 ];then
        status[3]=300
    fi
    if [ "${status[0]}" == "Yes" -a "${status[1]}" == "Yes" -a ${status[3]} -lt 120 ]
        then
            #echo "Mysql salve status is ok"
            return 0
        else
            #echo "Mysql replcation is failed"
            judgeError ${status[2]}
        fi
}
function MAIL(){
    local SUBJECT_CONTENT=$1
    for MAIL_USER in `echo $MAIL_GROUP`
    do
        mail -s "$SUBJECT_CONTENT" $MAIL_USER <$LOG_FILE
    done
}
function PAGER(){
    for PAGER_USER in `echo $PAGER_GROUP`
    do
        TITLE=$1
        CONTACT=$PAGER_USER
        HTTPGW=http://oldboy.sms.cn/smsproxy/sendsms.action
        #send_message method1
        curl -d cdkey=5ADF-EFA -D password=OLDBOY -d phone=$CONTACT -d message="$TITLE[$2]" $HTTPGW
    done
}
function SendMsg(){
    if [ $1 -ne 0 ]
        then
            RETVAL=1
            NOW_TIME=`date + "%Y-%m-%d %H:%M:%S"`
            SUBJECT_CONTENT="mysql salve is error,errorno is $2,${NOW_TIME}."
            echo -e "$SUBJECT_CONTENT"|tee $LOG_FILE
            MAIL $SUBJECT_CONTENT
            PAGER $SUBJECT_CONTENT $NOW_TIME
        else
            echo "Mysql slave status is ok."
            RETVAL=0
        fi
        return $RETVAL
}
function main(){
    while true
    do  
        CheckDb
        SendMsg $?
        sleep 30
    done
}
main

比较整数大小

#!/bin/sh
read -p "please input two num:" a b
#no1
[ -z "$a" ]||[ -z "$b" ] &&{
    echo "please input two num again."
    exit 1
}
#no2
expr $a + 10 &>/dev/null
RETVAL1=$?
expr $b + 10 &>/dev/null
RETVAL2=$?
test $RETVAL1 -eq 0 -a $RETVAL2 -eq 0 ||{
    echo "please input two num again."
    exit 2
}
#no3
[ $a -lt $b ] &&{
    echo "$a < $b"
    exit 0
}
#no4
[ $a -eq $b ] &&{
    echo "$a = $b"
    exit 0
}
#no5
[ $a -gt $b ] &&{
    echo "$a > $b"
    exit 0
}

菜单脚本

#!/bin/sh
path=/server/scripts
[ ! -d "$path" ] && mkdir $path -p
#menu
cat </dev/null
[ $? -ne 0 ] &&{
    echo "the num you input must be {1|2|3}"
    exit 1
}
[ $num -eq 1 ] &&{
    echo "start installing lamp"
    sleep 2;
    [ -x "$path/lamp.sh" ]||{
        echo "$path/lamp.sh does not exist or can not be exec."
        exit 1
    }
    source $path/lamp.sh
    exit $?
}

[ $num -eq 2 ] && {
    echo "start installing LNMP."
    sleep 2;
    [ -x "$path/lnmp.sh" ]||{
        echo "$path/lnmp.sh does not exist or can not be exec."
        exit 1
    }
    source $path/lnmp.sh
    exit $?
}
[ $num -eq 3 ] && {
    echo bye
    exit 3
}
[[ ! $num =~ [1-3] ]] &&{
    echo "the num you input must be {1|2|3}"
    echo "Input ERROR"
    exit 4
}

监控memcached缓存服务

#!/bin/bash
if [ `ss -lntup|grep 11211|wc-l` -lt 1 ]
    then
       echo "memcached service is error."
       exit 1
fi
printf "del key\r\n"|nc 127.0.0.1 11211 &>/dev/null
printf "set key 0 0 10 \r\noldboy1234\r\n"|nc 127.0.0.1 11211 &>/dev/null
McValues=`printf "get key\r\n"|nc 127.0.0.1 11211|grep oldboy1234|wc -l`
if [ $McValues -eq 1 ]
    then
       echo "memcached status is ok."
    else
       echo "memcached status is bad"
    fi

方法二:

[root@web02 scripts]# cat mem_mc.sh    
#!/bin/bash
export MemcachedIp=$1
export MemcachedPort=$2
export NcCmd="nc $MemcachedIp $MemcachedPort"
export MD5=68b329da9893e34099c7d8ad5cb9c940
USAGE() {
       echo "$0 MemcachedIp $MemcachedPort"
       exit 3
}
[ $# -ne 2 ] && USAGE
printf "set $MD5 0 0 3\r\nhao\r\n"|$NcCmd >/dev/null 2>&1
if [ $? -eq 0 ];then
    if [ `printf "get $MD5\r\n|$NcCmd|grep hao|wc -l"` -eq 1 ];then
        echo "Memcached status is ok"
        printf "delete $MD5\r\n"|$NcCmd >/dev/null 2>&1
        exit 0
    else
        echo "Memcached status is error."
        exit 2
    fi
else
        echo "Could not connect Mc server"
        exit 2
fi 

开发脚本实现***与报警

监控web站点目录(/var/html/www)下的所有文件是否被恶意篡改,如果要则打印改动文件名(发邮件),定时任务每3分钟执行一次。

问题分析
1)先思考
2)文件内容被改动后
2.1大小可能有变化
2.2修改时间会变化
2.3文件内容会变化,利用MD5sum指纹校验
2.4增加或删除文件,比对每次检测前后的文件数量。

  find /var/html/www -type f |xargs md5sum >/opt/zhiwen.db.ori

find /var/html/www -type f >/opt/zhiwen.db.ori
#!/bin/bash
RETVAL=0
export LANG=en
CHECK_DIR=/var/html/www
[ -e $CHECK_DIR ] || exit 1
ZhiWenDbOri="/opt/zhiwen.db.ori"
FileCountDbOri="/opt/wenjian.db.ori"
ErrLog="/opt/err.log"

[ -e $ZhiWenDbOri ] || exit 1
[ -e $FileCountDbOri ] || exit 1
#judge file content
echo "md5sum -c --quiet /opt/zhiwen.db.ori" >$ErrLog
md5sum -c --quiet /opt/zhiwen.db.ori &>>$ErrLog
RETVAL=$?
#com file count
find $CHECK_DIR -type f >/opt/weijian.db_curr.ori
echo "diff /opt/wenjian.db*" &>>$ErrLog
diff /opt/wenjian.db* &>>$ErrLog
if [ $RETVAL -ne 0 -o `diff /opt/wenjian.db*|wc -l` -ne 0 ]
    then
        mail -s "$(uname -n)$(date +%F)err" [email protected] <$ErrLog
    else
        echo "$Sites dir is ok"|mail -s "$(uname -n)$(date +%F) is ok" [email protected]"

加入定时任务/var/spool/cron/root
*/3 * * * * /bin/sh /server/scripts/check.sh >/dev/null 2>&1

开发rsync服务启动脚本/etc/init.d/rsyncd {start|stop|restart}

#!/bin/bash
if [ $# -ne 1 ]
    then 
        echo $"usage:$0 {start|stop|restart}"
        exit 1
fi
if [ "$1" = "start" ]
    then
        rsync --deadom
        sleep 2
      if  [ `ss -lntup|grep rsync|wc -l` -ge 1 ] 
      then
        echo "rsyncd is started."
        exit 0
    fi
elif [ "$1" = "stop" ]
    then
        pkill rsync &>/dev/null
        sleep 2
        if [ `ss -lntup|grep rsync|wc -l` -eq 0 ]
        then    
            echo "rsync is stopped."
            exit 0
        fi
elif [ "$1" = "restart" ]
    then
        pkill rsync &>/dev/null
        sleep 1
        killpro=`ss -lntup|grep rsync|wc -l`
        rsync --deamon
        startpro=`ss -lntup|grep rsync|wc -l`
        if [ $killpro -eq 0 -a $startpro -ge 1 ]
            then
                echo "rsync is restarted."
                exit 0
        fi
    else
        echo "usage:$0 {start|stop|restart}"
        exit 1
fi

开发MySQL多实例启动脚本

#!/bin/bash
#init
Port=3306
MysqlUser="root"
MysqlPass="lihao123"
CmdPath="/application/mysql/bin"
#startup function
start()
{
    if [ `ss -lntup|grep "$Port"|wc -l` -eq 0 ]
        then
            printf "starting MySQL...\n"
            /bin/sh $(CmdPath)/mysqld_safe --defaults-file=/data/${Port}/my.cnf 2>&1 > /dev/null &
        else
            printf "MySQL is running...\n"
        fi
}
#stop function
stop()
{
    if [ ! `ss -lntup|grep "$Port"|wc -l` -eq 0 ]
        then
            printf "stoping MySQL...\n"
            ${CmdPath}/mysqladmin -u ${MysqlUser} -p${MysqlPass} -S /data/${Port}/mysql.sock shutdown 
        else
            printf "MySQL is stopped...\n"
        fi
}
#restart function
restart()
{
    printf "Restarting MySQL...\n"
    stop
    sleep2
    start
}
case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    restart
    ;;
*)
    printf "Usage:$0 {start|stop|restart}\n"
esac

开发学生实践抓阄脚本

#!/bin/bash
FileLog=/tmp/zhuajiu.log
[ -f "$FileLog" ] ||touoch $FileLog
function Check_Name() {
    while true
    do
        read -p "please input ypur English name:" name
        if [ -n "$name" -a "$(grep -w "$name" $FileLog|wc -l)" -eq 0 ];then
            flag=1
            break
        else
            echo "The name your input is null or alread exist"
            continue
        fi
    done
}
function Product_RandomNum() {
    if [ $fleg -eq 1 ];then
        while true
        do
           RandomNum=$(expr $RANDOM % 99 + 1)
           if [ `grep -w "$RandomNum" $FileLog|wc -l` -ne 1 ];then
                ehco "$name,your num is ${RandomNum}." |tee -a $FileLog
                flag=0
            else
                flag=1
            fi
            if [ $flag1 -eq 1 ];then
                Product_RandomNum
            else
                Check_Name
            fi
        done
    fi
}
function main() {
Check_Name
Product_RandomNum
}
main

破解RANDOM随机数

#!/bin/bash
array=(
XXXX  #输入要破解的数字
XXXX
XXXX
)
Path=/tmp/md5.txt
Num=0
funGetMd5() {
    [ -f "$Path" ] || touch $Path
    rowNum=$(wc -l < $Path)
    if [ $rowNum -ne 32768 ];then
        > $Path
        for ((Num=0;Num<=32767;Num++))
            do
                {
                Stat=$(echo $Num|md5sum|cut -c 1-8)
                echo "$Stat $Num" >> $Path
                }&
            done
        else
            return 0

    fi
}
funFindMd5() {
    word=$(echo "${array[@]}"|sed -r 's# |\n#|#g')
    grep -E "$word" $Path
}
funcMain() {
    funGetMd5
    funFindMd5
}
funcMain

批量检查多个网站地址是否正常

要求:①使用shell数组方法,检测策略尽量模拟用户访问
②每10秒钟做一次所以检测,对无法访问的网址输出报警。
③待检测的地址如下:
http://blog.xiaoxue.com
http://blog.xiaoxue.org
http://www.xiaoxue.org
http://172.16.16.16

#!/bin/bash
./etc/init.d/functions

check_count=0
url_list=(
http://blog.xiaoxue.com
http://blog.xiaoxue.org
http://www.xiaoxue.org
http://172.16.16.16
)

function wait() {
    echo -n '3秒后,执行检查URL操作';
    for ((i=0;i<3;i++))
        do
            echo -n ".";sleep 1
        done
        echo
}
function check_url() {
    wait
    for ((i=0;i<`echo ${#url_list[*]}`;i++))
        do
            wget -o /dev/null -T 3 --tries=1 --spider ${url_list[$i]} >/dev/null 2>&1
            if [ $? -eq 0 ]
                then
                    action "${url_list[$i]}" /bin/true
                else
                    action "${url_list[$i]}" /bin/false
            fi
        done
        ((check_count++))
}
main() {

    while true
    do
        check_url
        echo "--------check count:${check_count}-------"
        sleep 10
    done    
}
main

检测脑裂脚本:备节点运行

[root@bogon scripts]# cat check_split_brain.sh 
#!/bin/bash
lb01_vip=172.16.10.100
lb01_ip=172.16.10.10
while true
do
ping -c 2 -w 3 $lb01_ip &>/dev/null
 if [ $? -eq 0 -a `ip add|grep "$lb01_vip"|wc -l` -eq 1  ]
     then
        echo "ha is split brain.warning."
     else
        echo "ha is ok."
 fi
sleep 5
done

单词及字母去重排序

用shell处理以下内容
the squid project provides a number of resources to assist users design,implement and support squid installations.Please browse the documentation and support sections for more infomation,by oldbo training.
①按单词出现的频率降序排序
②按字母出现的频率降序排序

[root@localhost tmp]# cat lihao.txt 
the squid project provides a number of resources to assist users design,implement and support squid installations.Please browse the documentation and support sections for more infomation,by oldbo training.
[root@localhost tmp]# 
[root@localhost tmp]# awk -F "[,. ]+" '{for(i=1;i<=NF;i++)array[$i]++}END{for(key in array)print array[key],key|"sort -nr"}' lihao.txt |column -t
2  the
2  support
2  squid
2  and
1  users
1  training
1  to
1  sections
1  resources
1  provides
1  project
1  Please
1  oldbo
1  of
1  number
1  more
1  installations
1  infomation
1  implement
1  for
1  documentation
1  design
1  by
1  browse
1  assist
1  a
[root@localhost tmp]# tr "[ ,.]" "\n"

开发脚本管理服务端LVS

请在LVS负载均衡主节点上,开发管理LVS服务的脚本ip_vs。
实现:利用ipvsadmin可以启动并配置好LVS服务,脚本如下:/etc/init.d/lvs{start|stop|restart}

#!/bin/bash
#description:Config Director vip and ipvs
./etc/init.d/functions
VIP=10.0.0.3
INTERFACE=eth0
SubINTERFACE=${INTERFACE}:`echo $VIP|cut -d. -f4`
PORT=80
GW=10.0.0.254
RETVAR=0
IP=/sbin/ip

ROUTE=/sbin/route
IPVSADM=/sbin/ipvsadm
ARPING=/sbin/arping
RIPS=(
10.0.0.7
10.0.0.8
)
function usage (){
    echo "Usage: $0 {start|stop|restart}"
    return 1
}
function ipvsStart (){
    $IP addr add $VIP dev ${INTERFACE} label $SubINTERFACE
    $IPVSADM -C
    $IPVSADM -A -t $VIP:$PORT -s wr -p 60
    for ((i=0;i<`echo ${#RIPS[*]}`;i++))
    do
       $IPVSADM -a -t $VIP:$PORT -r ${RIP[$i]}:$PORT -g -w 1
     done
     RETVAR=$?
     #update MAC
     $ARPING -c 1 -I ${INTERFACE} -s $VIP $GW &>/dev/null
     if [ $RETVAR -eq 0 ]
        then
            action "Ipvsadm started." /bin/true
        else
            action "Ipvsadm started." /bin/false
        fi
        return $RETVAR
}
function ipvsStop (){
$IPVSADM -C
$IPVSADM -Z
$IP addr del $VIP/24 dev ${INTERFACE} label $SubINTERFACE &>/dev/null
RETVAR=$?
$ROUTE del -host $VIP dev $SubINTERFACE &>/dev/null 2&>1
if [ $RETVAR -eq 0 ]
    then
        action "Ipvsadm stopped." /bin/true
    else
        action "Ipvsadm stopped." /bin/false
fi
return $RETVAR
}
main (){
#judge argv num
    if [ $# -ne 1 ];then
        usage $0
    fi
    case "$1" in
        start)
            ipvsStart
            ;;
        stop)
            ipvsStop
            ;;
        restart)
            ipvsStop
            ipvsStart
            ;;
        *)
            usage $0
            ;;
    esac
}
#start operating
main $*

LVS节点健康检查及管理脚本

#!/bin/bash
IPVSADM=/sbin/ipvsadm
VIP=10.0.0.3
PORT=80
RIPS=(
10.0.0.7
10.0.0.8
)
while true
do
    for ((i=0;i<${#RIPS[*]};i++))
    do
        PORT_COUNT=`nmap ${RIPS[$i]} -p $PROT|grep open|wc -l`
        if [ $PORT_COUNT -ne 1 ];then
            if [ `$IPVSADM -Ln|grep ${RIPS[$i]}|wc -l` -ne 0 ];then
                $IPVSADM -d -t $VIP:$PORT -r ${RIPS[$i]}:$PROT >/dev/null 2&>1
            fi
        else
            if [ `$IPVSADM -Ln|grep ${RIPS[$i]}|wc -l` -eq 0 ];then
                $IPVSADM -a -t $VIP:$PORT -r ${RIPS[$i]}:$PROT >/dev/null 2&>1
            fi
        fi
    done
    sleep 5
done

LVS客户端配置脚本

开发LVS客户端设置VIP及抑制ARP的管理脚本
实现:/etc/init.d/lvsclient {start|stop|restart}

#!/bin/bash
RETVAR=0
VIP=(
    10.0.0.3
    10.0.0.4
)
./etc/init.d/functions
case "$1" in
    start)
        for ((i=0;i<`echo ${#VIP[*]}`;i++))
        do
            interface="lo:`echo ${VIP[$i]}|awk -F "." '{print $4}'`"
            /sbin/ip addr add ${VIP[$i]}/24 dev lo label $interface
            RETVAR=$?
        done
        echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore
        echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce
        echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore
        echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce
         if [ $RETVAR -eq 0 ];then
                action "Start LVS Config of RearServer." /bin/ture
            else
                action "Start LVS Config of RearServer." /bin/false
        fi
        ;;
    stop)
        for ((i=0;i<`echo ${#VIP[*]}`;i++))
        do
            interface=`${VIP[$i]}|awk -F "." '{print $4}'`"
            /sbin/ip addr del ${VIP[$i]}/24 dev lo label $interface >/dev/null 2&>1
        done
            echo "0" >/proc/sys/net/ipv4/conf/lo/arp_ignore
            echo "0" >/proc/sys/net/ipv4/conf/lo/arp_announce
            echo "0" >/proc/sys/net/ipv4/conf/all/arp_ignore
            echo "0" >/proc/sys/net/ipv4/conf/all/arp_announce
         if [ $RETVAR -eq 0 ];then
                action "Close LVS Config of RearServer." /bin/ture
            else
                action "Close LVS Config of RearServer." /bin/false
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac
exit $RETVAR

来自老男孩shell编程实战一书