首页 > 系统服务 > 详细

Shell 编程中,在循环里使用ssh免密远程执行命令的注意事项

时间:2018-05-30 23:13:44      阅读:364      评论:0      收藏:0      [点我收藏+]

前提:给自己机器配置ssh免密登录
#!/bin/bash
cat << ‘EOD‘ > list
1
2
3
4
EOD

while read line
do
if ssh myname@127.0.0.1 "test -f /tmp/a.sh"; then #配置了免密登录,此处不用输入密码
echo "$line file exist."
else
echo "$line file not exist."
fi
done < list

问题:按理,list文件里有4行,这个while循环应该会执行4次才对,为何这个只执行了一次呢?

答案如下:

检查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 pro-
             gram 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读取本地的标准输入内容。

#要想使本脚本执行次数正常,ssh命令需要添加-n选项即可。

https://blog.csdn.net/notsea/article/details/42028359

Shell 编程中,在循环里使用ssh免密远程执行命令的注意事项

原文:https://www.cnblogs.com/Reggie/p/9114147.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!