一个简单的脚本,将需要的文件传出到远程机器上,再调度脚本远程执行,达到批量配置机器的目的
#!/bin/bash
dir=$(pwd)
example=$1
cat file.txt | while read ip2
do
echo $ip2
ssh-keygen -f "/root/.ssh/known_hosts" -R $ip2
sshpass -f password scp -o StrictHostKeyChecking=no ${dir}/config.sh ubuntu@$ip2:/home/ubuntu/
sshpass -f password scp -o StrictHostKeyChecking=no ${dir}/meIp.txt ubuntu@$ip2:/home/ubuntu/
sshpass -f password ssh -o StrictHostKeyChecking=no ubuntu@$ip2 "sudo bash /home/ubuntu/config.sh $example"
done
但是执行脚本之后,发现循环只走了一次就退出了。
注释掉最后一行ssh命令,前面的scp命令都按照预期走完循环,那么问题只能出在ssh上了。
问题在这里:
-n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)
可以说这个选项是专门用来解决这个问题的。用/dev/null来当ssh的输入,阻止ssh读取本地的标准输入内容。
将上述脚本修改为
sshpass -f password ssh -o StrictHostKeyChecking=no ubuntu@$ip2 -n "sudo bash /home/ubuntu/config.sh $example"
循环正常执行