2017-10-16 81 views
1

我有一堆虚拟机,我想用Bash脚本安装。我得到了一个包含所有虚拟机的所有IP地址的文本文件,并且在每行的前面都写有“ssh VM-Name”,所以当我的脚本读取每一行时,它将通过SSH连接到每个虚拟机,然后在该虚拟机内执行我的命令。它以某种方式打破了循环,并在SSH进入第一台虚拟机后停止。我如何退出第一台虚拟机,以便它可以进入下一个虚拟机? nodes.txtBash脚本循环问题(SSH到虚拟机)

ssh [email protected] 
ssh [email protected] 
ssh [email protected] 
ssh [email protected] 

它确实SSH进入第一VM的

#!/bin/bash 
#set -x 

cat nodes.txt|while read sshlink 
do 
    echo ------------------------------------------------------- 
    echo Creating Users on: $sshlink 
    $sshlink 'echo connecting...; sleep 2; echo Creating...; sleep 1; sudo apt  
    install ntp; uname -a; sleep 1; sleep 2; echo disconnecting...; exit;' 
done 

内容,它将执行我指定的命令,但它不会退出,并循环到下一个等。

MyUsername$ ./setupnodes.sh 
------------------------------------------------------- 
Creating Users on: ssh [email protected] 
connecting... 
Creating... 

WARNING: apt does not have a stable CLI interface. Use with caution in scripts. 

Reading package lists... 
Building dependency tree... 
Reading state information... 
ntp is already the newest version (1:4.2.8p4+dfsg-3ubuntu5.6). 
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. 
Linux node-1 4.4.0-93-generiC#116-Ubuntu SMP Fri Aug 11 21:17:51 UTC 2017  
x86_64 x86_64 x86_64 GNU/Linux 
disconnecting... 
+0

你可以编写一个期望脚本来做到这一点更简单https://unix.stackexchange.com/questions/288099/how-to-write-expect-in-shell – MohitC

+0

你可以使用'ssh -v ...'打印更多日志以深入挖掘。 – georgexsh

+0

'断开... DEBUG2:通道0:空OBUF DEBUG2:通道0:close_write DEBUG2:通道0:输出漏极 - >关闭 DEBUG2:通道0:几乎死 DEBUG2:通道0:GC:通知用户 DEBUG2:通道0:GC:用户分离 DEBUG2:通道0:发送关闭 DEBUG2:通道0:是死 DEBUG2:通道0:垃圾收集 DEBUG1:通道0:自由:客户端会话,nchannels 1 DEBUG1 :fd 0清零O_NONBLOCK 传送:发送3940,接收到3908字节,在6.4秒内 字节每秒:发送611.1,收到606.1 debug1:退出状态0 + exit' – benice

回答

0

这里试试这个。我已经使用了类似的问题:

while read -r remote_host; 
do 
    ssh $remote_host bash -s <<"END" 
    echo "Do Something" 
    echo "Do something else" 
    ... 
    echo "Closing connection" 
END 
done<$1 

该脚本将接受新线分隔的主机列表,ssh来每一个执行的操作。每个命令都可以放在一个新行中。

该脚本使用heredoc符号。