shell那点事儿——运维工程师必会shell脚本

本文详细介绍了Shell脚本在运维中的应用,包括信号控制、参数判断、正则表达式、文件创建、循环操作、交互式自动化、SSH免密、用户管理、函数运用、数组操作和批量主机管理等,展示了Shell脚本在日常运维工作中的强大功能和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一、脚本案例

1、信号控制
#!/bin/bash
trap "func" 2
func() {
read -p "Terminate the process? (Y/N): " input
if [ $input == "Y" ]; then
        exit
fi
}
for i in {1..10}
do
        echo $i
        sleep 1
done
2、判断脚本参数
#!/bin/bash
#判断脚本是否有参数
if [ $# -eq 0 ];then
        echo "Input `basename $0` file"         #basename去除脚本路径
        exit 1
fi

if [ ! -f $1 ];then
        echo "ERROR:$1 is not a file"
        exit 2
fi

for ip in `cat $1`
do
        ping -c1 $ip >/dev/null 2>&1
        if [ $? -eq 0 ];then
                echo "$ip is up!"
        else
                echo "$ip is down!"
        fi
done
3、-z 判断 及 正则表达式
#!/bin/bash
read -p "Input your username :" username
# "-z"表示0长度 后面变量必须加双引号
if [ -z "$username" ];then
        echo "ERROR!"
        exit 1
fi

read -p "Input number :" num
while true
do
        #判断是否是数字 "=~"正则匹配     "^[0-9]+$"正则表达式 表示数字 要用"[[ ]]"
        if [[ $num =~ ^[0-9]+$ ]];then
                break
        else
                read -p "Input your username again :" num
        fi
done

#seq一个数字序列 例如seq 1 10
for i in `seq $num`
do
        user=$username$i
        useradd $user
        echo "1" |passwd --stdin $user >/dev/null 2>&1
        if [ $? -eq 0 ];then
                echo "$user created !"
        fi
done
4、脚本中EOF创用建文件
覆盖
cat > EOF.txt <<-EOF
1.test1
2.test2
3.test3
4.test4
5.test5
EOF


追加
cat >> EOF.txt <<-EOF
1.test1
2.test2
3.test3
4.test4
5.test5
EOF

5、for 循环,printf 打印九九乘法表
#!/bin/bash

for ((i=1;i<=9;i++))
do
        for ((j=1;j<=i;j++))
        do
                printf "%d * %d = %d\t" $i $j $[j*i]
        done
echo
done
6、expect实现交互式自动化
#!/bin/expect
#位置变量传参
set user [lindex $argv 0]
set ip 192.168.93.133
set password woainixx
spawn ssh $user@$ip

expect {
        "yes/no" { send "yes\r"; exp_continue }
        "password:" { send "$password\r" }
}
expect "#"
send "pwd\r"
send "exit\r"
expect eof
7、expect与EOF实现批量ssh免密
#!/bin/bash
>ip.txt
pass=xx

if [ ! -f ~/.ssh/id_rsa ];then
        #无交互模式创建密钥
        ssh-keygen -P "" -f ~/.ssh/id_rsa
fi

for i in {100..200}
do
        {
        ip=192.168.93.$i
        ping -c1 -W1 $ip >/dev/null 2>&1
        if [ $? -eq 0 ];then
                echo "$ip" >>ip.txt
                expect <<-EOF 
                set timeout 10
                spawn ssh-copy-id $ip
                expect {
                        "yes/no" { send "yes\r";exp_continue }
                        "password:" { send "$pass\r" }
                }
                expect eof
                EOF
        fi
        }&  #后台并发执行,增加执行速度
done
#wait和后台符一起使用
wait
echo "finish..."
8、批量创建用户
#!/bin/bash
while read line
do
        if [ ${#line} -eq 0 ];then
                continue
        fi
        user=`echo $line |awk '{print $1}'`
        pass=`echo $line |awk '{print $2}'`
        id $user >/dev/null 2>&1
        if [ $? -eq 0 ];then
                echo "user $user is exists."
        else
                useradd $user
                echo "$pass" |passwd --stdin $user && |history -c >/dev/null 2>&1
                if [ $? -eq 0 ];then
                        echo "user $user is created"
                fi
        fi
done <$1
9、函数的位置变量
#!/bin/bash
factorial() {
        factorial=1
        #$1为函数的位置变量
        for ((i=1;i<=$1;i++))
        do
                let factorial=$factorial*$i
        done
        echo "$1的阶乘是:$factorial"
}
#$1为脚本的位置变量  脚本的$1传到函数的$1
factorial $1
factorial $2
factorial $3

./factorial.sh 5 10 15
5的阶乘是:120
10的阶乘是:3628800
15的阶乘是:1307674368000
10、函数的两种传参方式
#!/bin/bash
if [ $# -ne 3 ];then
        echo "usage: `basename $0` par1 par2 par3"
        exit
fi
fun2(){
        echo "$[$1*$2*$3]"
}

#两种传参方式
方式1:
num1=$1
num2=$2
num3=$3
result=`fun2 $num1 $num2 $num3`
echo "result is $result"


方式2:
result=`fun2 $1 $2 $3`
echo "result is $result"

11、函数传参数组
#!/bin/bash
num=(1 2 3 4 5)

array() {
        factorial=1
        for i in $*
        do
                let factorial=$factorial*$i
        done
        echo "$factorial"
}

array ${num[*]}
12、while循环实现累加求和
#!/bin/bash
while true
do
        read -p "plz input a number:" num
        if [[ ! $num =~ ^[0-9]+$ ]];then
                echo "重新输入"
        else
                break
        fi
done

for ((i=1;i<=$num;i++))
do
        let sum=$sum+$i
done
echo "1-${num}的累加和: $sum"
13、利用数组统计ip出现次数
#!/bin/sh
a=(`cat ip.txt`)
#定义数组
declare -A b
for i in ${a[*]}
do
        let b[$i]++
done

#打印数组b
declare -p b

for z in ${!b[*]}
do
        echo "${z}:${b[$z]}"
done
14、批量登录主机获取信息
#!/bin/sh
while read line
do
        ip=`echo "${line}" |awk '{print $1}'`
        pass=`echo "${line}" |awk '{print $2}'`
        newpass=`echo \${pass} |sed s"/'//g"`
        echo ${ip}
        echo ${newpass}
        sshpass -p "${newpass}" ssh -o StrictHostKeyChecking=no ${ip}  "cat /etc/redhat-release" </dev/null
        echo ""
done<$1
15、脚本练习:kvm_manager
#!/bin/sh

iso=/var/lib/libvirt/images/muban.img
configure_file=/etc/libvirt/qemu/muban.xml
location1=/var/lib/libvirt/images
location2=/etc/libvirt/qemu

echo -e "\e[1;31m
1.创建默认配置虚拟机
2.创建自定义虚拟机
3.管理虚拟机
4.虚拟机快照
5.退出
\e[0m"

read -p "PLS input your choice: " choice

case $choice in
1)

	read -p "请输入你想创建的虚拟机个数: " count
	i=0
	while [ $i -lt $count ]
	do
		kvmname=`openssl rand -hex 5`
		kvmuuid=`uuidgen`
		kvmmac=`openssl rand -hex 3 | sed -r 's/..\B/&:/g'`
		echo "请稍候..."
        echo "正在复制......"
		cp $iso $location1/${kvmname}.img
        cp $configure_file $location2/${kvmname}.xml
		echo "复制已完成"
		sed -ri "s#muban#$kvmname#g" $location2/${kvmname}.xml
		sed -ri "s#kvmuuid#$kvmuuid#" $location2/${kvmname}.xml
		sed -ri "s#kvmmem#1536000#" $location2/${kvmname}.xml
		sed -ri "s#kvmcpu#1#" $location2/${kvmname}.xml
		sed -ri "s#09:2e:17#$kvmmac#" $location2/${kvmname}.xml
		virsh define $location2/${kvmname}.xml &> /dev/null
		let i++
	done
		sleep 2
		virsh list --all
		echo "$count Virt-machine is created"
	exit
	;;
2)
	read -p "请输入你想要的虚拟机的名字: " name
	read -p "请输入该虚拟机的cpu个数: " count
	read -p "请输入该虚拟的内存: " mem

    uuid=`uuidgen`
	mac=`openssl rand -hex 3 | sed -r 's/..\B/&:/g'`
 	echo "请稍后..."
	echo "正在复制......"
	cp $iso $location1/${name}.img
        cp $configure_file $location2/${name}.xml
	echo "复制已完成"
	sed -ri "s#muban#$name#g" $location2/${name}.xml
	sed -ri "s#kvmmem#$mem#g" $location2/${name}.xml
	sed -ri "s#kvmcpu#$count#g" $location2/${name}.xml
	sed -ri "s#kvmuuid#$uuid#" $location2/${name}.xml
        sed -ri "s#kvmmac#$mac#" $location2/${name}.xml
	virsh define $location2/${name}.xml
	sleep 3
	virsh list --all
	echo "该虚拟机已创建成功."
	;;
3)
	echo -e "\e[1;40m 即将输出你可以操作的虚拟机列表: \e[0m"
	sleep 3
	virsh list --all
	read -p "请输入你所想要管理的虚拟机: " name

	echo -e "\e[1;31m
	1、开启虚拟机
	2、关闭虚拟机
	3、重启虚拟机
	4、删除虚拟机
	5、退出
	\e[0m"

	read -p "输入你的操作: " option
	case $option in
	1)
		virsh start $name
		;;
	2)
		virsh shutdown $name
		;;
	3)
		virsh reboot $name
		;;
	4)
		virsh shutdown $name >/dev/null 2>&1
		sleep 10
		a=`virsh snapshot-list virt-two |awk '{print $1}'|awk '!/^N/{print}'|awk '!/^-/{print}'`
		if [ ${#a} -gt 0 ];then
			read -p "此虚拟机有快照是否确认删除快照 [y] " p
			if [ "${p}" = "y" ];then
			 	virsh snapshot-delete --snapshotname $a $name
			 	sleep 3
                         	virsh undefine $name
				rm -rf $location1/${name}.img
                         	echo "$name 删除成功"
                	else
                        	exit
                	fi
		fi
		;;
	5)
		exit
		;;
	esac
	;;
4)

	echo -e "\e[1;40m 即将输出你可以操作的虚拟机列表: \e[0m"
	sleep 3
	virsh list --all
	read -p "请输入你所要操作的虚拟机: " name

	echo -e "\e[1;31m
	1.创建快照
	2.删除快照
	3.恢复快照
	4.退出
	\e[0m"
	read -p "请输入你对该虚拟机进行的快照操作: " choice
	case $choice in
	1)

		echo -e "\e[1;40m 即将输出你可以操作的虚拟机快照列表: \e[0m"
		sleep 3
	 	virsh snapshot-list $name
		echo "即将创建快照,请注意快照名字不可以一样."
		virsh snapshot-create-as $name ${name}.snap
		;;
	2)

		virsh snapshot-list $name
		virsh snapshot-delete --snapshotname ${name}.snap $name;;
	3)
		virsh snapshot-list $name
		virsh snapshot-revert $name ${name}.snap;;
	4)
		exit;;
	esac

	;;
5)
	exit
	;;
esac
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

偷学技术的梁胖胖yo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值