第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > linux脚本跳出循环语句 跳出循环的命令

linux脚本跳出循环语句 跳出循环的命令

时间:2019-07-02 00:22:40

相关推荐

linux脚本跳出循环语句 跳出循环的命令

1. exit #退出循环,同时也会退出脚本

[root@shell /scripts/shell-day31]# cat exit.sh

#!/bin/bash

for i in {1..3}

do

echo "123"

exit

echo "456"

done

echo "脚本执行结束"

[root@shell /scripts/shell-day31]# sh exit.sh

123

2. break#跳出当前循环,继续执行循环以外的命令

[root@shell /scripts/shell-day31]# cat break.sh

#!/bin/bash

for i in {1..3}

do

echo "123"

break

echo "456"

done

echo "脚本执行结束"

[root@shell /scripts/shell-day31]# sh break.sh

123

脚本执行结束

3. continue#跳出本次循环,不继续执行循环的剩余代码。继续执行下一次的循环。

[root@shell /scripts/shell-day31]# cat continue.sh

#!/bin/bash

for i in {1..3}

do

echo "123"

continue

echo "456"

done

echo "脚本执行结束"

[root@shell /scripts/shell-day31]# sh continue.sh

123

123

123

脚本执行结束

4. 先扫描10.0.0.0/24网段内的主机,存活的主机则下发公钥。

1. 先判断是否存在密钥,没有则进行创建密钥对,有则跳过

2. 批量探测主机是否存活,存活则判断远程端口是否开放

3. 主机存活且端口开放的主机则分发公钥

4. 判断是否发送成功

如何免交互式的进行创建密钥对

-f filename #指定私钥文件保存的路径

-N new_passphrase #指定一个新的密码

ssh-keygen -t rsa -f /root/.ssh/id_rsa -N ""

如何免交互式的分发公钥

-o StrictHostKeyChecking=no #忽略回复yes的交互(避免第一次交互出现 公钥检查)

sshpass -p123456 #指定密码为123456,忽略交互

yum install -y sshpass

sshpass -p1 ssh-copy-id -i /root/.ssh/id_rsa.pub -o "StrictHostKeyChecking=no" root@10.0.0.7

[root@shell /scripts/shell-day31]# cat fenfa.sh

#!/bin/bash

#1.引用函数库

[ -f /etc/init.d/functions ] && source /etc/init.d/functions || echo "函数库文件不存在!"

#2.判断是否存在秘钥对

if [ -f /root/.ssh/id_rsa.pub ] && [ -f /root/.ssh/id_rsa ];then

action "密钥对文件存在!" /bin/true

else

rm -rf /root/.ssh &>/dev/null

ssh-keygen -t rsa -f /root/.ssh/id_rsa -N "" &>/dev/null

if [ $? -eq 0 ];then

action "已经创建新的密钥对!" /bin/true

else

action "新的密钥对创建失败!" /bin/false

exit

fi

fi

#3.批量探测主机是否存活

Ip_log=/tmp/ip.log

>$Ip_log

i=1

while [ $i -le 254 ]

do

{

IP=10.0.0.$i

ping -c1 -W1 $IP &>/dev/null

if [ $? -eq 0 ];then

action "${IP}主机是存活的..........." /bin/true

echo "$IP" >>$Ip_log

fi

}&

let i++

sleep 0.1

done

wait

while read line

do

State=$(nmap -p22 $line | awk '/^22/{print $2}')

if [ $State == "open" ];then

action "主机地址${line}远程端口是开放的........" /bin/true

sshpass -p1 ssh-copy-id -p22 -i /root/.ssh/id_rsa.pub -o "StrictHostKeyChecking=no" root@$line &>/dev/null

if [ $? -eq 0 ];then

action "主机地址${line}公钥发送成功........" /bin/true

else

action "主机地址${line}公钥发送失败........" /bin/false

fi

else

action "主机地址${line}远程端口是关闭的........" /bin/false

fi

done < $Ip_log

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。