当主体包含 ssh 时,Bash while 循环仅迭代一次
我正在从文本文件中读取主机信息并将其传递给 ssh 命令: 该文本文件包含 ssh 命令的主机、用户和密码
while read LINE
do
R_USER=$(echo $LINE | cut -d ',' -f 1)
R_HOST=$(echo $LINE | cut -d ',' -f 2)
PY_SCRIPT=$(echo $LINE | cut -d ',' -f 4)
ssh $R_USER@$R_HOST 'touch /home/user/file_name.txt'
done </path_name/file_name
,事实证明,即使主机文本文件包含多个主机信息,while 循环也只执行一次。 当我删除 ssh 命令时, while 循环的执行次数与主机信息文本文件中的行数一样多。
不知道为什么会这样。 有这方面的信息吗?
罗兰
I'm reading host information from a text file and pass it to an ssh command:
The text file contains the host, user and password for the ssh command
while read LINE
do
R_USER=$(echo $LINE | cut -d ',' -f 1)
R_HOST=$(echo $LINE | cut -d ',' -f 2)
PY_SCRIPT=$(echo $LINE | cut -d ',' -f 4)
ssh $R_USER@$R_HOST 'touch /home/user/file_name.txt'
done </path_name/file_name
As it turns out the while loop is only executed once even if the host text file contains multiple host information.
When I remove the ssh command the while loop gets executed as much as there are lines in the host information text file.
Not sure why this is so.
Any information on this?
Roland
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ssh 的默认标准输入处理会耗尽 while 循环中的剩余行。
要避免此问题,请更改有问题的命令读取标准输入的位置。如果不需要将标准输入传递给命令,请从特殊的
/dev/null
设备读取标准输入:或者,尝试使用
ssh -n
这将阻止 ssh从标准输入读取。例如:The default standard input handling of ssh drains the remaining line from the while loop.
To avoid this problem, alter where the problematic command reads standard input from. If no standard input need be passed to the command, read standard input from the special
/dev/null
device:Or alternatively, try using
ssh -n
which will prevent ssh from reading from standard input. For instance:如果文件以空格分隔,
则进行简单的读取循环:
但系统会提示您输入密码。您无法将“密码”传递给 ssh,因此我建议存储无密码 ssh 密钥并将它们放置在您连接的用户的每个主机上。如果您从脚本运行此命令,您可以通过将您的公钥放入用户的
~/.ssh/authorized_keys<中以每个主机上的这些用户身份进行ssh /code> (或authorized_keys2)文件。如果您有
ssh-copy-id
命令,您可以通过以下方式执行此操作:它将您的 ssh-key复制到他们的authorized_keys文件,以便您然后就可以像他们一样 ssh 了。这是假设您有权限,但您又拥有他们的密码,那么您需要什么权限?
If the file is white space separated
then a simple read loop:
But you will be prompted for the password. You cannot pass the "Password" to ssh so I'd suggest storing passwordless ssh-keys and placing them on each host for the user you are connecting as. If you are running this command from a script you can ssh as these users on each host by placing your public key in the user's
~/.ssh/authorized_keys
(or authorized_keys2) file. If you have thessh-copy-id
command you could do this by:which would copy YOUR ssh-key to their authorized_keys file so you could then ssh as them. This is assuming you have permission but then again you have their password so what permission do you need?