在我的 bash 循环中一些服务器的列表中,如果 ssh 连接 bash 脚本退出 [英] in my bash loop over a list of some servers, if the ssh connects the bash script exits

查看:8
本文介绍了在我的 bash 循环中一些服务器的列表中,如果 ssh 连接 bash 脚本退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个快速脚本可以使用 ssh 在每个服务器上运行命令(我确信有很多更好的方法可以做到这一点,但它的目的是为了快速工作!!).对于 test1 等,没有服务器,所以脚本会继续,如果公钥认证失败,脚本也会继续.但是,如果脚本连接,则打印日期但 ssh 循环终止...

I have a quick script to run a command on each server using ssh (i am sure there are lots of better ways to do this, but it was intended to just work quick!!). For the test1 etc, there is no server so the script continues, the script also continues if the pubkey auth fails. However if the script connects, the date is printed but the ssh loop terminates...

#!/bin/bash -x

cat <<EOF |
##file servers
test1
test2
server1
server2
EOF
while read line
do
if [ "${line:0:1}" != "#"  ]; then

ssh -q -oPasswordAuthentication=no -i id_dsa user1@${line} date

fi
done

echo read line must have exited

输出就是这样;

+ cat
+ read line
+ '[' t '!=' '#' ']'
+ ssh -q -oPasswordAuthentication=no -i id_dsa user1@test1 date
+ read line
+ '[' t '!=' '#' ']'
+ ssh -q -oPasswordAuthentication=no -i id_dsa user1@test2 date
+ read line1
+ '[' s '!=' '#' ']'
+ ssh -q -oPasswordAuthentication=no -i id_dsa user1@server1 date
Fri Jul  9 09:04:16 PDT 2010
+ read line
+ echo read line must have exited
read line must have exited`enter code here`

与成功返回 ssh 命令有关的事情是弄乱了循环或 var 的条件......关于为什么的任何建议?

something to do with the successful return of the ssh command is messing with the condition for the loop or the var... any suggestions on why?

推荐答案

您应该将 -n 标志传递给 ssh,以防止它与 stdin 混淆:

You should pass the -n flag to ssh, to prevent it messing with stdin:

ssh -n -q -oPasswordAuthentication=no -i id_dsa user1@${line} date

我用自己的服务器对此进行了测试并重现了该问题,添加 -n 即可解决该问题.正如 ssh 手册页所说:

I tested this with my own server and reproduced the problem, adding -n solves it. As the ssh man page says:

从/dev/null 重定向标准输入(实际上,防止从标准输入)

Redirects stdin from /dev/null (actually, prevents reading from stdin)

在您的示例中,ssh 必须从 stdin 读取,这会在循环中弄乱您的读取.

In your example, ssh must have read from stdin, which messes up your read in the loop.

这篇关于在我的 bash 循环中一些服务器的列表中,如果 ssh 连接 bash 脚本退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆