shell基础巩固第三天

3年前 (2017-06-30) gtj linux, shell 0评论 已收录 208℃

if条件语句

if 条件表达式1
then
指令
elif 条件表达式2
then
指令
elif 条件表达式3
then
指令
else
指令
fi

例子:
写一个监控men的脚本

 [root@oldboy script]# free -m|awk 'NR==3 {print $NF}'
2047
[root@oldboy script]# free -m|awk 'NR==2 {print $NF}'
165
[root@oldboy script]# free -m|awk 'NR==2 {print $4}'
10
[root@oldboy script]# free -m|awk 'NR==2 {print $4}'
10
[root@oldboy script]# free -m|awk 'NR==2 {print $3}'
241
[root@oldboy script]# free -m|awk 'NR==2 {print $4}'
10
[root@oldboy script]# cat  6_30.sh 
#!/bin/bash
FreeMem=`free -m |awk 'NR==2 {print $4}'`  ##NR第几行 NF最后一列。
CHARS="Current memory is $FreeMem."
if [ $FreeMem -lt 100 ]
  then 
   echo $CHARS |tee /tmp/messages.txt
   mail -s "`date +%F-%T`$CHARS"  daniel_gtj@163.com  < /tmp/messages.txt
fi

结果:

然后可以把脚本加入报警,达到阈值就报警
*/3 * * * * /bin/sh /u02/scripts/6_30.sh >/dev/null 2>&1 ##三分钟监控一次。

例子1:
比较大小:

[root@sf106232 script]# cat 6_30_1.sh
#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-06-30 15:59
#       Filename: 6_30_1.sh
#    Description: 
#****************************************************
read -p "please input two num:" a b
 if [ $a -gt $b ] ;then 
   echo "yes,$a greater than $b"
 elif  [ $a -eq $b ] ;then
   echo "yes,$a equal $b"  
 else  [ $a -lt $b ] 
     echo "yes,$a less  $b"

fi
结果:
[root@sf106232 script]# sh 6_30_1.sh 
please input two num:23 56
yes,23 less  56

判断字符串是否为整型:

[root@sf106232 script]# num=test123
[root@sf106232 script]# [ -z "`echo "${num//[0-9]/}"`" ] && echo int || echo  char
char
[root@sf106232 script]# num=1234
[root@sf106232 script]# [ -z "`echo "${num//[0-9]/}"`" ] && echo int || echo  char
int

例子:

rsync启动关闭脚本

#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-06-30 18:30
#       Filename: rsyncd
#    Description: 
#****************************************************
[ -f /etc/init.d/functions ] && . /etc/init.d/functions
if [ $# -ne 1 ] ;then  
  echo $"usage:$0 {start|stop|restart|status}"
  exit 1
fi

if [ "$1" = "start" ] 
  then 
   rsync --daemon
   sleep 2
   if [ `netstat -lntup |grep rsync|wc -l` -ge 1]
     then 
       echo "rsyncd  is started."
       exit 0
   fi

elif [ "$1" = stop ] 
   then 
     killall rsync &>/dev/null
     sleep 2
     if [`netstat -lntup |grep rsync|wc -l` -eq 0 ] 
       then 
        echo "rsyncd  is stopped."
        exit 0
    fi
elif [ "$1"  = "restart" ] 
    then 
      killall rsync
      sleep 1
      killpro=`netstat -lntup|grep rsync |wc -l`
      rsync --daemon
      sleep 1 
      startpro=`netstat -lntup |grep  rsync |wc -l`
     if [ $killpro -eq 0 -a $startpro -ge 1 ] 
      then
       echo "rsyncd is restarted."
       exit 0
     fi
elif [ "$1" = "status" ] 
    then 
     statuspro=`netstat -lntup | grep  rsync | wc -l`
      if [ "$statuspro"   -eq 0 ] 
       then 
       #   echo "rsyncd  is stopped"
         echo -ne "\033[32mrsyncd  is stopped \033[0m" 
        exit 0
      else
      #  echo "rsyncd  is running"   
        echo -ne "\033[32mrsyncd  is running \033[0m" 
        exit 0
     fi

else 
   echo $"usage:$0 {start|stop|restart|status}"
        exit  1
fi

redis启动关闭脚本

#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-06-30 19:34
#       Filename: redis
#    Description: 
#****************************************************
[ -f /etc/init.d/functions ] && . /etc/init.d/functions

redis_server="/u02/redis/bin/redis-server"
redis_conf="/u02/redis/conf/redis.conf"

[ -x /u02/redis/bin/redis-server -a  -f /u02/redis/conf/redis.conf  ] || {
    echo "redis is not install."
    exit 1
}

if [ $# -ne 1 ] 
 then  
  echo $"usage:$0 {start|stop|restart|status}"
  exit 1
fi

function start () {
  stapro=`netstat -lntup|grep redis |wc -l` 
     if [ $stapro -ne 0 ] ; then 
        echo -e "\033[32mredis  is running \033[0m"  
        exit 2
     else  
         ${redis_server}   ${redis_conf}
         sleep 2
         stapro1=`netstat -lntup|grep redis |wc -l` 
         [ $stapro1 -ne 0 ] &&{ 
         action  "redis is started"  /bin/true
         exit 0
        }
     fi
}

function stop () {
  stopro=`netstat -lntup|grep redis |wc -l` 
     if [ $stopro -eq 0 ] ; then
        echo -e "\033[32mredis  is stopped \033[0m"  
        exit 2
     else
      #   PID=`ps aux|grep redis|grep -v grep|awk '{print $2}'`
      #    kill -9 ${PID} >/dev/null
            killproc redis-server
          sleep 2
         stopro1=`netstat -lntup|grep redis |wc -l`
         [ $stopro1 -eq 0 ] &&{
         action  "redis is stopped"  /bin/true
         exit 0
        }
     fi
}

function  status () {

  statpro=`netstat -lntup|grep redis |wc -l` 
  if [ $statpro -eq 0 ] ; then
      echo -e "\033[32mredis  is stopped \033[0m "   
  else
     echo -e "\033[32mredis  is running \033[0m "  
  fi 
 exit 0
}

case  $1 in
   "start") 
        start
         ;;
   "stop")
      stop
       ;;
   "restart")
         stop
         start
         ;;
   "status")
       status
       ;;

    * )
     echo $"Usage:$0 {start|stop|restart|status}"
      exit 4   
esac
exit 0

shell函数知识

别名的使用:
alias ssh='/etc/init.d/sshd'
函数的标准写法:
function 函数名(){
指令
return n
}
例子:
检查web url是否正常.

#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-01 17:05
#       Filename: 07_7_1.sh
#    Description: 
#****************************************************
#!/bin/sh
function  usage () {

   echo $"usage:$0 url"
   exit 1
}

function check_url () {

   wget --spider -q -o /dev/null --tries=1 -T 5 $1
  if [ $? -eq 0 ] ; then 
     echo " $1 is yes."
   else 
    echo "$1 is no."
  fi 
}

function main () {

 if [ $# -ne 1 ] 
     then 
       usage

 fi

  check_url  $1  ###接收函数的传参。

}
main $*   ##把命令行接收的参数作为函数参数传递到函数内部。
结果:
[root@cool360 script]# sh  07_01.sh 
usage:07_01.sh url
[root@cool360script]# sh  07_01.sh baidu.com
 baidu.com is yes.
[root@cool360 script]# sh  07_01.sh blog.cool360.org
 blog.cool360.org is yes.
[root@cool360script]# sh  07_01.sh hhhhhhh
hhhhhhh is no.
注释:
wget --spider -q -o /dev/null --tries=1 -T 5 $1
-q 设置wget不输出任何信息  
--spider 
--tries 尝试连接次数
-T --timeout=SECONDS 设定响应超时的秒数 
--spider 不下载任何东西 
-q --quiet 安静模式(没有输出) 

检查web url是否正常.引用内部函数


[root@oldboy script]# cat  07_01.sh
#!/bin/sh
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-01 17:05
#       Filename: 07_7_1.sh
#    Description: 
#****************************************************
[ -f /etc/init.d/functions ] && . /etc/init.d/functions

function  usage () {

   echo $"usage:$0 url"
   exit 1
}

function check_url () {

   wget --spider -q -o /dev/null --tries=1 -T 5 $1
  if [ $? -eq 0 ] ; then 
     action " $1 is yes."  /bin/true
   else 
    action  "$1 is no."  /bin/false
  fi 
}

function main () {

 if [ $# -ne 1 ] 
     then 
       usage

 fi

  check_url  $1

}
main $*
结果:
[root@oldboy script]# sh  07_01.sh blog.cool360.org 
 blog.cool360.org is yes.                                  [  确定  ]

例子2:

linux系统优化脚本

cat 8_7_1.sh
#!/bin/bash
#set env
export PATH=$PATH:/bin:/sbin:/usr/sbin
# Require root to run this script.
if [ "$UID" != "0" ]; then
    echo "Please run this script by root."
    exit 1
fi
 
#define cmd var
SERVICE=`which service`
CHKCONFIG=`which chkconfig`
 
function mod_yum(){
    #modify yum path
    if [ -e /etc/yum.repos.d/CentOS-Base.repo ]
     then
       mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup&&\
       wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
    fi
}
 
function close_selinux(){
    #1.close selinux
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
    #grep SELINUX=disabled /etc/selinux/config
    setenforce 0 &>/dev/null
    #getenforce
}
 
function close_iptables(){
    #2.close iptables
    /etc/init.d/iptables stop
    /etc/init.d/iptables stop
    chkconfig iptables off
}
 
function least_service(){
    #3.least service startup
    chkconfig|awk '{print "chkconfig",$1,"off"}'|bash
    chkconfig|egrep "crond|sshd|network|rsyslog|sysstat"|awk '{print "chkconfig",$1,"on"}'|bash
    #export LANG=en
    #chkconfig --list|grep 3:on
}
 
function adduser(){
    #4.add oldboy and sudo
    if [ `grep -w oldboy /etc/passwd|wc -l` -lt 1 ]
      then
        useradd oldboy
        echo 123456|passwd --stdin oldboy
        \cp /etc/sudoers /etc/sudoers.ori
        echo "oldboy  ALL=(ALL) NOPASSWD: ALL " >>/etc/sudoers
        tail -1 /etc/sudoers
        visudo -c &>/dev/null
    fi
}
 
function charset(){
    #5.charset config
    cp /etc/sysconfig/i18n /etc/sysconfig/i18n.ori
    echo 'LANG="zh_CN.UTF-8"'  >/etc/sysconfig/i18n
    source /etc/sysconfig/i18n
    #echo $LANG
}
 
function time_sync(){
    #6.time sync.
    cron=/var/spool/cron/root
    if [ `grep -w "ntpdate" $cron|wc -l` -lt 1  ]
      then
        echo '#time sync by oldboy at 2010-2-1' >>$cron
        echo '*/5 * * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2>&1' >>$cron
        crontab -l
    fi
}
 
function com_line_set(){
    #7.command set.
    if [ `egrep "TMOUT|HISTSIZE|HISTFILESIZE" /etc/profile|wc -l` -ge 3  ]
      then
        echo 'export TMOUT=300' >>/etc/profile
        echo 'export HISTSIZE=5' >>/etc/profile
        echo 'export HISTFILESIZE=5' >>/etc/profile
        . /etc/profile
    fi
}
 
function open_file_set(){
    #8.increase open file.
    if [ `grep 65535 /etc/security/limits.conf|wc -l` -lt 1 ]
      then 
        echo '*               -       nofile          65535 ' >>/etc/security/limits.conf
        tail -1 /etc/security/limits.conf
    fi
}
 
function set_kernel(){
    #9.kernel set.
    if [ `grep kernel_flag /etc/sysctl.conf|wc -l` -lt 1 ]
      then
        cat >>/etc/sysctl.conf<<EOF
        #kernel_flag
        net.ipv4.tcp_fin_timeout = 2
        net.ipv4.tcp_tw_reuse = 1
        net.ipv4.tcp_tw_recycle = 1
        net.ipv4.tcp_syncookies = 1
        net.ipv4.tcp_keepalive_time = 600
        net.ipv4.ip_local_port_range = 4000    65000
        net.ipv4.tcp_max_syn_backlog = 16384
        net.ipv4.tcp_max_tw_buckets = 36000
        net.ipv4.route.gc_timeout = 100
        net.ipv4.tcp_syn_retries = 1
        net.ipv4.tcp_synack_retries = 1
        net.core.somaxconn = 16384
        net.core.netdev_max_backlog = 16384
        net.ipv4.tcp_max_orphans = 16384
        net.nf_conntrack_max = 25000000
        net.netfilter.nf_conntrack_max = 25000000
        net.netfilter.nf_conntrack_tcp_timeout_established = 180
        net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
        net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
        net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120
EOF
        sysctl -p
    fi
}
function init_ssh(){
    \cp /etc/ssh/sshd_config /etc/ssh/sshd_config.`date +"%Y-%m-%d_%H-%M-%S"`
    #sed -i 's%#Port 22%Port 52113%' /etc/ssh/sshd_config
    sed -i 's%#PermitRootLogin yes%PermitRootLogin no%' /etc/ssh/sshd_config
    sed -i 's%#PermitEmptyPasswords no%PermitEmptyPasswords no%' /etc/ssh/sshd_config
    sed -i 's%#UseDNS yes%UseDNS no%' /etc/ssh/sshd_config
    /etc/init.d/sshd reload &>/dev/null
}
 
function update_linux(){
    #10.upgrade linux.
    if [ `rpm -qa lrzsz nmap tree dos2unix nc|wc -l` -le 3 ]
      then
        yum install lrzsz nmap tree dos2unix nc -y
        #yum update -y
    fi
}
main(){
    mod_yum
    close_selinux
    close_iptables
    least_service
    adduser
    charset
    time_sync
    com_line_set
    open_file_set
    set_kernel
    init_ssh
    update_linux
}
main

检测优化是否成功脚本

#!/bin/bash
#set env
export PATH=$PATH:/bin:/sbin:/usr/sbin
# Require root to run this script.
if [ "$UID" != "0" ]; then
    echo "Please run this script by root."
    exit 1
fi
 
# Source function library.
. /etc/init.d/functions
 
function check_yum(){
    Base=/etc/yum.repos.d/CentOS-Base.repo
    if [ `grep aliyun $Base|wc -l` -ge 1  ];then
        action "$Base config" /bin/true
    else
        action "$Base config" /bin/false
    fi
}
 
function check_selinux(){
    config=/etc/selinux/config
    if [ `grep "SELINUX=disabled" $config|wc -l ` -ge 1  ];then
        action "$config config" /bin/true
    else
        action "$config config" /bin/false
    fi
}
 
function check_service(){
    export LANG=en
    if [ `chkconfig|grep 3:on|egrep "crond|sshd|network|rsyslog|sysstat"|wc -l` -eq 5 ]
      then
        action "sys service init" /bin/true
    else
        action "sys service init" /bin/false
    fi
}
function check_open_file(){
    limits=/etc/security/limits.conf
    if [ `grep 65535 $limits|wc -l` -eq 1 ]
      then
        action "$limits" /bin/true
    else
        action "$limits" /bin/false
    fi
}
main(){
    check_yum
    check_selinux
    check_service
    check_open_file
}
main  
 

case条件语句

case语法:
case "变量" in
值1)
指令1....
;;
值2)
指令2
;;
*)
指令3
;;
esac

例子:
输入一个数0-9 返回输入的数。

[root@sf106232 script]# cat 20170701.sh 
#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-01 19:23
#       Filename: 20170701.sh
#    Description: 
#****************************************************
read -p "pls input a number:" num
case "$num" in
     1) 

     echo "the num you input is 1"
      ;;
    2)

     echo "the num you input is 2"
      ;;
     [3-9])

     echo "the num you input is $num"
      ;;
      *) 
       echo "pls  input [0-9] int"
       exit 1 
esac

结果:

[root@sf106232 script]# sh 20170701.sh 
pls input a number:1
the num you input is 1
[root@sf106232 script]# sh 20170701.sh 
pls input a number:2
the num you input is 2
[root@sf106232 script]# sh 20170701.sh 
pls input a number:6
the num you input is 6
[root@sf106232 script]# sh 20170701.sh 
pls input a number:nn
pls  input [0-9] int

例子2:
选择喜欢的水果,用不同的颜色显示。

#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-01 19:38
#       Filename: 2017070101.sh
#    Description: 
#****************************************************
red_color='\033[1;31m'
green_color='\E[1;32m'
yellow_color='\033[1;33m'
blue_color='\E[1;34m'
res='\E[0m'
function  usage () {
     echo "USAGE: $0 {1|2|3}"
     exit 1
}
function menu () {
    cat  << END
    1.apple
    2.pear
    3.bananan
END
}
function chose () {
read -p "pls  input your choice:"  num
case "$num" in
     1)
         echo -e "${red_color}apple ${res}" 
         ;;
    2)
       echo -e "${green_color}pear${res}"
       ;;
    3)
       echo  -e "${yellow_color}bananan${res}"
        ;;
   *)
      usage
esac

}

function main () {
      menu
      chose
}
main

结果:


[root@sf106232 script]# sh 2017070101.sh 
    1.apple
    2.pear
    3.bananan
pls  input your choice:2
pear
[root@sf106232 script]# sh 2017070101.sh 
    1.apple
    2.pear
    3.bananan
pls  input your choice:3
bananan
[root@sf106232 script]# sh 2017070101.sh 
    1.apple
    2.pear
    3.bananan
pls  input your choice:1
apple 
[root@sf106232 script]# sh 2017070101.sh 4
    1.apple
    2.pear
    3.bananan
pls  input your choice:4
USAGE: 2017070101.sh {1|2|3}


颜色调用

[root@sf106232 script]# echo -e "\033[30m 黑色 \033[0m"
黑色
[root@sf106232 script]# echo -e "\033[31m 红色 \033[0m"
红色
[root@sf106232 script]# echo -e "\033[32m 绿色 \033[0m"
绿色
[root@sf106232 script]# echo -e "\033[33m 棕色 \033[0m"
棕色
[root@sf106232 script]# echo -e "\033[34m 蓝色 \033[0m"
蓝色
[root@sf106232 script]# echo -e "\033[35m 洋红色 \033[0m"
洋红色
[root@sf106232 script]# echo -e "\033[036m 蓝绿色 \033[0m"
蓝绿色
[root@sf106232 script]# echo -e "\033[37m 白色 \033[0m"
白色
字的背景对应数字范围为 40 ~ 47.
例子:echo -e "\033[42;31m 红色 \033[0m" #42表示绿色背景,然后31表示红色字.


例子:
输入一个字符串 然后加粗加颜色:

[root@sf106232 script]# cat 2017070102.sh 
#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-01 20:34
#       Filename: 2017070102.sh
#    Description: 
#****************************************************
red_color='\033[1;31m'
green_color='\033[1;32m'
yellow_color='\033[1;33m'
blue_color='\033[1;34m'
pink='\033[1;35m'
res='\E[0m'
if [ $# -ne 2 ] ; then
     echo "Usage $0 content {red|yellow|blue|green|pink}"
     exit
fi
case "$2" in 
    red|RED)
        echo -e "${red_color}$1${res}"
         ;;
    green|GREEN)
           echo -e "${green_color}$1${res}"
             ;;            
    yellow|YELLOW)
         echo -e "${yellow_color}$1${res}"
          ;;   
      blue|BLUE)
         echo -e "${blue_color}$1${res}"
         ;;
      pink|PINK)
         echo -e "${pink}$1${res}"
          ;;
       *)
       echo "Usage $0  content {red|yellow|blue|green|pink}"
       exit 
esac 

结果:

拓展:

[root@sf106232 script]# cat 2017070102.sh 
#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-01 20:34
#       Filename: 2017070102.sh
#    Description: 
#****************************************************
plus_color(){
red_color='\033[1;31m'
green_color='\033[1;32m'
yellow_color='\033[1;33m'
blue_color='\033[1;34m'
pink='\033[1;35m'
res='\E[0m'
if [ $# -ne 2 ] ; then
     echo "Usage $0 content {red|yellow|blue|green|pink}"
     exit
fi
case "$2" in 
    red|RED)
        echo -e "${red_color}$1${res}"
         ;;
    green|GREEN)
           echo -e "${green_color}$1${res}"
             ;;            
    yellow|YELLOW)
         echo -e "${yellow_color}$1${res}"
          ;;   
      blue|BLUE)
         echo -e "${blue_color}$1${res}"
         ;;
      pink|PINK)
         echo -e "${pink}$1${res}"
          ;;
       *)
       echo "Usage $0  content {red|yellow|blue|green|pink}"
       exit 
esac 
}
plus_color "nihao" red
plus_color "i am suixiaofeng" yellow

编写openvpn添加删除查询用户脚本

#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-03 15:03
#       Filename: add_openvpn-user
#    Description: 
#****************************************************
.  /etc/init.d/functions
FILE_PATH=/etc/openvpn_authfile.conf
[ ! -f  $FILE_PATH ] && touch $FILE_PATH
 usage() {
    cat <<EOF
     USAGE: `basename $0` {-add|-del|-search} username
EOF
}
#user
if [ "$UID" -ne  0 ] ;  then
    echo "youare not supper user,pls call root!"
    exit 1
fi


#judge  arg  numbers.
if [ $# -ne 2 ] ; then 
       usage 
       exit 2
fi

#case
case "$1" in
    -a|-add) 
        shift   ##将第一个参数移除,第二个传参到第一个。
        if [ `grep "^$1$" ${FILE_PATH} |wc -l` -ge 1 ]  
         then 
            action $"vpnuser,$1 is exist" /bin/false 
            exit
         else 
             chattr -i  ${FILE_PATH}
          /bin/cp ${FILE_PATH}  ${FILE_PATH}.$(date +%F%T) 
         echo "$1" >> ${FILE_PATH}
         [ $? -eq 0 ] && action $"Add $1"  /bin/true
         chattr +i ${FILE_PATH}
       fi
       ;;

     -d|-del)
        shift 
        if [ `grep "\b$1\b" ${FILE_PATH}|wc -l` -lt 1 ] 
         then 
           action $"vpnuser,$1 is not exist." /bin/false
           exit
         else 
           chattr -i ${FILE_PATH}
           /bin/cp ${FILE_PATH} ${FILE_PATH}.$(date +%F%T)
           sed -i "/^${1}$/d" ${FILE_PATH}
           [ $? -eq 0 ] && action $"Del $1" /bin/true
           chattr +i ${FILE_PATH}
           exit
        fi
         ;;
       -s|-search) 
            shift  
         if [ `grep -w "$1"  ${FILE_PATH}|wc -l` -lt 1 ]
            then 
               echo $"vpnuser,$1 is not exist." ; exit
            else 
              echo $"vpnuser,$1 is exist." ; exit
        fi 
        ;;
        *)

           usage
           exit
            ;;
esac

结果:

[root@sf106232 script]# sh  add_openvpn-user -add suixiaofeng
vpnuser,suixiaofeng is exist                               [FAILED]
[root@sf106232 script]# cat /etc/open
openldap/                                 openvpn_authfile.conf                     openvpn_authfile.conf.2017-07-0316:53:47  openvpn_authfile.conf.2017-07-0316:57:00  openvpn_authfile.conf.2017-07-0316:57:11  
[root@sf106232 script]# cat /etc/openvpn_authfile.conf
suixiaofeng
[root@sf106232 script]# sh  add_openvpn-user -add cool360.org
Add cool360.org                                            [  OK  ]
[root@sf106232 script]# sh  add_openvpn-user -add hhhh jjjjj
     USAGE: add_openvpn-user {-add|-del|-search} username
[root@sf106232 script]# sh  add_openvpn-user -search suixiaofeng
vpnuser,suixiaofeng is exist.
[root@sf106232 script]# sh  add_openvpn-user -search suixiaofe
vpnuser,suixiaofe is not exist.
[root@sf106232 script]# sh  add_openvpn-user -del suixiaofeng
Del suixiaofeng                                            [  OK  ]
[root@sf106232 script]# sh  add_openvpn-user -search suixiaofeng
vpnuser,suixiaofeng is not exist.
[root@sf106232 script]# 

grep相关:

精确匹配字符串

[root@sf106232 script]# grep sdd /etc/openvpn_authfile.conf
sdd
sddd
sdd23
[root@sf106232 script]# grep -w "sdd" /etc/openvpn_authfile.conf
sdd
[root@sf106232 script]# grep "\bsdd\b" /etc/openvpn_authfile.conf
sdd
[root@sf106232 script]# grep "^sdd$" /etc/openvpn_authfile.conf
sdd

nginx启动脚本

#!/bin/sh
# chkconfig: 2345 40 98
# description: Start/Stop Nginx server
path=/application/nginx/sbin
pid=/application/nginx/logs/nginx.pid
RETVAL=0
. /etc/init.d/functions
start(){
    if [ ! -f $pid ];then
        $path/nginx
        RETVAL=$?
        if [ $RETVAL -eq 0 ];then
            action "nginx is started" /bin/true
            return $RETVAL
        else
            action "nginx is started" /bin/false
            return $RETVAL
        fi
    else
        echo "nginx is running"
        return 0
    fi
}
stop(){
    if [ -f $pid ];then
        $path/nginx -s stop
         RETVAL=$?
        if [ $RETVAL -eq 0 ];then
            action "nginx is stopped" /bin/true
            return $RETVAL
        else
            action "nginx is stopped" /bin/false
            return $RETVAL
        fi
    else
        echo "nginx is no running"
        return $RETVAL
    fi
}
 
case "$1" in
    start)
        start
        RETVAL=$?
        ;;
    stop)
        stop
        RETVAL=$?
        ;;
    restart)
         stop
             sleep 1
         start
         RETVAL=$?
         ;;
    *)
         echo $"Usage: $0 {start|stop|restart|reload}"
         exit 1
esac
exit $RETVAL

while循环和until循环

while语句

while基本语法:
while 条件表达式
do
指令
done
until 条件表达式 #表达式不成立执行循环体
do
指令
done

例子:


[root@sf106232 script]# cat 2017070401.sh
#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-04 10:15
#       Filename: 2017070401.sh
#    Description: 
#****************************************************
i=5
until ((i<1))
do 

echo "$i"
((i--))
done
结果:
[root@sf106232 script]# sh 2017070401.sh 
5
4
3
2
1

发短信扣费脚本一

#!/bin/sh
export LANG="zh_CN.UTF-8"
sum=15
msg_fee=15
msg_count=0
menu(){
    cat <<END
当前余额为${sum}分,每条短信需要${msg_fee}分
==========================
      1.充值
      2.发消息
      3.退出
==========================
END
}
recharge(){
    read -p "请输入金额充值:" money
        expr $money + 1 &>/dev/null 
        if [ $? -ne 0 ]
           then
               echo "then money your input is error,must be int."
           else 
               sum=$(($sum+$money))
               echo "当前余额为:$sum"
        fi
}
sendInfo(){
    if [ ${sum} -lt $msg_fee ]
       then
            printf "余额不足:$sum ,请充值。\n"
       else 
            while true 
              do
                 read -p "请输入短信内容(不能有空格):" msg
                 sum=$(($sum-$msg_fee))
                 printf "Send "$msg" successfully!\n"
                 printf "当前余额为: $sum\n"
                 if [ $sum -lt 15 ]
                    then
                        printf "余额不足,剩余$sum分\n"
                        return 
                 fi
            done
    fi
}
main(){
while true
do
   menu
   read -p "请输入数字选择:" num
   case "$num" in
       1)
         recharge
         ;;
       2)
         sendInfo
         ;;
       3)
         exit 
         ;;
       *)
        printf "选择错误,必须是{1|2|3}\n"
   esac
done
}
main

例子:

#!/bin/sh
TOTAL=500
MSG_FEE=499
. /etc/init.d/functions
 
function IS_NUM(){
    expr $1 + 1 &>/dev/null
    if [ $? -ne 0 -a "$1" != "-1" ];then
        return 1
    fi
    return 0
}
 
function color(){
RED_COLOR='\E[1;31m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
if [ $# -ne 2 ];then
   echo "Usage $0 content {red|yellow|blue|green}"
   exit
fi
case "$2" in
  red|RED)
         echo -e  "${RED_COLOR}$1${RES}"
         ;;
  yellow|YELLOW)
         echo -e  "${YELLOW_COLOR}$1${RES}"
         ;;
   green|GREEN)
         echo -e  "${GREEN_COLOR}$1${RES}"
         ;;
   blue|BLUE)
         echo -e  "${BLUE_COLOR}$1${RES}"
         ;;
   pink|PINK)
         echo -e  "${PINK_COLOR}$1${RES}"
         ;;
   *)
         echo "Usage $0 content {red|yellow|blue|green}"
         exit
esac
}
 
function consum(){
    color "You have left $TOTAL money,Send a msg need to charge $MSG_FEE money" yellow
    if [ $TOTAL -lt $MSG_FEE ];then
    charge
    fi
    read -p "Pls input your msg:" TXT
    read -p "Are you to send?[y|n]" OPTION
    case $OPTION in
        [yY]|[yY][eE][sS])
                color "Send "$TXT" successfully!" yellow
                echo $TXT >>/tmp/consum.log
                ((TOTAL=TOTAL-MSG_FEE))
                color "Your have $TOTAL left!" yellow
                ;;
        [nN]|[nN][oO])
                echo "Canceled"
                ;;
        *)
                echo "Invalid Input,this msg doesnt send out"
                ;;
    esac
}
 
 
function charge(){
        if [ $TOTAL -lt $MSG_FEE ];then
                color "Money is not enough,Are U want to charge?[y|n]" red
                read  OPT2
        case $OPT2 in
                y|Y)
                        while true
                        do
                                read -p "How much are you want to charge?[INT]" CHARGE
                                IS_NUM $CHARGE&&break||{
                                echo "INVALID INPUT" 
                                exit 100
                                }
                        done
                        ((TOTAL+=CHARGE)) && echo "you have $TOTAL money."
                        if [ $TOTAL -lt $MSG_FEE ];then
                          charge
                        fi
                        ;;
                n|N)
                        color "You have left $TOTAL money,can not send a msg,bye" red
                        ;;
                *)
                        charge
                        ;;
        esac
        fi
}
 
main(){
 while [ $TOTAL -ge $MSG_FEE ]
 do
  #color "You have left $TOTAL money" red
  consum
  charge
done
}
main

上面脚本完善版:

#!/bin/sh
TOTAL=500
MSG_FEE=499
. /etc/init.d/functions
 
function IS_NUM(){
    expr $1 + 1 &>/dev/null
    if [ $? -ne 0 -a "$1" != "-1" ];then
        return 1
    fi
    return 0
}
 
function color(){
RED_COLOR='\E[1;31m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'
if [ $# -ne 2 ];then
   echo "Usage $0 content {red|yellow|blue|green}"
   exit
fi
case "$2" in
  red|RED)
         echo -e  "${RED_COLOR}$1${RES}"
         ;;
  yellow|YELLOW)
         echo -e  "${YELLOW_COLOR}$1${RES}"
         ;;
   green|GREEN)
         echo -e  "${GREEN_COLOR}$1${RES}"
         ;;
   blue|BLUE)
         echo -e  "${BLUE_COLOR}$1${RES}"
         ;;
   pink|PINK)
         echo -e  "${PINK_COLOR}$1${RES}"
         ;;
   *)
         echo "Usage $0 content {red|yellow|blue|green}"
         exit
esac
}
 
function consum(){
    color "You have left $TOTAL money,Send a msg need to charge $MSG_FEE money" yellow
    if [ $TOTAL -lt $MSG_FEE ];then
    charge
    fi
   read -p "are you  want send msg ?[y|n]:" choice
    case $choice in
       [yY]|[yY][eE][sS])
    read -p "Pls input your msg:" TXT
    read -p "Are you to send?[y|n]" OPTION
    case $OPTION in
        [yY]|[yY][eE][sS])
                color "Send "$TXT" successfully!" yellow
                echo $TXT >>/tmp/consum.log
                ((TOTAL=TOTAL-MSG_FEE))
                color "Your have $TOTAL left!" yellow
                ;;
        [nN]|[nN][oO])
                echo "Canceled"
                ;;
        *)
                echo "Invalid Input,this msg doesnt send out"
                ;;
    esac
    ;;  
     [nN]|[nN][oO])
       echo "this is quit."
       exit 
         ;;
     *)
       echo $"Usage choice {y|Y|n|N|yes|no|YES|NO}"
       exit 
   esac
 
 

}
 
 
function charge(){
        if [ $TOTAL -lt $MSG_FEE ];then
                color "Money is not enough,Are U want to charge?[y|n]" red
                read  OPT2
        case $OPT2 in
                y|Y)
                        while true
                        do
                                read -p "How much are you want to charge?[INT]" CHARGE
                                IS_NUM $CHARGE&&break||{
                                echo "INVALID INPUT" 
                                exit 100
                                }
                        done
                        ((TOTAL+=CHARGE)) && echo "you have $TOTAL money."
                        if [ $TOTAL -lt $MSG_FEE ];then
                          charge
                        fi
                        ;;
                n|N)
                        color "You have left $TOTAL money,can not send a msg,bye" red
                        ;;
                *)
                        charge
                        ;;
        esac
        fi
}
 
main(){
 while [ $TOTAL -ge $MSG_FEE ]
 do
  #color "You have left $TOTAL money" red
  consum
  charge
done
}
main

shell数组检查网站状态

#!/bin/bash
#*****************************************************
#         Author: suixiaofeng
#           blog:https://bk.devopstack.cn
#          Email: 258818040@qq.com 
#  Last modified: 2017-07-04 15:18
#       Filename: url_ping.sh
#    Description: 
#****************************************************
. /etc/init.d/functions
check_count=0
url_list=(
http://blog.cool360.org
http://cool360.org
http://www.cool360.org
)
function wait () {
  echo -n '3s ping 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}"" 
      done
}
main    

结果:

[root@sf106232 script]# sh url_ping.sh
3s ping url...
http://blog.cool360.org                                    [FAILED]
http://cool360.org                                         [FAILED]
http://www.cool360.org                                     [FAILED]
-----------check count:1
3s ping url...
http://blog.cool360.org                                    [FAILED]
http://cool360.org                                         [FAILED]
http://www.cool360.org                                     [FAILED]
-----------check count:2
3s ping url.

在while的循环结尾done处通过输入重定向指定读取的文件

  1. while read line
  2.     do
  3.     cmd
  4.     done <file
  5. 例子:
  6. [root@sf106232 script]# cat cat.sh
  7. while read line
  8.     do
  9.     echo $line
  10.     done <$1
  11. 结果:
  12. [root@sf106232 script]# sh cat.sh /etc/hosts
  13. 127.0.0.1 localhost
  14. 127.0.0.1 sf106232
  15. 10.19.106.232 sf106232

采用exec读取文件,进入循环。

exec<file
  sum=0
 while read line
  do 
   cmd
done

监控某一个ip的并发数,超过100封掉。脚本如下:

file=$1
while true
do
        awk '{print $1}' $1|grep -v "^$"|sort|uniq -c >/tmp/tmp.log
        exec </tmp/tmp.log
        while read line
        do
          ip=`echo $line|awk '{print $2}'`
          count=`echo $line|awk '{print $1}'`
            if [ $count -gt 3 ] && [ `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
        done
        sleep 5
done
 

博主

这货来去如风,什么鬼都没留下!!!

相关推荐

嗨、骚年、快来消灭0回复。

×
订阅图标按钮
Less is more!!!