在學習Linux運維時,廣泛反饋是:Linux Shell是一個很難的知識板塊。雖然你們都認真學,基本的語法也都掌握了,但有需求時,很難直接上手編程,要麼寫了好久,要麼寫很差!
也有不少作運維不少年的朋友也是如此,Shell腳本一直寫的不6!在網上看例子能照貓畫虎寫出來,徹底獨立寫就困難了。對於初學者而言,由於沒有實戰經驗,寫不出來Shell腳本很正常,若是工做了幾年的運維老年仍是寫不出來,那就是沒主動找需求,缺少練習,缺少經驗。
針對以上問題,總結了30個生產環境中經典的Shell腳本,經過這些需求案例,但願能幫助你們提高Shell編寫思路,掌握編寫技巧。mysql
先了解下編寫Shell過程當中注意事項:
開頭加解釋器:#!/bin/bash
語法縮進,使用四個空格;多加註釋說明。
命名建議規則:變量名大寫、局部變量小寫,函數名小寫,名字體現出實際做用。
默認變量是全局的,在函數中變量local指定爲局部變量,避免污染其餘做用域。
有兩個命令能幫助我調試腳本:set -e 遇到執行非0時退出腳本,set-x 打印執行過程。
寫腳本必定先測試再到生產上。nginx
一、獲取隨機字符串或數字sql
獲取隨機8位字符串:
方法1:
# echo $RANDOM |md5sum |cut -c 1-8
471b94f2
方法2:
# openssl rand -base64 4
vg3BEg==
方法3:
# cat /proc/sys/kernel/random/uuid |cut -c 1-8
ed9e032c
獲取隨機8位數字:
方法1:
# echo $RANDOM |cksum |cut -c 1-8
23648321
方法2:
# openssl rand -base64 4 |cksum |cut -c 1-8
38571131
方法3:
# date +%N |cut -c 1-8
69024815
cksum:打印CRC效驗和統計字節docker
二、定義一個顏色輸出字符串函數數據庫
方法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
}
方法2:
function echo_color() {
case $1 in
green)
echo -e "[32;40m$2[0m"
;;
red)
echo -e "[31;40m$2[0m"
;;
*)
echo "Example: echo_color red string"
esac
}
使用方法:echo_color green "test"
function關鍵字定義一個函數,可加或不加。編程
三、批量建立用戶數組
#!/bin/bash
DATE=$(date +%F_%T)
USER_FILE=user.txt
echo_color(){
if [ $1 == "green" ]; then
echo -e "[32;40m$2[0m"
elif [ $1 == "red" ]; then
echo -e "[31;40m$2[0m"
fi
}
# 若是用戶文件存在而且大小大於0就備份
if [ -s $USER_FILE ]; then
mv $USER_FILE ${USER_FILE}-${DATE}.bak
echo_color green "$USER_FILE exist, rename ${USER_FILE}-${DATE}.bak"
fi
echo -e "User Password" >> $USER_FILE
echo "----------------" >> $USER_FILE
for 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!"
fi
done安全
四、檢查軟件包是否安裝bash
#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed."
else
echo "sysstat is not installed!"
fi服務器
五、檢查服務狀態
#!/bin/bash
PORT_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 "內容" | mail -s "主題" dst@example.com
fi
六、檢查主機存活狀態
方法1:將錯誤IP放到數組裏面判斷是否ping失敗三次
#!/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
FAIL_COUNT[$NUM]=$IP let NUM++ fi done if [ ${#FAIL_COUNT[*]} -eq 3 ];then echo "${FAIL_COUNT[1]} Ping is failure!" unset FAIL_COUNT[*] fi
done
方法2:將錯誤次數放到FAIL_COUNT變量裏面判斷是否ping失敗三次
#!/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
let FAIL_COUNT++ fi done if [ $FAIL_COUNT -eq 3 ]; then echo "$IP Ping is failure!" fi
done
方法3:利用for循環將ping通就跳出循環繼續,若是不跳出就會走到打印ping失敗
#!/bin/bash
ping_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
ping_success_status
ping_success_status
echo "$IP Ping is failure!"
done
七、監控CPU、內存和硬盤利用率
1)CPU
藉助vmstat工具來分析CPU統計信息。
#!/bin/bash
DATE=$(date +%F" "%H:%M)
IP=$(ifconfig eth0 |awk -F [ :]+ /inet addr/{print $4} ) # 只支持CentOS6br/>MAIL="example@mail.com"
if ! which vmstat &>/dev/null; then
echo "vmstat command no found, Please install procps package."
exit 1
fi
US=$(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" $MAIL
fi
2)內存
#!/bin/bash
DATE=$(date +%F" "%H:%M)
IP=$(ifconfig eth0 |awk -F [ :]+ /inet addr/{print $4} ) br/>MAIL="example@mail.com"
TOTAL=$(free -m |awk /Mem/{print $2} )
USE=$(free -m |awk /Mem/{print $3-$6-$7} )
FREE=$(($TOTAL-$USE))
# 內存小於1G發送報警郵件
if [ $FREE -lt 1024 ]; then
echo "
Date: $DATE
Host: $IP
Problem: Total=$TOTAL,Use=$USE,Free=$FREE
" | mail -s "Memory Monitor" $MAIL
fi
3)硬盤
#!/bin/bash
DATE=$(date +%F" "%H:%M)
IP=$(ifconfig eth0 |awk -F [ :]+ /inet addr/{print $4} ) br/>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 $1,int($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
fi
done
八、批量主機磁盤利用率監控
前提監控端和被監控端SSH免交互登陸或者密鑰登陸。
寫一個配置文件保存被監控主機SSH鏈接信息,文件內容格式:IP User Port
#!/bin/bash
HOST_INFO=host.info
for 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 $1,int($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 $USE_RATE%!"
fi
done
done
九、檢查網站可用性
1)檢查URL可用性
方法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
}
方法2:
check_url() {
if ! wget -T 10 --tries=1 --spider $1 >/dev/null 2>&1; then
#-T超時時間,--tries嘗試1次,--spider爬蟲模式
echo "Warning: $1 Access failure!"
fi
}
使用方法:check_url www.baidu.com
2)判斷三次URL可用性
思路與上面檢查主機存活狀態同樣。
方法1:利用循環技巧,若是成功就跳出當前循環,不然執行到最後一行
#!/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
方法2:錯誤次數保存到變量
#!/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!"
fi
done
方法3:錯誤次數保存到數組
#!/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 #建立數組,以$NUM下標,$IP元素
let NUM++
else
break
fi
done
if [ ${#FAIL_COUNT[]} -eq 3 ]; then
echo "Warning: $URL Access failure!"
unset FAIL_COUNT[] #清空數組
fi
done
十、檢查MySQL主從同步狀態
#!/bin/bash
USER=bak
PASSWD=123456
IO_SQLSTATUS=$(mysql -u$USER -p$PASSWD -e show slave statusG |awk -F: /Slave._Running/{gsub(": ",":");print $0} ) #gsub去除冒號後面的空格
for i in $IO_SQL_STATUS; do
THREAD_STATUS_NAME=${i%:}
THREAD_STATUS=${i#*:}
if [ "$THREAD_STATUS" != "Yes" ]; then
echo "Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!"
fi
done
十一、iptables自動屏蔽訪問網站頻繁的IP
場景:惡意訪問,安全防範
1)屏蔽每分鐘訪問超過200的IP
方法1:根據訪問日誌(Nginx爲例)
#!/bin/bash
DATE=$(date +%d/%b/%Y:%H:%M)
ABNORMAL_IP=$(tail -n5000 access.log |grep $DATE |awk '{a[$1]++}END{for(i in a)if(a[i]>100)print i}')
#先tail防止文件過大,讀取慢,數字可調整每分鐘最大的訪問量。awk不能直接過濾日誌,由於包含特殊字符。
for IP in $ABNORMAL_IP; do
if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
iptables -I INPUT -s $IP -j DROP
fi
done
方法2:經過TCP創建的鏈接
#!/bin/bash
ABNORMAL_IP=$(netstat -an |awk '$4~/:80$/ && $6~/ESTABLISHED/{gsub(/:[0-9]+/,"",$5);{a[$5]++}}END{for(i in a)if(a[i]>100)print i}')
#gsub是將第五列(客戶端IP)的冒號和端口去掉
for IP in $ABNORMAL_IP; do
if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
iptables -I INPUT -s $IP -j DROP
fi
done
2)屏蔽每分鐘SSH嘗試登陸超過10次的IP
方法1:經過lastb獲取登陸狀態:
#!/bin/bash
DATE=$(date +"%a %b %e %H:%M") #星期月天時分 %e單數字時顯示7,而%d顯示07
ABNORMAL_IP=$(lastb |grep "$DATE" |awk '{a[$3]++}END{for(i in a)if(a[i]>10)print i}')
for IP in $ABNORMAL_IP; do
if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
iptables -I INPUT -s $IP -j DROP
fi
done
方法2:經過日誌獲取登陸狀態
#!/bin/bash
DATE=$(date +"%b %d %H")
ABNORMAL_IP="$(tail -n10000 /var/log/auth.log |grep "$DATE" |awk '/Failed/{a[$(NF-3)]++}END{for(i in a)if(a[i]>5)print i}')"
for IP in $ABNORMAL_IP; do
if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
iptables -A INPUT -s $IP -j DROP
echo "$(date +"%F %T") - iptables -A INPUT -s $IP -j DROP" >>~/ssh-login-limit.log
fi
done
十二、判斷用戶輸入的是否爲IP地址
方法1:
#!/bin/bash
function check_ip(){
IP=$1
VALID_CHECK=$(echo $IP|awk -F. '$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
if echo $IP|grep -E "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$">/dev/null; then
if [ $VALID_CHECK == "yes" ]; then
echo "$IP available."
else
echo "$IP not available!"
fi
else
echo "Format error!"
fi
}
check_ip 192.168.1.1
check_ip 256.1.1.1
方法2:
#!/bin/bash
function check_ip(){
IP=$1
if [[ $IP =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ ]]; then
FIELD1=$(echo $IP|cut -d. -f1)
FIELD2=$(echo $IP|cut -d. -f2)
FIELD3=$(echo $IP|cut -d. -f3)
FIELD4=$(echo $IP|cut -d. -f4)
if [ $FIELD1 -le 255 -a $FIELD2 -le 255 -a $FIELD3 -le 255 -a $FIELD4 -le 255 ]; then
echo "$IP available."
else
echo "$IP not available!"
fi
else
echo "Format error!"
fi
}
check_ip 192.168.1.1
check_ip 256.1.1.1
增長版:
加個死循環,若是IP可用就退出,不可用提示繼續輸入,並使用awk判斷。
#!/bin/bash
function check_ip(){
local IP=$1
VALID_CHECK=$(echo $IP|awk -F. '$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
if echo $IP|grep -E "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$" >/dev/null; then
if [ $VALID_CHECK == "yes" ]; then
return 0
else
echo "$IP not available!"
return 1
fi
else
echo "Format error! Please input again."
return 1
fi
}
while true; do
read -p "Please enter IP: " IP
check_ip $IP
[ $? -eq 0 ] && break || continue
done
1三、判斷用戶輸入的是否爲數字
方法1:
#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]; then
echo "Is Number."
else
echo "No Number."
fi
方法2:
#!/bin/bash
if [ $1 -gt 0 ] 2>/dev/null; then
echo "Is Number."
else
echo "No Number."
fi
方法3:
#!/bin/bash
echo $1 |awk '{print $0~/^[0-9]+$/?"Is Number.":"No Number."}' #三目運算符
12.14 找出包含關鍵字的文件
DIR=$1
KEY=$2
for FILE in $(find $DIR -type f); do
if grep $KEY $FILE &>/dev/null; then
echo "--> $FILE"
fi
done
1四、給定目錄找出包含關鍵字的文件
#!/bin/bash
DIR=$1
KEY=$2
for FILE in $(find $DIR -type f); do
if grep $KEY $FILE &>/dev/null; then
echo "--> $FILE"
fi
done
1五、監控目錄,將新建立的文件名追加到日誌中
場景:記錄目錄下文件操做。
需先安裝inotify-tools軟件包。
#!/bin/bash
MON_DIR=/opt
inotifywait -mq --format %f -e create $MON_DIR |\
while read files; do
echo $files >> test.log
done
1六、給用戶提供多個網卡選擇
場景:服務器多個網卡時,獲取指定網卡,例如網卡流量
#!/bin/bash
function local_nic() {
local NUM ARRAY_LENGTH
NUM=0
for NIC_NAME in $(ls /sys/class/net|grep -vE "lo|docker0"); do
NIC_IP=$(ifconfig $NIC_NAME |awk -F'[: ]+' '/inet addr/{print $4}')
if [ -n "$NIC_IP" ]; then
NIC_IP_ARRAY[$NUM]="$NIC_NAME:$NIC_IP" #將網卡名和對應IP放到數組
let NUM++
fi
done
ARRAY_LENGTH=${#NIC_IP_ARRAY[]}
if [ $ARRAY_LENGTH -eq 1 ]; then #若是數組裏面只有一條記錄說明就一個網卡
NIC=${NIC_IP_ARRAY[0]%:}
return 0
elif [ $ARRAY_LENGTH -eq 0 ]; then #若是沒有記錄說明沒有網卡
echo "No available network card!"
exit 1
else
#若是有多條記錄則提醒輸入選擇
for NIC in ${NIC_IP_ARRAY[]}; do
echo $NIC
done
while true; do
read -p "Please enter local use to network card name: " INPUT_NIC_NAME
COUNT=0
for NIC in ${NIC_IP_ARRAY[]}; do
NIC_NAME=${NIC%:}
if [ $NIC_NAME == "$INPUT_NIC_NAME" ]; then
NIC=${NIC_IP_ARRAY[$COUNT]%:}
return 0
else
COUNT+=1
fi
done
echo "Not match! Please input again."
done
fi
}
local_nic
1七、查看網卡實時流量
適用於CentOS6操做系統。
#!/bin/bash
# Description: Only CentOS6
traffic_unit_conv() {
local traffic=$1
if [ $traffic -gt 1024000 ]; then
printf "%.1f%s" "$(($traffic/1024/1024))" "MB/s"
elif [ $traffic -lt 1024000 ]; then
printf "%.1f%s" "$(($traffic/1024))" "KB/s"
fi
}
NIC=$1
echo -e " In ------ Out"
while true; do
OLD_IN=$(awk -F'[: ]+' '$0~"'$NIC'"{print $3}' /proc/net/dev)
OLD_OUT=$(awk -F'[: ]+' '$0~"'$NIC'"{print $11}' /proc/net/dev)
sleep 1
NEW_IN=$(awk -F'[: ]+' '$0~"'$NIC'"{print $3}' /proc/net/dev)
NEW_OUT=$(awk -F'[: ]+' '$0~"'$NIC'"{print $11}' /proc/net/dev)
IN=$(($NEW_IN-$OLD_IN))
OUT=$(($NEW_OUT-$OLD_OUT))
echo "$(traffic_unit_conv $IN) $(traffic_unit_conv $OUT)"
sleep 1
done
使用:./traffic.sh eth0
1八、MySQL數據庫備份
#!/bin/bash
DATE=$(date +%F_%H-%M-%S)
HOST=192.168.1.120
DB=test
USER=bak
PASS=123456
MAIL="zhangsan@example.com lisi@example.com"
BACKUP_DIR=/data/db_backup
SQL_FILE=${DB}full$DATE.sql
BAK_FILE=${DB}full$DATE.zip
cd $BACKUP_DIR
if mysqldump -h$HOST -u$USER -p$PASS --single-transaction --routines --triggers -B $DB > $SQL_FILE; then
zip $BAK_FILE $SQL_FILE && rm -f $SQL_FILE
if [ ! -s $BAK_FILE ]; then
echo "$DATE 內容" | mail -s "主題" $MAIL
fi
else
echo "$DATE 內容" | mail -s "主題" $MAIL
fi
find $BACKUP_DIR -name '*.zip' -ctime +14 -exec rm {} \;
1九、Nginx服務管理腳本
場景:使用源碼包安裝Nginx不含帶服務管理腳本,也就是不能使用"service nginx start"或"/etc/init.d/nginx start",因此寫了如下的服務管理腳本。
#!/bin/bash
# Description: Only support RedHat system
. /etc/init.d/functions
WORD_DIR=/usr/local/nginx
DAEMON=$WORD_DIR/sbin/nginx
CONF=$WORD_DIR/conf/nginx.conf
NAME=nginx
PID=$(awk -F'[; ]+' '/^[^#]/{if($0~/pid;/)print $2}' $CONF)
if [ -z "$PID" ]; then
PID=$WORD_DIR/logs/nginx.pid
else
PID=$WORD_DIR/$PID
fi
stop() {
$DAEMON -s stop
sleep 1
[ ! -f $PID ] && action " Stopping $NAME" /bin/true || action " Stopping $NAME" /bin/false
}
start() {
$DAEMON
sleep 1
[ -f $PID ] && action " Starting $NAME" /bin/true || action " Starting $NAME" /bin/false
}
reload() {
$DAEMON -s reload
}
test_config() {
$DAEMON -t
}
case "$1" in
start)
if [ ! -f $PID ]; then
start
else
echo "$NAME is running..."
exit 0
fi
;;
stop)
if [ -f $PID ]; then
stop
else
echo "$NAME not running!"
exit 0
fi
;;
restart)
if [ ! -f $PID ]; then
echo "$NAME not running!"
start
else
stop
start
fi
;;
reload)
reload
;;
testconfig)
test_config
;;
status)
[ -f $PID ] && echo "$NAME is running..." || echo "$NAME not running!"
;;
)
echo "Usage: $0 {start|stop|restart|reload|testconfig|status}"
exit 3
;;
esac
20、用戶根據菜單選擇要鏈接的Linux主機
Linux主機SSH鏈接信息:
**# cat host.txt
Web 192.168.1.10 root 22
DB 192.168.1.11 root 22
內容格式:主機名 IP User Port
#!/bin/bashPS3="Please input number: "HOST_FILE=host.txtwhile true; doselect NAME in $(awk '{print $1}' $HOST_FILE) quit; do[ ${NAME:=empty} == "quit" ] && exit 0IP=$(awk -v NAME=${NAME} '$1==NAME{print $2}' $HOST_FILE)USER=$(awk -v NAME=${NAME} '$1==NAME{print $3}' $HOST_FILE)PORT=$(awk -v NAME=${NAME} '$1==NAME{print $4}' $HOST_FILE)if [ $IP ]; thenecho "Name: $NAME, IP: $IP"ssh -o StrictHostKeyChecking=no -p $PORT -i id_rsa $USER@$IP # 密鑰免交互登陸breakelseecho "Input error, Please enter again!"breakfidonedone