Precautions
1) Opening add interpreter: #!/bin/bash
2) syntax indentation, use four spaces, and more explanatory notes.
3) Naming recommendation rules: variable name capital, local variable lowercase, function name lowercase, the name reflects the actual role.
4) The default variable is global, and in the function the local variable is specified as a locally variable to avoid contaminating other scopes.
5) There are two commands that can help me debug the script: Set-e encounters a non-0 o'clock exit script, set-x the print execution process.
6) Write scripts must be tested before production.
12.1 getting a random string or number
Get a random 8-bit string:
Method 1:# echo $RANDOM |md5sum |cut-c 1-8471b94f2 method 2:# OpenSSL rand-base64 4vg3beg== method 3:# Cat/proc/sys/kernel/random/uuid | Cut-c 1-8ed9e032c
Get a random 8-digit number:
Method 1:# echo $RANDOM |cksum |cut-c 1-823648321 method 2:# OpenSSL rand-base64 4 |cksum |cut-c 1-838571131 method 3:# Date +%n |cut-c 1-869024815
Cksum: Print CRC validation and statistics bytes
12.2 Defining a color output string function
Method 1:function echo_color () { if [ $1 == "Green" ]; then echo -e "\033[32;40m$2\033[0m" elif [ $1 == "Red" ]; then echo -e "\033[31;40m$2\033[0m" fi} Method 2:function echo_color () { case $1 in green) echo -e "\033[32;40m$2\033[0m" ;; red) echo -e "\033[31;40m$2\033[0m" ;; *) echo " Example: echo_color red string " esac} How to use:echo_color green " Test
The Functions keyword defines a function that can be added or not added.
12.3 Creating users in batches
#!/bin/bashdate=$ (date +%f_%t) User_file=user.txtecho_color () { if [ $1 == "Green" ]; then echo -e "\033 [32;40m$2\033[0m " elif [ $1 == " Red " ]; then echo -e "\033[31;40m$2\033[0m" fi}# If the user file exists and the size is greater than 0, backup if [ -s $USER _file ]; then mv $USER _ file ${user_file}-${date}.bak echo_color green "$USER _file exist, rename ${user_file}-${date}.bak "fiecho -e " User\tpassword " >> $USER _ fileecho "----------------" >> $USER _filefor user in user{1..10}; do if ! id $USER &>/dev/null; then pass=$ (echo $RANDOM |md5sum |cut -c 1-8) useradd $USER echo $PASS |passwd -- stdin $USER &>/dev/null echo -e "$ User\t$pass " >> $USER _file echo " $USER user create successful. " else echo_color red "$USER user already exists! " fidone
12.4 Check if the package is installed
#!/bin/bashif rpm-q Sysstat &>/dev/null; Then echo "Sysstat is already installed." else echo "Sysstat is not installed!" Fi
12.5 checking Service status
#!/bin/bashport_c=$ (Ss-anu |grep-c 123) ps_c=$ (ps-ef |grep ntpd |grep-vc grep) If [$PORT _c-eq 0-o $PS _c-eq 0]; Then echo "Content" | Mail-s "Theme" [Email Protected]fi
12.6 Checking host survival status
Method 1: put the error IP into the array to determine if the ping failed three times
#!/bin/bash ip_list= "192.168.18.1 192.168.1.1 192.168.18.2" for IP in $IP _ list; do num=1 while [ $NUM -le 3 ]; do if ping -c 1 $IP > /dev/null; then echo "$IP ping is successful. " break else # echo "$IP Ping is failure $NUM" fail_count[$NUM]= $IP Let num++ fi done if [ ${#FAIL_COUNT [*]} -eq 3 ];then echo "${fail_count[1]} ping is failure!" unset fail_count[*] fidone
method 2: Put the number of errors in the Fail_count variable to determine if the ping failed three times
#!/bin/bash ip_list= "192.168.18.1 192.168.1.1 192.168.18.2" for IP in $IP _ list; do fail_count=0 for ((i=1;i<=3;i++)); do if ping -c 1 $IP >/dev/null; then echo "$IP ping is successful. " break else # echo "$IP Ping is failure $i" let FAIL_COUNT++ fi done if [ $FAIL _count -eq 3 ]; then echo "$IP ping is failure!" fidone
Method 3: use the For loop to ping the loop to continue, and if you do not jump, you will go to the print ping failure
#!/bin/bashping_success_status () {if ping-c 1 $IP >/dev/null; then echoes "$IP Ping is successful." Continue fi}ip_list= "192.168.18.1 192.168.1.1 192.168.18.2" for IP in $IP _list; Do ping_success_status ping_success_status ping_success_status echo "$IP Ping is failure!" Done
12.7 monitoring CPU, memory, and hard disk utilization
1) CPU
Use the Vmstat tool to analyze CPU statistics.
#!/bin/bashdate=$ (date +%f " "%h:%m) ip=$ (ifconfig eth0 |awk -f ' [ :]+ ' '/inet addr/{print $4} ' # only supports centos6mail= "[email protected]" if ! which vmstat &>/dev/null; then echo "Vmstat command no found, please install procps package. " exit 1fius=$ (vmstat |awk ' nr==3{print $13} ') SY=$ (vmstat |awk ' nr==3{print $14} ') idle=$ (vmstat |awk ' nr==3{print $15} ') wait=$ (vmstat |awk ' nr==3{print $16} ') use=$ (($US + $SY)) if [ $USE -ge 50 ]; then echo Date: $DATE Host: $IP Problem: CPU utilization $USE | mail -s "Cpu monitor" $MAILFI
2) Memory
#!/bin/bashdate=$ (Date +%f ""%h:%m) ip=$ (ifconfig eth0 |awk-f ' [:]+ '/inet addr/{print $4} ') mail= "[email protected]" to tal=$ (free-m |awk '/mem/{print $} ') use=$ (free-m |awk '/mem/{print $3-$6-$7} ') free=$ (($TOTAL-$USE)) # Memory less than 1G send alert mail if [$ FREE-LT 1024]; Then echo "Date: $DATE Host: $IP problem:total= $TOTAL, use= $USE, free= $FREE" | Mail-s "Memory Monitor" $MAILfi
3) Hard Drive
#!/bin/bashdate=$ (date +%f " "%h:%m) ip=$ (ifconfig eth0 |awk -f ' [ :]+ ' '/inet addr/{print $4} ') mail= "[email protected]" total=$ (Fdisk -l |awk -f ' [: ]+ ' ' begin{ofs= ' = '}/^disk \/dev/{printf '%s=%sg, ', $2,$3} ') part_use=$ (df - h |awk ' begin{ofs= "="}/^\/dev/{print $1,int ($), $6} ') for i in $PART _use; do part=$ (echo $i |cut -d "=" -f1) use=$ (Echo $i |cut -d "=" -f2) mount=$ (echo $i |cut -d "=" -F3) if [ $USE -gt 80 ]; then echo Date: $DATE Host: $IP total: $TOTAL problem: $PART = $USE ($MOUNT) " | mail -s disk monitor" $MAIL fidone
12.8 Bulk host disk utilization monitoring
The prerequisite monitoring side and the monitored side SSH free interactive login or key login.
Write a configuration file to save the monitored host SSH connection information, file content format: IP User Port
#!/bin/bashhost_info=host.infofor ip in $ (awk '/^[^#]/{print $1} ' $HOST _info); do user=$ (awk -v ip= $IP ' ip==$1{print $2} ' $HOST _info) port=$ (awk -v ip= $IP ' ip==$1{print $3} ' $HOST _info) TMP_FILE=/tmp/disk.tmp ssh -p $PORT [email Protected] $IP ' df -h ' > $TMP _file use_rate_list=$ (awk ' begin{ofs= "="}/^\/dev/{print $1,int ($)} ' $TMP _file) for USE_RATE in $USE _rate_list; do part_name=${use_rate%=*} USE_RATE=${USE_RATE#*=} if [ $USE _rate -ge 80 ]; then echo&nBSP; " warning: $PART _name partition usage $USE _rate%! " fi donedone
12.9 Checking the availability of sites
1) Check URL availability
Method 1:check_url () {http_code=$ (Curl-o/dev/null--connect-timeout 3-s-w "%{http_code}" $) if [$HTTP _code-ne 200 ]; Then echo "Warning: Access failure!" Fi} Method 2:check_url () {if! wget-t--tries=1--spider >/dev/null 2>&1; then #-t time Out,--tries try 1 times,--spider crawler echo "Warning: Access failure!" FI} How to use: Check_url www.baidu.com
2) determine three times URL availability
The idea is the same as above to check the host's survival status.
Method 1: Take advantage of the looping technique, if successful, jump out of the current loop, otherwise execute to the last line #!/bin/bash check_url () { http_code=$ ( curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $1) if [ $HTTP _code -eq 200 ]; then continue fi}url_list= "Www.baidu.com www.agasgf.com" For url in $URL _list; do check_url $URL check_url $URL check_url $URL echo "warning: $URL access failure! " Done Method 2: The number of errors saved to the variable #!/bin/bash url_list= "www.baidu.com www.agasgf.com" for url in $URL _list; do fail_count=0 for ((i=1;i<=3;i++)); do http_code=$ (Curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL) if [ $HTTP _code -ne 200 ]; then let FAIL_COUNT++ else break fi done if [ $FAIL _count -eq 3 ]; then echo "warning: $URL access failure! " fidone Method 3: Number of errors saved to array #!/bin/bash url_list= "www.baidu.com www.agasgf.com" for url in $URL _list; do num=1 while [ $NUM -le 3 ]; do http_code=$ (Curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL) if [ $HTTP _code -ne 200 ]; then fail_count[$NUM]= $IP #创建数组, with $num subscript, $IP elements let NUM++ else break fi done if [ ${#FAIL_COUNT [*]} -eq 3 ]; then echo "warning: $URL access failure!" unset FAIL_COUNT[*] #清空数组 fidone
This chapter is written in shell script examples are more practical, in the interview also often appear, I hope you refer to the more hands-on writing, do not copy and paste to take to run, this is not learning! If you have any questions, please dabigatran Exchange:323779636 (Shell/python devops Development Group)
This article is from the "Li Zhenliang Technology Blog" blog, make sure to keep this source http://lizhenliang.blog.51cto.com/7876557/1929044
The 12th Chapter shell script Writing and common face question (i.)