while循环中碰到ssh的话,如何避免退出

简介:
先看一个例子:
#!/bin/sh
. /root/.bash_profile
cat /home/yejr/alldb|while read LINE
do
   #取得IP和组号
   IP=`echo $LINE | awk '{print $1}'`
   NU=`echo $LINE | awk '{print $2}' | awk -F '-' '{print $1}'`
   cnt=`ssh root@$IP "mysql -e 'select count(*) from yejr.tbl1'|tail -n 1"`
   echo "$IP $NU $cnt"
done
看起来没有问题吧,实际上,执行的时候只循环了一次,就退出while循环了,为什么呢?
这是因为ssh需要从输入终端来读取数据,在第一次循环时ssh就把 read 读到的数据也给读取了,相当于是被他"吃"了.
解决办法是,指定 ssh 的输入终端,有3种方法:
ssh -f
-f Requests ssh to go to background just before command execution.  This is useful if ssh is going to ask for
   passwords or passphrases, but the user wants it in the background.  This implies -n.  The recommended way to
   start X11 programs at a remote site is with something like ssh -f host xterm.
或者:
ssh -n
-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 automati-
   cally 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.)
或者,将ssh放到后台中执行. 以下是几种写法的综合:
 

cnt=`ssh root@$IP "mysql -e 'select count(*) from yejr.tbl1'|tail -n 1"



本文转自叶金荣51CTO博客,原文链接:http://blog.51cto.com/imysql/308604,如需转载请自行联系原作者

相关文章
|
7月前
|
安全 网络安全
配置SSH服务远程连接空闲超时退出时间(包括SSH无法登录、登录缓慢)
配置SSH服务远程连接空闲超时退出时间(包括SSH无法登录、登录缓慢)
|
12月前
|
安全 网络安全
配置SSH服务远程连接空闲超时退出时间
配置SSH服务远程连接空闲超时退出时间
|
网络安全 Shell
如何避免远程循环执行SSH时,到第一条之后就退出
RT 今天遇到的小问题,记录下来。 据说关键是加  < /dev/null 我也是看网上别人说的,测试成功。 #!/bin/bash while read line do echo $line ssh -l wls81 $line "cp -r /appsystems/ /appsystems.
1044 0
|
29天前
|
安全 Linux Shell
Linux SSH(Secure Shell)服务
Linux SSH提供安全网络协议,使用公钥加密技术确保远程服务传输安全。OpenSSH是实现SSH服务的免费开源工具,允许用户加密连接远程登录Linux服务器执行任务。SSH比Telnet更安全,防止数据被截获。SSH还支持端口转发和隧道,广泛应用于系统管理和网络维护,是安全远程访问服务器的重要工具。
25 1
|
2月前
|
安全 Shell Linux
【Shell 命令集合 文件管理】Linux ssh 远程主机之间复制文件 scp 命令使用教程
【Shell 命令集合 文件管理】Linux ssh 远程主机之间复制文件 scp 命令使用教程
43 0
|
15天前
|
Linux 网络安全 数据安全/隐私保护
SSH工具连接远程服务器或者本地Linux系统
SSH工具连接远程服务器或者本地Linux系统
18 0
|
2天前
|
存储 安全 Linux