栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

踩坑记录: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}/configSu31.sh  ubuntu@$ip2:/home/ubuntu/
        sshpass -f password scp -o StrictHostKeyChecking=no ${dir}/meIp.txt ubuntu@$ip2:/home/ubuntu/
        sshpass -f password scp -o StrictHostKeyChecking=no ${dir}/bn-ptn-communication.properties 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"

循环正常执行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号