標籤:shell指令碼 shell面試題
注意事項
1)開頭加解譯器:#!/bin/bash
2)文法縮排,使用四個空格;多加註釋說明。
3)命名建議規則:變數名大寫、局部變數小寫,函數名小寫,名字型現出實際作用。
4)預設變數是全域的,在函數中變數local指定為局部變數,避免汙染其他範圍。
5)有兩個命令能協助我調試指令碼:set -e 遇到執行非0時退出指令碼,set-x 列印執行過程。
6)寫指令碼一定先測試再到生產上。
12.1 擷取隨機字串或數字
擷取隨機8位字串:
方法1:# echo $RANDOM |md5sum |cut -c 1-8471b94f2方法2:# openssl rand -base64 4vg3BEg==方法3:# cat /proc/sys/kernel/random/uuid |cut -c 1-8ed9e032c
擷取隨機8位元字:
方法1:# echo $RANDOM |cksum |cut -c 1-823648321方法2:# openssl rand -base64 4 |cksum |cut -c 1-838571131方法3:# date +%N |cut -c 1-869024815
cksum:列印CRC效驗和統計位元組
12.2 定義一個顏色輸出字串函數
方法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 "\033[32;40m$2\033[0m" ;; red) echo -e "\033[31;40m$2\033[0m" ;; *) echo "Example: echo_color red string" esac}使用方法:echo_color green "test"
function關鍵字定義一個函數,可加或不加。
12.3 大量建立使用者
#!/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}# 如果使用者檔案存在並且大小大於0就備份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 檢查軟體包是否安裝
#!/bin/bashif rpm -q sysstat &>/dev/null; then echo "sysstat is already installed."else echo "sysstat is not installed!"fi
12.5 檢查服務狀態
#!/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 "內容" | mail -s "主題" [email protected]fi
12.6 檢查主機存活狀態
方法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 # 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
方法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 # echo "$IP Ping is failure $i" let FAIL_COUNT++ fi done if [ $FAIL_COUNT -eq 3 ]; then echo "$IP Ping is failure!" fidone
方法3:利用for迴圈將ping通就跳出迴圈繼續,如果不跳出就會走到列印ping失敗
#!/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 ping_success_status ping_success_status echo "$IP Ping is failure!"done
12.7 監控CPU、記憶體和硬碟利用率
1)CPU
藉助vmstat工具來分析CPU統計資訊。
#!/bin/bashDATE=$(date +%F" "%H:%M)IP=$(ifconfig eth0 |awk -F ‘[ :]+‘ ‘/inet addr/{print $4}‘) # 只支援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)記憶體
#!/bin/bashDATE=$(date +%F" "%H:%M)IP=$(ifconfig eth0 |awk -F ‘[ :]+‘ ‘/inet addr/{print $4}‘) MAIL="[email protected]"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" $MAILfi
3)硬碟
#!/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($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
12.8 批量主機磁碟利用率監控
前提監控端和被監控端SSH免互動登入或者密鑰登入。
寫一個設定檔儲存被監控主機SSH串連資訊,檔案內容格式: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($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 donedone
12.9 檢查網站可用性
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!" fidone方法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[*] #清空數組 fidone
本章寫的Shell指令碼例子都比較實用,在面試題中也經常出現,希望大家參考著多動手寫寫,不要複製粘貼就拿來跑,這樣是學不會的!有問題請加群交流:323779636(Shell/Python營運開發群)
本文出自 “李振良的技術部落格” 部落格,請務必保留此出處http://lizhenliang.blog.51cto.com/7876557/1929044
第十二章 Shell指令碼編寫及常見面試題(一)