(转)30个关于Shell脚本的经典案例
https://www.cnblogs.com/linuxprobe/p/11518761.html
30个关于Shell脚本的经典案例(上)
| 对于初学者而言,因为没有实战经验,写不出来Shell脚本很正常,如果工作了几年的运维老年还是写不出来,那就是没主动找需求,缺乏练习,缺乏经验。针对以上问题,总结了30个生产环境中经典的Shell脚本,通过这些需求案例,希望能帮助大家提升Shell编写思路,掌握编写技巧。 |
先了解下编写Shell过程中注意事项:
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">开头加解释器:#!/bin/bash
语法缩进,使用四个空格;多加注释说明。
命名建议规则:变量名大写、局部变量小写,函数名小写,名字体现出实际作用。
默认变量是全局的,在函数中变量local指定为局部变量,避免污染其他作用域。
有两个命令能帮助我调试脚本:set -e 遇到执行非0时退出脚本,set-x 打印执行过程。
写脚本一定先测试再到生产上。
</pre>
1、获取随机字符串或数字
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">获取随机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效验和统计字节
</pre>
2、定义一个颜色输出字符串函数
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">方法1:
function echo_color() {
if [ 2\033[0m"
elif [ 2\033[0m"
fi
}
方法2:
function echo_color() {
case 2[0m"
;;
red)
echo -e "[31;40m$2[0m"
;;
*)
echo "Example: echo_color red string"
esac
}
使用方法:echo_color green "test"
function关键字定义一个函数,可加或不加。
</pre>
3、批量创建用户
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">#!/bin/bash
DATE=1 == "green" ]; then
echo -e "[32;40m1 == "red" ]; then
echo -e "[31;40m$2[0m"
fi
}
如果用户文件存在并且大小大于0就备份
if [ -s USER_FILE {DATE}.bak
echo_color green "{USER_FILE}-USER_FILE
echo "----------------" >> USER &>/dev/null; then
PASS=RANDOM |md5sum |cut -c 1-8)
useradd PASS |passwd --stdin USER USER_FILE
echo "USER User already exists!"
fi
done
</pre>
4、检查软件包是否安装
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed."
else
echo "sysstat is not installed!"
fi
</pre>
5、检查服务状态
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">#!/bin/bash
PORT_C=(ps -ef |grep ntpd |grep -vc grep)
if [ PS_C -eq 0 ]; then
echo "内容" | mail -s "主题" dst@example.com
fi
</pre>
6、检查主机存活状态
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">方法1:将错误IP放到数组里面判断是否ping失败三次
!/bin/bash
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in NUM -le 3 ]; do
if ping -c 1 IP Ping is successful."
break
else
# echo "NUM"
FAIL_COUNT[IP
let NUM++
fi
done
if [ {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 >/dev/null; then
echo "IP Ping is failure 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 Ping is successful."
continue
fi
}
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in IP Ping is failure!"
done
</pre>
7、监控CPU、内存和硬盘利用率
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">1)CPU
借助vmstat工具来分析CPU统计信息。
!/bin/bash
DATE=(ifconfig eth0 |awk -F [ :]+ /inet addr/{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print ((SY))
if [ DATE
Host: USE
" | mail -s "CPU Monitor" $MAIL
fi
2)内存
!/bin/bash
DATE=(ifconfig eth0 |awk -F [ :]+ /inet addr/{print (free -m |awk /Mem/{print (free -m |awk /Mem/{print 6-((USE))
内存小于1G发送报警邮件
if [ DATE
Host: TOTAL,Use=FREE
" | mail -s "Memory Monitor" $MAIL
fi
3)硬盘
!/bin/bash
DATE=(ifconfig eth0 |awk -F [ :]+ /inet addr/{print (fdisk -l |awk -F [: ]+ BEGIN{OFS="="}/^Disk /dev/{printf "%s=%sG,",3} )
PART_USE=1,int(6} )
for i in (echo (echo (echo USE -gt 80 ]; then
echo "
Date: IP
Total: PART=MOUNT)
" | mail -s "Disk Monitor" $MAIL
fi
done
</pre>
8、批量主机磁盘利用率监控
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">前提监控端和被监控端SSH免交互登录或者密钥登录。
写一个配置文件保存被监控主机SSH连接信息,文件内容格式:IP User Port
!/bin/bash
HOST_INFO=host.info
for IP in 1} (awk -v ip=1{print HOST_INFO)
PORT=IP ip==3} PORT IP df -h > (awk BEGIN{OFS="="}/^/dev/{print 5)} USE_RATE_LIST; do
PART_NAME={USE_RATE#*=}
if [ PART_NAME Partition usage $USE_RATE%!"
fi
done
done
</pre>
9、检查网站可用性
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">1)检查URL可用性
方法1:
check_url() {
HTTP_CODE=1)
if [ 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=1)
if [ URL_LIST; do
check_url URL
check_url URL Access failure!"
done
方法2:错误次数保存到变量
!/bin/bash
URL_LIST="www.baidu.com www.agasgf.com"
for URL in (curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" HTTP_CODE -ne 200 ]; then
let FAIL_COUNT++
else
break
fi
done
if [ URL Access failure!"
fi
done
方法3:错误次数保存到数组
!/bin/bash
URL_LIST="www.baidu.com www.agasgf.com"
for URL in NUM -le 3 ]; do
HTTP_CODE=URL)
if [ NUM]=NUM下标,{#FAIL_COUNT[]} -eq 3 ]; then
echo "Warning: $URL Access failure!"
unset FAIL_COUNT[] #清空数组
fi
done
</pre>
10、检查MySQL主从同步状态
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word;">#!/bin/bash
USER=bak
PASSWD=123456
IO_SQL_STATUS=USER -p0} ) #gsub去除冒号后面的空格
for i in {i%:*}
THREAD_STATUS=THREAD_STATUS" != "Yes" ]; then
echo "Error: MySQL Master-Slave THREAD_STATUS!"
fi
done
</pre>
动手练一练,让你的Shell功底上升一个段位!
本文目录
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">11、iptables自动屏蔽访问网站频繁的IP
12、判断用户输入的是否为IP地址
13、判断用户输入的是否为数字
14、给定目录找出包含关键字的文件
15、监控目录,将新创建的文件名追加到日志中
16、给用户提供多个网卡选择
17、查看网卡实时流量
18、MySQL数据库备份
19、Nginx服务管理脚本
20、用户根据菜单选择要连接的Linux主机
</pre>
11、iptables自动屏蔽访问网站频繁的IP
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">场景:恶意访问,安全防范
1)屏蔽每分钟访问超过200的IP
方法1:根据访问日志(Nginx为例)
!/bin/bash
DATE=(tail -n5000 access.log |grep 1]++}END{for(i in a)if(a[i]>100)print i}')
先tail防止文件过大,读取慢,数字可调整每分钟最大的访问量。awk不能直接过滤日志,因为包含特殊字符。
for IP in (iptables -vnL |grep -c "IP -j DROP
fi
done
方法2:通过TCP建立的连接
!/bin/bash
ABNORMAL_IP=4~/:806~/ESTABLISHED/{gsub(/:[0-9]+/,"",5]++}}END{for(i in a)if(a[i]>100)print i}')
gsub是将第五列(客户端IP)的冒号和端口去掉
for IP in (iptables -vnL |grep -c "IP -j DROP
fi
done
2)屏蔽每分钟SSH尝试登录超过10次的IP
方法1:通过lastb获取登录状态:
!/bin/bash
DATE=(lastb |grep "3]++}END{for(i in a)if(a[i]>10)print i}')
for IP in (iptables -vnL |grep -c "IP -j DROP
fi
done
方法2:通过日志获取登录状态
!/bin/bash
DATE=(tail -n10000 /var/log/auth.log |grep "(NF-3)]++}END{for(i in a)if(a[i]>5)print i}')"
for IP in (iptables -vnL |grep -c "IP -j DROP
echo "IP -j DROP" >>~/ssh-login-limit.log
fi
done
</pre>
12、判断用户输入的是否为IP地址
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">方法1:
!/bin/bash
function check_ip(){
IP=(echo 1< =255&&3<=255&&IP|grep -E "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}VALID_CHECK == "yes" ]; then
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=IP =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}(echo (echo (echo (echo FIELD1 -le 255 -a FIELD3 -le 255 -a 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=(echo 1< =255&&3<=255&&IP|grep -E "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}VALID_CHECK == "yes" ]; then
return 0
else
echo "IP
[ $? -eq 0 ] && break || continue
done
</pre>
13、判断用户输入的是否为数字
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">方法1:
!/bin/bash
if [[ ]]; 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 0~/^[0-9]+1
KEY=(find KEY FILE"
fi
done
</pre>
14、给定目录找出包含关键字的文件
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
DIR=2
for FILE in DIR -type f); do
if grep FILE &>/dev/null; then
echo "--> $FILE"
fi
done
</pre>
15、监控目录,将新创建的文件名追加到日志中
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">场景:记录目录下文件操作。
需先安装inotify-tools软件包。
!/bin/bash
MON_DIR=/opt
inotifywait -mq --format %f -e create files >> test.log
done
</pre>
16、给用户提供多个网卡选择
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">场景:服务器多个网卡时,获取指定网卡,例如网卡流量
!/bin/bash
function local_nic() {
local NUM ARRAY_LENGTH
NUM=0
for NIC_NAME in (ifconfig 4}')
if [ -n "NUM]="NIC_IP" #将网卡名和对应IP放到数组
let NUM++
fi
done
ARRAY_LENGTH=ARRAY_LENGTH -eq 1 ]; then #如果数组里面只有一条记录说明就一个网卡
NIC=ARRAY_LENGTH -eq 0 ]; then #如果没有记录说明没有网卡
echo "No available network card!"
exit 1
else
#如果有多条记录则提醒输入选择
for NIC in NIC
done
while true; do
read -p "Please enter local use to network card name: " INPUT_NIC_NAME
COUNT=0
for NIC in {NIC%:}
if [ INPUT_NIC_NAME" ]; then
NIC=COUNT]%:}
return 0
else
COUNT+=1
fi
done
echo "Not match! Please input again."
done
fi
}
local_nic
</pre>
17、查看网卡实时流量
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">适用于CentOS6操作系统。
!/bin/bash
Description: Only CentOS6
traffic_unit_conv() {
local traffic=traffic -gt 1024000 ]; then
printf "%.1f%s" "traffic/1024/1024))" "MB/s"
elif [ ((1
echo -e " In ------ Out"
while true; do
OLD_IN=0~"'3}' /proc/net/dev)
OLD_OUT=0~"'11}' /proc/net/dev)
sleep 1
NEW_IN=0~"'3}' /proc/net/dev)
NEW_OUT=0~"'11}' /proc/net/dev)
IN=NEW_IN-((OLD_OUT))
echo "IN) OUT)"
sleep 1
done
使用:./traffic.sh eth0
</pre>
18、MySQL数据库备份
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
DATE={DB}full{DB}fullBACKUP_DIR
if mysqldump -hUSER -pDB > BAK_FILE SQL_FILE
if [ ! -s DATE 内容" | mail -s "主题" DATE 内容" | mail -s "主题" BACKUP_DIR -name '*.zip' -ctime +14 -exec rm {} ;
</pre>
19、Nginx服务管理脚本
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">场景:使用源码包安装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/conf/nginx.conf
NAME=nginx
PID=0~/pid;/)print CONF)
if [ -z "WORD_DIR/logs/nginx.pid
else
PID=PID
fi
stop() {
PID ] && action "* Stopping NAME" /bin/false
}
start() {
PID ] && action "* Starting NAME" /bin/false
}
reload() {
DAEMON -t
}
case "PID ]; then
start
else
echo "PID ]; then
stop
else
echo "PID ]; then
echo "PID ] && echo "NAME not running!"
;;
*)
echo "Usage: $0 {start|stop|restart|reload|testconfig|status}"
exit 3
;;
esac</pre>
https://article.pchome.net/content-2100027.html
http://www.51cto.com/it/news/2019/0909/14338.html
https://www.linuxprobe.com/books
20、用户根据菜单选择要连接的Linux主机
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Linux主机SSH连接信息:
cat host.txt
Web 192.168.1.10 root 22
DB 192.168.1.11 root 22
内容格式:主机名 IP User Port
!/bin/bash
PS3="Please input number: "
HOST_FILE=host.txt
while true; do
select NAME in 1}' {NAME:=empty} == "quit" ] && exit 0
IP={NAME} '2}' (awk -v NAME=1==NAME{print HOST_FILE)
PORT={NAME} '4}' IP ]; then
echo "Name: IP"
ssh -o StrictHostKeyChecking=no -p USER@$IP # 密钥免交互登录
break
else
echo "Input error, Please enter again!"
break
fi
done
done</pre>
本文目录
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">21、从FTP服务器下载文件
22、连续输入5个100以内的数字,统计和、最小和最大
23、将结果分别赋值给变量
24、批量修改文件名
25、统计当前目录中以.html结尾的文件总大
26、扫描主机端口状态
27、Expect实现SSH免交互执行命令
28、批量修改服务器用户密码
29、打印乘法口诀
30、getopts工具完善脚本命令行参数
</pre>
21、从FTP服务器下载文件
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
if [ 0 filename"
fi
dir=1)
file=1)
ftp -n -v << EOF # -n 自动登录
open 192.168.1.10 # ftp服务器
user admin password
binary # 设置ftp传输模式为二进制,避免MD5值不同或.tar.gz压缩包格式错误
cd file"
EOF
</pre>
22、连续输入5个100以内的数字,统计和、最小和最大
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
COUNT=1
SUM=0
MIN=0
MAX=100
while [ INT =~ ^[0-9]+INT -gt 100 ]]; then
echo "输入必须是100以内!"
exit 1
fi
SUM=SUM+MIN -lt INT
[ INT ] && MAX=SUM"
echo "MIN: MAX"
</pre>
23、将结果分别赋值给变量
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">应用场景:希望将执行结果或者位置参数赋值给变量,以便后续使用。
方法1:
for i in i=a4 a6
方法2:将位置参数192.168.1.1{1,2}拆分为到每个变量
num=0
for i in *);do #eval将{1,2}分解为1 2
let num+=1
eval nodei"
done
echo node2 $node3
bash a.sh 192.168.1.1{1,2}
192.168.1.11 192.168.1.12
方法3:
arr=(4 5 6)
INDEX1={arr[0]})
INDEX2={arr[1]})
INDEX3={arr[2]})
</pre>
24、批量修改文件名
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">示例:
touch article_{1..3}.html
ls
article_1.html article_2.html article_3.html
目的:把article改为bbs
方法1:
for file in file bbs_file file |sed -r 's/.(_.)/bbs\1/')
# mv (echo (cut -d_ -f2)
done
方法2:
for file in file bbs_${file#*_}
done
方法3:
rename article bbs *.html
</pre>
25、统计当前目录中以.html结尾的文件总大
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">方法1:
find . -name "*.html" -exec du -k {} ; |awk '{sum+=$1}END{print sum}'
方法2:
for size in 5}'); do
sum=sum+sum
</pre>
26、扫描主机端口状态
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
HOST=PORT; do
if echo &>/dev/null > /dev/tcp/PORT; then
echo "PORT close"
fi
done
</pre>
27、Expect实现SSH免交互执行命令
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Expect是一个自动交互式应用程序的工具,如telnet,ftp,passwd等。
需先安装expect软件包。
方法1:EOF标准输出作为expect标准输入
!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect << EOF
set timeout 30
spawn ssh IP
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "USER@" {send "USER@" {send "exit\r"}
expect eof
EOF
方法2:
!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect -c "
spawn ssh IP
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "USER@*" {send "df -h\r exit\r"; exp_continue}
}"
方法3:将expect脚本独立出来
登录脚本:
cat login.exp
!/usr/bin/expect
set ip [lindex argv 1]
set passwd [lindex argv 3]
if { user@passwd\r"}
}
expect "cmd\r"}
expect "$user@*" {send "exit\r"}
expect eof
执行命令脚本:写个循环可以批量操作多台服务器
!/bin/bash
HOST_INFO=user_info.txt
for ip in 1}' (awk -v I="1{print HOST_INFO)
pass=ip" 'I==3}' ip pass $1
done
Linux主机SSH连接信息:
cat user_info.txt
192.168.1.120 root 123456
</pre>
28、批量修改服务器用户密码
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Linux主机SSH连接信息:旧密码
cat old_pass.txt
192.168.18.217 root 123456 22
192.168.18.218 root 123456 22
内容格式:IP User Password Port
SSH远程修改密码脚本:新密码随机生成
https://www.linuxprobe.com/books
!/bin/bash
OLD_INFO=old_pass.txt
NEW_INFO=new_pass.txt
for IP in 1}' (awk -v I=1{print OLD_INFO)
PASS=IP 'I==3}' (awk -v I=1{print OLD_INFO)
NEW_PASS=IP NEW_PASS NEW_INFO
expect -c "
spawn ssh -pUSER@PASS\r";exp_continue}
"NEW_PASS' |passwd --stdin $USER\r exit\r";exp_continue}
}"
done
生成新密码文件:
cat new_pass.txt
192.168.18.217 root n8wX3mU% 22
192.168.18.218 root c87;ZnnL 22
</pre>
29、打印乘法口诀
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">方法1:
awk 'BEGIN{for(n=0;n++<9;){for(i=0;i++<n;)printf i"x"n"="i*n" ";print ""}}'
方法2:
for ((i=1;i<=9;i++)); do
for ((j=1;j<=i;j++)); do
result=ijresult "
done
echo
done
</pre>
30、getopts工具完善脚本命令行参数
<pre style="margin: 0px; padding: 0px; white-space: pre-wrap; overflow-wrap: break-word; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">getopts是一个解析脚本选项参数的工具。
命令格式:getopts optstring name [arg]
初次使用你要注意这几点:
脚本位置参数会与optstring中的单个字母逐个匹配,如果匹配到就赋值给name,否则赋值name为问号;
optstring中单个字母是一个选项,如果字母后面加冒号,表示该选项后面带参数,参数值并会赋值给OPTARG变量;
optstring中第一个是冒号,表示屏蔽系统错误(test.sh: illegal option -- h);
允许把选项放一起,例如-ab
下面写一个打印文件指定行的简单例子,引导你思路:
!/bin/bash
while getopts :f:n: option; do
case OPTARG
[ ! -f FILE File not exist!" && exit
;;
n)
sed -n "FILE
;;
?)
echo "Usage: $0 -f -n "
echo "-f, --file specified file"
echo "-n, --line-number print specified line"
exit 1
;;
esac
done
</pre>
根据工作经验总结的30个Shell脚本案例至此完结,都还是比较实用的,面试笔试题也经常会出。希望朋友们多动手练一练,让你的Shell功底上升一个段位!