获取随机字符串或数字

1.获取随机 8 位字符串

  1. 方法 1 # echo $RANDOM |md5sum |cut -c 1-8
  2. 471b94f2
  3. 方法 2 # openssl rand -base64 4
  4. vg3BEg==
  5. 方法 3 # cat /proc/sys/kernel/random/uuid |cut -c 1-8
  6. ed9e032c

2.获取随机 8 位数字

  1. 方法 1 # echo $RANDOM |cksum |cut -c 1-8
  2. 23648321
  3. 方法 2 # openssl rand -base64 4 |cksum |cut -c 1-8
  4. 38571131
  5. 方法 3 # date +%N |cut -c 1-8
  6. 69024815

定义一个颜色输出字符串函数

方法 1

  1. #!/bin/bash
  2. function echo_color(){
  3. if [ $1 == "green" ]; then
  4. echo -e "\033[32;40m$2\033[0m"
  5. elif [ $1 == "red" ]; then
  6. echo -e "\033[31;40m$2\033[0m"
  7. fi
  8. }
  9. echo_color green "我是绿色"
  10. echo_color red "我是红色"

方法 2:也可以在前面不写function,也可以定义函数

  1. #!/bin/bash
  2. echo_color(){
  3. case $1 in
  4. green)
  5. echo -e "\033[32;40m$2\033[0m"
  6. ;;
  7. red)
  8. echo -e "\033[31;40m$2\033[0m"
  9. ;;
  10. *)
  11. echo "Example: echo_color red string"
  12. esac
  13. }
  14. echo_color green "我是绿色"

创建用户

  1. #!/bin/bash
  2. USER="cola1"
  3. if ! id $USER &>/dev/null; then
  4. PASS=$(echo $RANDOM |md5sum |cut -c 1-10)
  5. useradd $USER
  6. echo $PASS |passwd --stdin $USER &>/dev/null
  7. echo "$USER User create successful."
  8. else
  9. echo "$USER User already exists!"
  10. fi

检查服务状态

如果端口、进程有一个不存在则报警

  1. #!/bin/bash
  2. PORT_C=$(ss -anu |grep -c 123)
  3. PS_C=$(ps -ef |grep ntpd |grep -vc grep)
  4. if [ $PORT_C -eq 0 -o $PS_C -eq 0 ]; then
  5. echo "内容" | mail -s "主题" dst@example.com
  6. fi

检查主机存活状态

方法 1:将错误 IP 放到数组里面判断是否 ping 失败三次

  1. #!/bin/bash
  2. IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
  3. for IP in $IP_LIST; do
  4. NUM=1
  5. while [ $NUM -le 3 ]; do
  6. if ping -c 1 $IP > /dev/null; then
  7. echo "$IP Ping is successful."
  8. break
  9. else
  10. # echo "$IP Ping is failure $NUM"
  11. FAIL_COUNT[$NUM]=$IP
  12. let NUM++
  13. fi
  14. done
  15. if [ ${#FAIL_COUNT[*]} -eq 3 ];then
  16. echo "${FAIL_COUNT[1]} Ping is failure!"
  17. unset FAIL_COUNT[*]
  18. fi
  19. done

方法 2:将错误次数放到 FAIL_COUNT 变量里面判断是否 ping 失败三次

  1. #!/bin/bash
  2. IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
  3. for IP in $IP_LIST; do
  4. FAIL_COUNT=0
  5. for ((i=1;i<=3;i++)); do
  6. if ping -c 1 $IP >/dev/null; then
  7. echo "$IP Ping is successful."
  8. break
  9. else
  10. # echo "$IP Ping is failure $i"
  11. let FAIL_COUNT++
  12. fi
  13. done
  14. if [ $FAIL_COUNT -eq 3 ]; then
  15. echo "$IP Ping is failure!"
  16. fi
  17. done

方法 3:利用 for 循环将 ping 通就跳出循环继续,如果不跳出就会走到打印 ping 失败

  1. #!/bin/bash
  2. ping_success_status() {
  3. if ping -c 1 $IP >/dev/null; then
  4. echo "$IP Ping is successful."
  5. continue
  6. fi
  7. }
  8. IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
  9. for IP in $IP_LIST; do
  10. ping_success_status
  11. ping_success_status
  12. ping_success_status
  13. echo "$IP Ping is failure!"
  14. done

监控 CPU、内存和硬盘利用率

1)CPU
借助 vmstat 工具来分析 CPU 统计信息。

  1. #!/bin/bash
  2. DATE=$(date +%F" "%H:%M)
  3. IP=$(ifconfig eth0 |awk -F '[ :]+' '/inet addr/{print $4}') # 只支持 CentOS6
  4. MAIL="example@mail.com"
  5. if ! which vmstat &>/dev/null; then
  6. echo "vmstat command no found, Please install procps package."
  7. exit 1
  8. fi
  9. US=$(vmstat |awk 'NR==3{print $13}')
  10. SY=$(vmstat |awk 'NR==3{print $14}')
  11. IDLE=$(vmstat |awk 'NR==3{print $15}')
  12. WAIT=$(vmstat |awk 'NR==3{print $16}')
  13. USE=$(($US+$SY))
  14. if [ $USE -ge 50 ]; then
  15. echo "
  16. Date: $DATE
  17. Host: $IP
  18. Problem: CPU utilization $USE
  19. " | mail -s "CPU Monitor" $MAIL
  20. fi

2)内存

  1. #!/bin/bash
  2. DATE=$(date +%F" "%H:%M)
  3. IP=$(ifconfig eth0 |awk -F '[ :]+' '/inet addr/{print $4}')
  4. MAIL="example@mail.com"
  5. TOTAL=$(free -m |awk '/Mem/{print $2}')
  6. USE=$(free -m |awk '/Mem/{print $3-$6-$7}')
  7. FREE=$(($TOTAL-$USE))
  8. # 内存小于 1G 发送报警邮件
  9. if [ $FREE -lt 1024 ]; then
  10. echo "
  11. Date: $DATE
  12. Host: $IP
  13. Problem: Total=$TOTAL,Use=$USE,Free=$FREE
  14. " | mail -s "Memory Monitor" $MAIL
  15. fi

3)硬盘

  1. #!/bin/bash
  2. DATE=$(date +%F" "%H:%M)
  3. IP=$(ifconfig eth0 |awk -F '[ :]+' '/inet addr/{print $4}')
  4. MAIL="example@mail.com"
  5. TOTAL=$(fdisk -l |awk -F'[: ]+' 'BEGIN{OFS="="}/^Disk \/dev/{printf "%s=%sG,",$2,$3}')
  6. PART_USE=$(df -h |awk 'BEGIN{OFS="="}/^\/dev/{print $1,int($5),$6}')
  7. for i in $PART_USE; do
  8. PART=$(echo $i |cut -d"=" -f1)
  9. USE=$(echo $i |cut -d"=" -f2)
  10. MOUNT=$(echo $i |cut -d"=" -f3)
  11. if [ $USE -gt 80 ]; then
  12. echo "
  13. Date: $DATE
  14. Host: $IP
  15. Total: $TOTAL
  16. Problem: $PART=$USE($MOUNT)
  17. " | mail -s "Disk Monitor" $MAIL
  18. fi
  19. done

批量主机磁盘利用率监控
前提监控端和被监控端 SSH 免交互登录或者密钥登录。
写一个配置文件保存被监控主机 SSH 连接信息,文件内容格式:IP User Port

  1. #!/bin/bash
  2. HOST_INFO=host.info
  3. for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do
  4. USER=$(awk -v ip=$IP 'ip==$1{print $2}' $HOST_INFO)
  5. PORT=$(awk -v ip=$IP 'ip==$1{print $3}' $HOST_INFO)
  6. TMP_FILE=/tmp/disk.tmp
  7. ssh -p $PORT $USER@$IP 'df -h' > $TMP_FILE
  8. USE_RATE_LIST=$( awk 'BEGIN{OFS="="}/^\/dev/{print $1,int($5)}' $TMP_FILE)
  9. for USE_RATE in $USE_RATE_LIST; do
  10. PART_NAME=${USE_RATE%=*}
  11. USE_RATE=${USE_RATE#*=}
  12. if [ $USE_RATE -ge 80 ]; then
  13. echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
  14. fi
  15. done
  16. done

检查网站可用性

1)检查 URL 可用性

  1. check_url() {
  2. HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $1)
  3. if [ $HTTP_CODE -ne 200 ]; then
  4. echo "Warning: $1 Access failure!"
  5. fi
  6. }

2

  1. check_url() {
  2. if ! wget -T 10 --tries=1 --spider $1 >/dev/null 2>&1; then
  3. #-T 超时时间,--tries 尝试 1 次,--spider 爬虫模式
  4. echo "Warning: $1 Access failure!"
  5. fi
  6. }

使用方法:check_url www.baidu.com

2)判断三次 URL 可用性
思路与上面检查主机存活状态一样。
方法 1:利用循环技巧,如果成功就跳出当前循环,否则执行到最后一行

  1. #!/bin/bash
  2. check_url() {
  3. HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $1)
  4. if [ $HTTP_CODE -eq 200 ]; then
  5. continue
  6. fi
  7. }
  8. URL_LIST="www.baidu.com www.agasgf.com"
  9. for URL in $URL_LIST; do
  10. check_url $URL
  11. check_url $URL
  12. check_url $URL
  13. echo "Warning: $URL Access failure!"
  14. done

方法 2:错误次数保存到变量

  1. #!/bin/bash
  2. URL_LIST="www.baidu.com www.agasgf.com"
  3. for URL in $URL_LIST; do
  4. FAIL_COUNT=0
  5. for ((i=1;i<=3;i++)); do
  6. HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL)
  7. if [ $HTTP_CODE -ne 200 ]; then
  8. let FAIL_COUNT++
  9. else
  10. break
  11. fi
  12. done
  13. if [ $FAIL_COUNT -eq 3 ]; then
  14. echo "Warning: $URL Access failure!"
  15. fi
  16. done

方法 3:错误次数保存到数组

  1. #!/bin/bash
  2. URL_LIST="www.baidu.com www.agasgf.com"
  3. for URL in $URL_LIST; do
  4. NUM=1
  5. while [ $NUM -le 3 ]; do
  6. HTTP_CODE=$(curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" $URL)
  7. if [ $HTTP_CODE -ne 200 ]; then
  8. FAIL_COUNT[$NUM]=$IP #创建数组,以$NUM 下标,$IP 元素
  9. let NUM++
  10. else
  11. break
  12. fi
  13. done
  14. if [ ${#FAIL_COUNT[*]} -eq 3 ]; then
  15. echo "Warning: $URL Access failure!"
  16. unset FAIL_COUNT[*] #清空数组
  17. fi
  18. done

检查 MySQL 主从同步状态

  1. #!/bin/bash
  2. USER=bak
  3. PASSWD=123456
  4. IO_SQL_STATUS=$(mysql -u$USER -p$PASSWD -e 'show slave status\G' |awk -F:
  5. '/Slave_.*_Running/{gsub(": ",":");print $0}') #gsub 去除冒号后面的空格
  6. for i in $IO_SQL_STATUS; do
  7. THREAD_STATUS_NAME=${i%:*}
  8. THREAD_STATUS=${i#*:}
  9. if [ "$THREAD_STATUS" != "Yes" ]; then
  10. echo "Error: MySQL Master-Slave $THREAD_STATUS_NAME status is
  11. $THREAD_STATUS!"
  12. fi
  13. done

屏蔽访问频繁的 IP
1)屏蔽每分钟访问超过 200 的 IP
方法 1:以 Nginx 日志作为测试

  1. DATE=$(date +%d/%b/%Y:%H:%M)
  2. ABNORMAL_IP=$(tail -n5000 access.log |grep $DATE |awk '{a[$1]++}END{for(i in
  3. a)if(a[i]>100)print i}')
  4. #先 tail 防止文件过大,读取慢,数字可调整每分钟最大的访问量。awk 不能直接过滤日志,因为
  5. 包含特殊字符。
  6. for IP in $ABNORMAL_IP; do
  7. if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
  8. iptables -I INPUT -s $IP -j DROP
  9. fi
  10. done

方法 2:通过建立连接数

  1. ABNORMAL_IP=$(netstat -an |awk '$4~/:80$/ && $6~/ESTABLISHED/{gsub(/:[0-
  2. 9]+/,"",$5);{a[$5]++}}END{for(i in a)if(a[i]>100)print i}')
  3. #gsub 是将第五列(客户端 IP)的冒号和端口去掉
  4. for IP in $ABNORMAL_IP; do
  5. if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
  6. iptables -I INPUT -s $IP -j DROP
  7. fi
  8. done

2)屏蔽每分钟 SSH 暴力破解超过 10 次的 IP
方法 1:通过 lastb 获取登录状态:

  1. DATE=$(date +"%a %b %e %H:%M") #星期月天时分 %e 单数字时显示 7,而%d 显示 07
  2. ABNORMAL_IP=$(lastb |grep "$DATE" |awk '{a[$3]++}END{for(i in a)if(a[i]>10)print i}')
  3. for IP in $ABNORMAL_IP; do
  4. if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
  5. iptables -I INPUT -s $IP -j DROP
  6. fi
  7. done

方法 2:通过日志获取登录状态

  1. DATE=$(date +"%b %d %H")
  2. ABNORMAL_IP="$(tail -n10000 /var/log/auth.log |grep "$DATE" |awk '/Failed/{a[$(NF-
  3. 3)]++}END{for(i in a)if(a[i]>5)print i}')"
  4. for IP in $ABNORMAL_IP; do
  5. if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
  6. iptables -A INPUT -s $IP -j DROP
  7. echo "$(date +"%F %T") - iptables -A INPUT -s $IP -j DROP" >>~/ssh-loginlimit.log
  8. fi
  9. done

判断输入是否为 IP
方法 1:

  1. function check_ip(){
  2. IP=$1
  3. VALID_CHECK=$(echo $IP|awk -F. '$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
  4. if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$">/dev/null;
  5. then
  6. if [ $VALID_CHECK == "yes" ]; then
  7. echo "$IP available."
  8. else
  9. echo "$IP not available!"
  10. fi
  11. else
  12. echo "Format error!"
  13. fi
  14. }
  15. check_ip 192.168.1.1
  16. check_ip 256.1.1.1

方法 2:

  1. function check_ip(){
  2. IP=$1
  3. if [[ $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
  4. FIELD1=$(echo $IP|cut -d. -f1)
  5. FIELD2=$(echo $IP|cut -d. -f2)
  6. FIELD3=$(echo $IP|cut -d. -f3)
  7. FIELD4=$(echo $IP|cut -d. -f4)
  8. if [ $FIELD1 -le 255 -a $FIELD2 -le 255 -a $FIELD3 -le 255 -a $FIELD4 -le
  9. 255 ]; then
  10. echo "$IP available."
  11. else
  12. echo "$IP not available!"
  13. fi
  14. else
  15. echo "Format error!"
  16. fi
  17. }
  18. check_ip 192.168.1.1
  19. check_ip 256.1.1.1

增加版:加个死循环,如果 IP 可用就退出,不可用提示继续输入,并使用 awk 判断

  1. function check_ip(){
  2. local IP=$1
  3. VALID_CHECK=$(echo $IP|awk -F. '$1<=255&&$2<=255&&$3<=255&&$4<=255{print "yes"}')
  4. if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" >/dev/null;
  5. then
  6. if [ $VALID_CHECK == "yes" ]; then
  7. return 0
  8. else
  9. echo "$IP not available!"
  10. return 1
  11. fi
  12. else
  13. echo "Format error! Please input again."
  14. return 1
  15. fi
  16. }
  17. while true; do
  18. read -p "Please enter IP: " IP
  19. check_ip $IP
  20. [ $? -eq 0 ] && break || continue
  21. done

判断输入是否为数字
方法 1:

  1. if [[ $1 =~ ^[0-9]+$ ]]; then
  2. echo "Is Number."
  3. else
  4. echo "No Number."
  5. fi
  6. 方法 2
  7. if [ $1 -gt 0 ] 2>/dev/null; then
  8. echo "Is Number."
  9. else
  10. echo "No Number."
  11. fi

方法 3:

  1. echo $1 |awk '{print $0~/^[0-9]+$/?"Is Number.":"No Number."}' #三目运算符
  2. ## 找出包含关键字的文件
  3. ```bash
  4. DIR=$1
  5. KEY=$2
  6. for FILE in $(find $DIR -type f); do
  7. if grep $KEY $FILE &>/dev/null; then
  8. echo "--> $FILE"
  9. fi
  10. done

监控目录,将新创建的文件名追加到日志中
需安装 inotify-tools 软件包。

  1. #!/bin/bash
  2. MON_DIR=/opt
  3. inotifywait -mq --format %f -e create $MON_DIR |\
  4. while read files; do
  5. echo $files >> test.log
  6. done

12.16 多个网卡选择

  1. function local_nic() {
  2. local NUM ARRAY_LENGTH
  3. NUM=0
  4. for NIC_NAME in $(ls /sys/class/net|grep -vE "lo|docker0"); do
  5. NIC_IP=$(ifconfig $NIC_NAME |awk -F'[: ]+' '/inet addr/{print $4}')
  6. if [ -n "$NIC_IP" ]; then
  7. NIC_IP_ARRAY[$NUM]="$NIC_NAME:$NIC_IP" #将网卡名和对应 IP 放到数
  8. let NUM++
  9. fi
  10. done
  11. ARRAY_LENGTH=${#NIC_IP_ARRAY[*]}
  12. if [ $ARRAY_LENGTH -eq 1 ]; then #如果数组里面只有一条记录说明就一个网卡
  13. NIC=${NIC_IP_ARRAY[0]%:*}
  14. return 0
  15. elif [ $ARRAY_LENGTH -eq 0 ]; then #如果没有记录说明没有网卡
  16. echo "No available network card!"
  17. exit 1
  18. else
  19. #如果有多条记录则提醒输入选择
  20. for NIC in ${NIC_IP_ARRAY[*]}; do
  21. echo $NIC
  22. done
  23. while true; do
  24. read -p "Please enter local use to network card name: "
  25. INPUT_NIC_NAME
  26. COUNT=0
  27. for NIC in ${NIC_IP_ARRAY[*]}; do
  28. NIC_NAME=${NIC%:*}
  29. if [ $NIC_NAME == "$INPUT_NIC_NAME" ]; then
  30. NIC=${NIC_IP_ARRAY[$COUNT]%:*}
  31. return 0
  32. else
  33. COUNT+=1
  34. fi
  35. done
  36. echo "Not match! Please input again."
  37. done
  38. fi
  39. }
  40. local_nic

如果有只有一个网卡就不选择。

查看网卡实时流量

  1. #!/bin/bash
  2. # Description: Only CentOS6
  3. traffic_unit_conv() {
  4. local traffic=$1
  5. if [ $traffic -gt 1024000 ]; then
  6. printf "%.1f%s" "$(($traffic/1024/1024))" "MB/s"
  7. elif [ $traffic -lt 1024000 ]; then
  8. printf "%.1f%s" "$(($traffic/1024))" "KB/s"
  9. fi
  10. }
  11. NIC=$1
  12. echo -e " In ------ Out"
  13. while true; do
  14. OLD_IN=$(awk -F'[: ]+' '$0~"'$NIC'"{print $3}' /proc/net/dev)
  15. OLD_OUT=$(awk -F'[: ]+' '$0~"'$NIC'"{print $11}' /proc/net/dev)
  16. sleep 1
  17. NEW_IN=$(awk -F'[: ]+' '$0~"'$NIC'"{print $3}' /proc/net/dev)
  18. NEW_OUT=$(awk -F'[: ]+' '$0~"'$NIC'"{print $11}' /proc/net/dev)
  19. IN=$(($NEW_IN-$OLD_IN))
  20. OUT=$(($NEW_OUT-$OLD_OUT))
  21. echo "$(traffic_unit_conv $IN) $(traffic_unit_conv $OUT)"
  22. sleep 1
  23. done

也可以通过 ficonfig 命令获取收发流量

  1. while true; do
  2. OLD_IN=$(ifconfig $NIC |awk -F'[: ]+' '/bytes/{print $4}')
  3. OLD_OUT=$(ifconfig $NIC |awk -F'[: ]+' '/bytes/{print $9}')
  4. sleep 1
  5. NEW_IN=$(ifconfig $NIC |awk -F'[: ]+' '/bytes/{print $4}')
  6. NEW_OUT=$(ifconfig $NIC |awk -F'[: ]+' '/bytes/{print $9}')
  7. IN=$(($NEW_IN-$OLD_IN))
  8. OUT=$(($NEW_OUT-$OLD_OUT))
  9. echo "$(traffic_unit_conv $IN) $(traffic_unit_conv $OUT)"
  10. sleep 1
  11. done

12.18 MySQL 数据库备份

  1. #!/bin/bash
  2. DATE=$(date +%F_%H-%M-%S)
  3. HOST=192.168.1.120
  4. DB=test
  5. USER=bak
  6. PASS=123456
  7. MAIL="zhangsan@example.com lisi@example.com"
  8. BACKUP_DIR=/data/db_backup
  9. SQL_FILE=${DB}_full_$DATE.sql
  10. BAK_FILE=${DB}_full_$DATE.zip
  11. cd $BACKUP_DIR
  12. if mysqldump -h$HOST -u$USER -p$PASS --single-transaction --routines --triggers -B
  13. $DB > $SQL_FILE; then
  14. zip $BAK_FILE $SQL_FILE && rm -f $SQL_FILE
  15. if [ ! -s $BAK_FILE ]; then
  16. echo "$DATE 内容" | mail -s "主题" $MAIL
  17. fi
  18. else
  19. echo "$DATE 内容" | mail -s "主题" $MAIL
  20. fi
  21. find $BACKUP_DIR -name '*.zip' -ctime +14 -exec rm {} \;

12.19 Nginx 启动脚本

  1. #!/bin/bash
  2. # Description: Only support RedHat system
  3. . /etc/init.d/functions
  4. WORD_DIR=/data/project/nginx1.10
  5. DAEMON=$WORD_DIR/sbin/nginx
  6. CONF=$WORD_DIR/conf/nginx.conf
  7. NAME=nginx
  8. PID=$(awk -F'[; ]+' '/^[^#]/{if($0~/pid;/)print $2}' $CONF)
  9. if [ -z "$PID" ]; then
  10. PID=$WORD_DIR/logs/nginx.pid
  11. else
  12. PID=$WORD_DIR/$PID
  13. fi
  14. stop() {
  15. $DAEMON -s stop
  16. sleep 1 [ ! -f $PID ] && action "* Stopping $NAME" /bin/true || action "* Stopping
  17. $NAME" /bin/false
  18. }
  19. start() {
  20. $DAEMON
  21. sleep 1 [ -f $PID ] && action "* Starting $NAME" /bin/true || action "* Starting $NAME"
  22. /bin/false
  23. }
  24. reload() {
  25. $DAEMON -s reload
  26. }
  27. test_config() {
  28. $DAEMON -t }
  29. case "$1" in
  30. start)
  31. if [ ! -f $PID ]; then
  32. start
  33. else
  34. echo "$NAME is running..."
  35. exit 0
  36. fi
  37. ;;
  38. stop)
  39. if [ -f $PID ]; then
  40. stop
  41. else
  42. echo "$NAME not running!"
  43. exit 0
  44. fi
  45. ;;
  46. restart)
  47. if [ ! -f $PID ]; then
  48. echo "$NAME not running!"
  49. start
  50. else
  51. stop
  52. start
  53. fi
  54. ;;
  55. reload)
  56. reload
  57. ;;
  58. testconfig)
  59. test_config
  60. ;;
  61. status)
  62. [ -f $PID ] && echo "$NAME is running..." || echo "$NAME not running!"
  63. ;;
  64. *)
  65. echo "Usage: $0 {start|stop|restart|reload|testconfig|status}"
  66. exit 3
  67. ;;
  68. esac

12.20 选择 SSH 连接主机
写一个配置文件保存被监控主机 SSH 连接信息,文件内容格式:主机名 IP User Port

  1. #!/bin/bash
  2. PS3="Please input number: "
  3. HOST_FILE=host
  4. while true; do
  5. select NAME in $(awk '{print $1}' $HOST_FILE) quit; do
  6. [ ${NAME:=empty} == "quit" ] && exit 0
  7. IP=$(awk -v NAME=${NAME} '$1==NAME{print $2}' $HOST_FILE)
  8. USER=$(awk -v NAME=${NAME} '$1==NAME{print $3}' $HOST_FILE)
  9. PORT=$(awk -v NAME=${NAME} '$1==NAME{print $4}' $HOST_FILE)
  10. if [ $IP ]; then
  11. echo "Name: $NAME, IP: $IP"
  12. ssh -o StrictHostKeyChecking=no -p $PORT -i id_rsa $USER@$IP # 密钥登录
  13. break
  14. else
  15. echo "Input error, Please enter again!"
  16. break
  17. fi
  18. done
  19. done

12.21 FTP 下载文件

  1. #!/bin/bash
  2. if [ $# -ne 1 ]; then
  3. echo "Usage: $0 filename"
  4. fi
  5. dir=$(dirname $1)
  6. file=$(basename $1)
  7. ftp -n -v << EOF # -n 自动登录
  8. open 192.168.1.10
  9. user admin adminpass
  10. binary # 设置 ftp 传输模式为二进制,避免 MD5 值不同或.tar.gz 压缩包格式错误
  11. cd $dir
  12. get "$file"
  13. EOF

12.22 输入五个 100 数之内的字符,统计和、最小和最大

  1. COUNT=1
  2. SUM=0
  3. MIN=0
  4. MAX=100
  5. while [ $COUNT -le 5 ]; do
  6. read -p "请输入 1-10 个整数:" INT
  7. if [[ ! $INT =~ ^[0-9]+$ ]]; then
  8. echo "输入必须是整数!"
  9. exit 1
  10. elif [[ $INT -gt 100 ]]; then
  11. echo "输入必须是 100 以内!"
  12. exit 1
  13. fi
  14. SUM=$(($SUM+$INT))
  15. [ $MIN -lt $INT ] && MIN=$INT
  16. [ $MAX -gt $INT ] && MAX=$INT
  17. let COUNT++
  18. done
  19. echo "SUM: $SUM"
  20. echo "MIN: $MIN"
  21. echo "MAX: $MAX"

12.22 等待执行

  1. wait(){
  2. echo -n "wait 3s"
  3. for ((i=1;i<=3;i++)); do
  4. echo -n "."
  5. sleep 1
  6. done
  7. echo
  8. }
  9. wait

12.23 将结果分别赋值给变量
方法 1:

  1. for i in $(echo "4 5 6"); do
  2. eval a$i=$i
  3. done
  4. echo $a4 $a5 $a6

方法 2:将位置参数 192.168.18.1{1,2}拆分为到每个变量

  1. num=0
  2. for i in $(eval echo $*);do #eval 将{1,2}分解为 1 2
  3. let num+=1
  4. eval node${num}="$i"
  5. done
  6. echo $node1 $node2 $node3
  7. # bash a.sh 192.168.18.1{1,2}
  8. 192.168.18.11 192.168.18.12

方法 3:

  1. arr=(4 5 6)
  2. INDEX1=$(echo ${arr[0]})
  3. INDEX2=$(echo ${arr[1]})
  4. INDEX3=$(echo ${arr[2]})

12.24 批量修改文件
``bash

touch article_{1..3}.html

ls

article1.html article_2.html article_3.html
现在想把 article 改为 bbs:
方法 1:
for file in $(ls *html); do
mv ![](https://g.yuque.com/gr/latex?file%20bbs
#card=math&code=file%20bbs){file#*}

mv $file $(echo $file |sed -r ‘s/.(_.)/bbs\1/‘)

mv $file $(echo shell-实战 - 图2(cut -d_ -f2)

done
方法 2:
for file in $(find . -maxdepth 1 -name “html”); do
mv shell-实战 - 图3{file#
_}
done
方法 3: # rename article bbs .html
12.25 统计当前目录中以.html 结尾的文件总大小
方法 1: # find . -name “
.html” -maxdepth 1 -exec du -b {} ; |awk ‘{sum+=$1}END{print sum}’
方法 2:
for size in $(ls -l *.html |awk ‘{print shell-实战 - 图4%3B%20do%0Asum%3D#card=math&code=5%7D%27%29%3B%20do%0Asum%3D)((shell-实战 - 图5size))
done
echo $sum
递归统计:

find . -name “*.html” -exec du -k {} ; |awk ‘{sum+=$1}END{print sum}’

12.26 扫描主机端口状态

!/bin/bash

HOST=$1
PORT=”22 25 80 8080”
for PORT in shell-实战 - 图6HOST/shell-实战 - 图7PORT open”
else
echo “shell-实战 - 图8argc 统计位置参数数量
[lindex $argv 0] 位置参数
puts 打印字符串,类似于 echo
expect{…} 输入多行记录
方法 1:EOF 标准输出作为 expect 标准输入

!/bin/bash

USER=root
PASS=123.com
IP=192.168.1.120
expect << EOF
set timeout 30
spawn ssh shell-实战 - 图9IP
expect {
“(yes/no)” {send “yes\r”; exp_continue}
“password:” {send “shell-实战 - 图10USER@“ {send “shell-实战 - 图11USER@“ {send “exit\r”}
expect eof
EOF
方法 2:

!/bin/bash

USER=root
PASS=123.com
IP=192.168.1.120
expect -c “
spawn ssh shell-实战 - 图12IP
expect {
“(yes/no)” {send “yes\r”; exp_continue}
“password:” {send “shell-实战 - 图13USER@*” {send “df -h\r exit\r”; exp_continue}
}”
方法 3:将 expect 脚本独立出来
login.exp 登录文件:

!/usr/bin/expect

set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set cmd [lindex $argv 3]
if { $argc != 4 } {
puts “Usage: expect login.exp ip user passwd”
exit 1
}
set timeout 30
spawn ssh shell-实战 - 图14ip
expect {
“(yes/no)” {send “yes\r”; exp_continue}
“password:” {send “shell-实战 - 图15user@“ {send “shell-实战 - 图16user@“ {send “exit\r”}
expect eof
执行命令脚本:

!/bin/bash

HOST_INFO=user_info
for ip in $(awk ‘{print $1}’ shell-实战 - 图17%0Ado%0Auser%3D#card=math&code=HOST_INFO%29%0Ado%0Auser%3D)(awk -v I=”$ip” ‘I==$1{print $2}’ shell-实战 - 图18%0Apass%3D#card=math&code=HOST_INFO%29%0Apass%3D)(awk -v I=”$ip” ‘I==$1{print $3}’ $HOST_INFO)
expect login.exp $ip $user $pass $1
done
SSH 连接信息文件:

cat user_info

192.168.1.120 root 123456
12.28 批量修改服务器用户密码
旧密码 SSH 主机信息 old_info 文件:

ip user passwd port

———————————————————

192.168.18.217 root 123456 22
192.168.18.218 root 123456 22
修改密码脚本:

!/bin/bash

OLD_INFO=old_info
NEW_INFO=new_info
for IP in $(awk ‘/#]/{print $1}’ shell-实战 - 图19%3B%20do%0AUSER%3D#card=math&code=OLD_INFO%29%3B%20do%0AUSER%3D)(awk -v I=$IP ‘I==$1{print $2}’ shell-实战 - 图20%0APASS%3D#card=math&code=OLD_INFO%29%0APASS%3D)(awk -v I=$IP ‘I==$1{print $3}’ shell-实战 - 图21%0APORT%3D#card=math&code=OLD_INFO%29%0APORT%3D)(awk -v I=$IP ‘I==$1{print $4}’ shell-实战 - 图22%0ANEW_PASS%3D#card=math&code=OLD_INFO%29%0ANEW_PASS%3D)(mkpasswd -l 8)
echo “$IP $USER $NEW_PASS $PORT” >> shell-实战 - 图23PORT shell-实战 - 图24IP
set timeout 2
expect {
“(yes/no)” {send “yes\r”;exp_continue}
“password:” {send “shell-实战 - 图25USER@“ {send “echo ‘$NEW_PASS’ |passwd —stdin shell-实战 - 图26%7Bfor(i%3D0%3Bi%2B%2B%3Cn%3B)printf%20i%22x%22n%22%3D%22in%22%20%22%3Bprint%20%22%22%7D%7D’%0A%E6%96%B9%E6%B3%95%202%EF%BC%9A%0Afor%20((i%3D1%3Bi%3C%3D9%3Bi%2B%2B))%3B%20do%0Afor%20((j%3D1%3Bj%3C%3Di%3Bj%2B%2B))%3B%20do%0Aresult%3D#card=math&code=USER%5Cr%20%0Aexit%5Cr%5C%22%3Bexp_continue%7D%0A%7D%22%0Adone%0A%E7%94%9F%E6%88%90%E6%96%B0%E5%AF%86%E7%A0%81%20new_info%20%E6%96%87%E4%BB%B6%EF%BC%9A%0A192.168.18.217%20root%20n8wX3mU%25%2022%0A192.168.18.218%20root%20c87%3BZnnL%2022%0A12.29%20%E6%89%93%E5%8D%B0%E4%B9%98%E6%B3%95%E5%8F%A3%E8%AF%80%0A%E6%96%B9%E6%B3%95%201%EF%BC%9A%20%23%20awk%20%27BEGIN%7Bfor%28n%3D0%3Bn%2B%2B%3C9%3B%29%7Bfor%28i%3D0%3Bi%2B%2B%3Cn%3B%29printf%20i%22x%22n%22%3D%22i%2An%22%20%22%3Bprint%20%22%22%7D%7D%27%0A%E6%96%B9%E6%B3%95%202%EF%BC%9A%0Afor%20%28%28i%3D1%3Bi%3C%3D9%3Bi%2B%2B%29%29%3B%20do%0Afor%20%28%28j%3D1%3Bj%3C%3Di%3Bj%2B%2B%29%29%3B%20do%0Aresult%3D)((shell-实战 - 图27j))
echo -n “shell-实战 - 图28i=$result “
done
echo
done
12.30 getopts 工具完善脚本命令行参数
getopts 是一个解析脚本选项参数的工具。
命令格式:getopts optstring name [arg]
初次使用你要注意这几点: 1)脚本位置参数会与 optstring 中的单个字母逐个匹配,如果匹配到就赋值给 name,否则赋值 name
为问号;
2)optstring 中单个字母是一个选项,如果字母后面加冒号,表示该选项后面带参数,参数值并会赋
值给 OPTARG 变量;
3)optstring 中第一个是冒号,表示屏蔽系统错误(test.sh: illegal option — h); 4)允许把选项放一起,例如-ab
下面写一个打印文件指定行的简单例子,用于引导你思路,扩展你的脚本选项功能:

!/bin/bash

while getopts :f:n: option; do
case shell-实战 - 图29%0AFILE%3D#card=math&code=option%20in%0Af%29%0AFILE%3D)OPTARG
[ ! -f shell-实战 - 图30FILE File not exist!” ; exit
;;
n)
sed -n “${OPTARG}p” $FILE
;;
?)
echo “Usage: $0 -f -n
echo “-f, —file specified file”
echo “-n, —line-number print specified line”
exit 1
;;
esac
done

bash test.sh -h

Usage: test.sh -f -n
-f, —file specified file
-n, —line-number print specified line

bash test.sh -f /etc/passwd -n 1

rootshell-实战 - 图310:0:root:/root:/bin/bash
思路扩展:限定脚本参数,将参数保存变量,下面调用变量继续操作

文字地图游戏


瓦雀