踩坑记录:shell脚本循环调度ssh,仅循环一次

一个简单的脚本,将需要的文件传出到远程机器上,再调度脚本远程执行,达到批量配置机器的目的

#!/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"

循环正常执行

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值