In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/03 Report--
For beginners, it is normal that they cannot write Shell scripts because they have no actual combat experience. If the operation and maintenance seniors who have worked for several years are still unable to write them, they are not actively looking for demand, lack of practice and lack of experience. In view of the above problems, summed up 30 classic Shell scripts in the production environment, through these demand cases, hope to help you improve Shell writing ideas and master writing skills.
Let's take a look at the following considerations in the process of writing Shell:
Add an interpreter at the beginning: #! / bin/bash syntax indentation, using four spaces; add more comments. Naming suggestion rules: variable name uppercase, local variable lowercase, function name lowercase, name reflects the actual role. The default variable is global, and the variable local is specified as a local variable in the function to avoid polluting other scopes. There are two commands to help me debug the script: set- e exits the script when it encounters a non-zero execution, and set-x prints the execution process. To write a script, be sure to test it before going to production.
1. Get a random string or number
Get random 8-bit string: method 1 echo # echo $RANDOM | md5sum | cut-c 1-8471b94f2 method 2VG # openssl rand-base64 4vg3BEgEng = method 3V # cat / proc/sys/kernel/random/uuid | cut-c 1-8ed9e032c get random 8-digit numbers: method 1 echo $RANDOM | cksum | cut-c 1-823648321 method 2 echo # openssl rand-base64 4 | cksum | cut-c 1-838571131 method 3 charge # date +% N | cut-c 1-869024815cksum: print CRC validity and statistical bytes
2. Define a color output string function
Method 1:function echo_color () {if [$1 = = "green"]; then echo-e "\ 033 [32 case 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 "[3240m / 0m" Red) echo-e "; *) echo" Example: echo_color red string "esac} usage: the echo_color green" test "function keyword defines a function with or without addition.
3. Create users in batch
#! / bin/bashDATE=$ (date +% financing% T) USER_FILE=user.txtecho_color () {if [$1 = = "green"]; then echo-e "[32 + 40m" elif [$1 = = "red"]; then echo-e "[31th 40m elif 2 [0m" fi} # backup if [- s $USER_FILE] if the user file exists and the size is greater than 0 Then mv $USER_FILE ${USER_FILE}-${DATE} .bak echo_color green "$USER_FILE exist, rename ${USER_FILE}-${DATE} .bak" fiecho-e "User Password" > > $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 $PASS" > > $USER_FILE echo "$USER User create successful." Else echo_color red "$USER User already exists!" Fidone
4. Check whether the software package is installed
#! / bin/bashif rpm-Q sysstat & > / dev/null; then echo "sysstat is already installed." else echo "sysstat is not installed!" fi
5. Check the 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" dst@example.comfi
6. Check the survival status of the host
Method 1: put the error IP in the array to determine whether 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 whether the ping has failed three times #! / bin/bash IP_LIST= "192.168.18.1 192.168.18.2" for IP in $IP_LIST; do FAIL_COUNT=0 for (
< =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 jump ping out of the loop and continue. If you don't jump out, you will go to print ping failure #! / bin/bashping_success_status () {if ping-c 1$ IP > / dev/null; then echo "$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 echo "$IP Ping is failure!" done
7. Monitor CPU, memory and hard disk utilization
1) CPU uses the vmstat tool to analyze CPU statistics. #! / bin/bashDATE=$ (date +% F ""% HIP=$% M) IP=$ (ifconfig eth0 | awk-F [:] + / inet addr/ {print $4}) # only supports CentOS6MAIL= "example@mail.com" 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" $MAILfi2) memory #! / bin/bashDATE=$ (date +% F ""% IP=$% M) IP=$ (ifconfig eth0 | awk-F [:] + / inet addr/ {print $4}) MAIL= "example@mail.com" TOTAL=$ (free-m | awk / Mem/ {print $2}) USE=$ (free-m | awk / Mem/ {print $3) }) FREE=$ (($TOTAL-$USE)) # send alarm email if with less than 1G memory [$FREE-lt 1024] Then echo "Date: $DATE Host: $IP Problem: Total=$TOTAL,Use=$USE,Free=$FREE" | mail-s "Memory Monitor" $MAILfi3) hard disk #! / bin/bashDATE=$ (date +% F ""% print% M) IP=$ (ifconfig eth0 | awk-F [:] + / inet addr/ {print $4}) MAIL= "example@mail.com" TOTAL=$ (fdisk-l | awk-F [:] + BEGIN {OFS= "="} / ^ Disk / dev/ {printf "% s=%sG,", $2) $3}) PART_USE=$ (df-h | awk BEGIN {OFS= "="} / ^ / dev/ {print $1mint ($5), $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
8. Disk utilization monitoring of batch hosts
The premise is that the SSH of the monitoring side and the monitored side is free of interactive login or key login. Write a configuration file to save the SSH connection information of the monitored host. The format of the file is as follows: IP User PortPortConnectionBash _ 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 $USER@$IP df-h > $TMP_FILE USE_RATE_LIST=$ (awk BEGIN {OFS= "="} / ^ / dev/ {print $1int ($5)} $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 "Warning: $PART_NAME Partition usage $user rate%!" Fi donedone
9. Check the usability of the website
1) check the URL availability method 1:check_url () {HTTP_CODE=$ (curl-o / dev/null-- connect-timeout 3-s-w "% {http_code}" $1) if [$HTTP_CODE-ne 200]; then echo "Warning: $1 Access failure!" Fi} method 2:check_url () {if! Wget-T 10-- tries=1-- spider $1 > / dev/null 2 > & 1; then #-T timeout,-- tries try once,-- spider crawler mode echo "Warning: $1 Access failure!" Fi} usage: check_url www.baidu.com2) the idea of judging the availability of URL three times is the same as checking the survival status of the host above. Method 1: use the loop technique to jump out of the current loop if successful, 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 echo "Warning: $URL Access failure!" done method 2: save the number of errors to the variable #! / bin/bash URL_LIST= "www.baidu.com www.agasgf.com" for URL in $URL_LIST; do FAIL_COUNT=0 for 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: save the number of errors to the 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] Then FAIL_COUNT [$NUM] = $IP # create an array with $NUM subscript, $IP element let NUM++ else break fi done if [${# FAIL_COUNT [*]}-eq 3]; then echo "Warning: $URL Access failure!" Unset FAIL_COUNT [*] # clear the array fidone
10. Check the master-slave synchronization status of MySQL
#! / bin/bash USER=bakPASSWD=123456IO_SQL_STATUS=$ (mysql-u$USER-p$PASSWD-e show slave statusG | awk-F: / Slave_.*_Running/ {gsub (":", ":"); print $0}) # gsub removes the space after the colon for i in $IO_SQL_STATUS; do THREAD_STATUS_NAME=$ {I% IO_SQL_STATUS; do THREAD_STATUS_NAME=$ *} THREAD_STATUS=$ {ionization:} if ["$THREAD_STATUS"! = "Yes"] Then echo "Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!" Fidone
Practice and let your Shell skills rise to one Rank!
To be continued.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.