在远程计算机上执行并发脚本,并等待该过程完成

时间:2016-05-12 17:25:06

标签: bash ssh remote-access

最初的想法是将脚本复制到每个IP地址,这将在每台计算机上安装一些RPM和一些配置步骤。由于yum-install大约需要20分钟,所以希望在每台机器上同时进行安装,然后在继续之前等待所有生成的进程完成。

#!/bin/bash

PEM=$1
IPS=$2

for IP in IPS; do
   scp    -i $PEM /tmp/A.sh ec2-user@IP:/tmp
   ssh    -i $PEM ec2-user@$IP chmod 777 /tmp/A.sh
done

for IP in IPS; do
   ssh -t -i $PEM ec2-user@$IP sudo /tmp/A.sh &
done

wait
echo "IPS have been configured."
exit 0

在后台对三个IP地址执行远程sudo执行命令会产生三条错误消息。显然,我的逻辑存在缺陷。

Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
sudo: sorry, you must have a tty to run sudo
sudo: sorry, you must have a tty to run sudo
sudo: sorry, you must have a tty to run sudo

所有机器都是CentOS 6.5

2 个答案:

答案 0 :(得分:1)

你需要告诉ssh不要从标准输入中读取

ssh -n -t root@host "sleep 100" &

这是一个例子

drao@darkstar:/tmp$ cat a
date
ssh -n -t me@host1 "sleep 100" & 
ssh -n -t me@host2 "sleep 100" & 
wait
date
darkstar:/tmp$ . ./a
Mon May 16 15:32:16 CEST 2016
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.

[1]-  Done                    ssh -n -t me@host1 "sleep 100"
[2]+  Done                    ssh -n -t me@host2 "sleep 100"
Mon May 16 15:33:57 CEST 2016
darkstar:/tmp

等待所有101秒。显然我有ssh键,所以我没有收到密码提示。

但是看看你的输出,看起来远程机器上的sudo失败了......你甚至可能不需要-n。

答案 1 :(得分:0)

只是为了推动一些苛刻的学说。

Ansible做得非常好。

相关问题