zl程序教程

您现在的位置是:首页 >  系统

当前栏目

Linux shell脚本使用while循环执行ssh的注意事项

Linuxssh循环执行shell 使用 脚本 注意事项
2023-06-13 09:15:43 时间

如果要使用ssh批量登录到其它系统上操作时,我们会采用循环的方式去处理,那么这里存在一个巨大坑,你必须要小心了。

一、场景还原:

我现在是想用一个脚本获取一定列表服务器的运行时间,首先我建立一个名字为ip.txt的IP列表(一个IP一行),再建好密钥实现不用密码直接登录。然后写脚本如下:

[code language= shell ]#!/bin/bash
while read ips;
do
echo ips;
doneips;
upt=`ssh root@ips uptime
echoupt;
done ip.txt[/code]

脚本只对第一个IP做了检测,就直接跳出来了。

二、问题分析:

while使用重定向机制,ip.txt文件中的信息都已经读入并重定向给了整个while语句,所以当我们在while循环中再一次调用read语句,就会读取到下一条记录。问题就出在这里,ssh语句正好回读取输入中的所有东西。为了禁止ssh读所有东西增加一个 /dev/null,将ssh 的输入重定向输入。

三、解决策略:

1、使用for循环代表while,因为for没有一次把文件内容缓存获取过来,代码段修改如下:

[code language= shell ]for ips in `cat ip.txt`; do
echo {ips};
upt=`ssh root@{ips} uptime`;
echo upt;
done[/code]

2、若坚持使用while循环,那么需要对ssh增加-n参数,为什么增加了-n参数也可以解决问题呢?通过man ssh查看-n参数的说明:
Redirects stdin from /dev/null (actually, prevents reading from stdin)
这就和

修改后的代码如下:

[code language= shell ]#!/bin/bash
while read ips;
do
echoips;
upt=`ssh -n root@ips uptime
echoupt;
done ip.txt[/code]

本文链接:http://www.yunweipai.com/4339.html

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/53224.html

javashell