【发布时间】:2017-10-16 20:40:03
【问题描述】:
我有一堆想要使用 Bash 脚本设置的虚拟机。我得到了一个包含所有虚拟机的所有 IP 地址的文本文件,并且还在每一行的前面写了“ssh VM-Name”,所以当我的脚本读取每一行时,它会通过 SSH 连接到每个虚拟机,然后在该虚拟机中执行我的命令.它以某种方式打破循环并在 SSH 进入第一个 VM 后停止。如何退出第一个虚拟机,以便它可以通过 SSH 连接到下一个?
#!/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
nodes.txt 的内容
ssh node1@IP
ssh node2@IP
ssh node3@IP
ssh node4@IP
它会通过 SSH 连接到第一个虚拟机,它会执行我指定的命令,但不会退出并循环到下一个,依此类推。
MyUsername$ ./setupnodes.sh
-------------------------------------------------------
Creating Users on: ssh node1@TheIPAdressofthatVM
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...
【问题讨论】:
-
你可以写一个expect脚本来做这个更简单unix.stackexchange.com/questions/288099/…
-
您可以使用
ssh -v ...打印更多日志以深入挖掘。 -
disconnecting... debug2: channel 0: obuf empty debug2: channel 0: close_write debug2: channel 0: output drain -> closed debug2: channel 0: almost dead debug2: channel 0: gc: notify user debug2: channel 0: gc: user detached debug2: channel 0: send close debug2: channel 0: is dead debug2: channel 0: garbage collecting debug1: channel 0: free: client-session, nchannels 1 debug1: fd 0 clearing O_NONBLOCK Transferred: sent 3940, received 3908 bytes, in 6.4 seconds Bytes per second: sent 611.1, received 606.1 debug1: Exit status 0 + exit -
尝试使用 eval 命令运行带有参数的 $sshlink。当命令在变量中时,它可能会解决问题。其他选项,如果没有帮助,请尝试使用 scp 将脚本复制到远程主机,并使用 ssh 运行脚本
标签: bash shell virtual-machine