今天生产要批量连接服务器并执行命令:把所有的IP写到一个iplist文件,然后用while read 和for进行遍历拼接ssh命令发现两个问题:ssh连接参数-n 和while read与for读取的区别
脚本
iplist
192.168.4.12
192.168.4.13
192.168.4.14
tongjidf.sh
#!/bin/bash
cmd="df -m | grep app"
while read line
do
ssh [email protected]${line} $cmd
done <./iplist
执行的结果发现只连接了一个地址192.168.4.12、后面的地址没有执行
然后改成了for
#!/bin/bash
cmd="df -m|grep app"
for ips in `cat iplist`
do
ssh [email protected]${line} $cmd
done
这个脚本就可以实现连接以上所有地址然后进行命令执行。
终于找到了一个说法:就是for是一行一行的读取,而while read line是一次读取放入内存
第二个就是ssh默认读取本地的内容,而-n参数阻止了,而是从/dev/null/读取,这样一来ssh如果用while read line的形式就是连接一个
-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