使用 xargs ssh 到多个主机,接收到:名称或服务未知
Using xargs to ssh to multiple hosts, receiving :Name or service not known
我正在编写一个 shell 脚本,它将通过 ssh 连接到多个主机,并对它们执行一些操作。
我的脚本 test.sh,如下所示:
cat < | xargs -e -d ' ' -I % ssh % grep "example" /opt/example/test.log
我运行它通过下面的命令
./test.sh prod_hosts.txt
和prod_hosts.txt的内容:
hostname1 hostname2 hostname3 hostname4
我已确认此文件末尾没有 carraige return,但我收到以下错误:
[ryan@hostname1 ~]$ ./test.sh prod_hosts.txt
ssh: hostname4
: Name or service not known
xargs: ssh: exited with status 255; aborting
看起来它成功地通过 ssh 连接到 4 台主机,但是它尝试通过 ssh 连接时有一个空白条目,因此出现错误。
知道我在这里遗漏了什么吗?好像我遗漏了一些明显的东西!
echo '1 2' | xargs -d ' ' -I % echo %
产生:
1
2
<blank line>
而 echo -n '1 2' | xargs -d ' ' -I % echo %
returns:
1
2
即xargs
如果输入字符串以换行符结束,则决定再生成一个输出条目。
解决方法:
- 在 hosts.txt 和
<hosts.txt xargs -I % <ssh-command>
中使用换行符分隔的条目
- 如果hosts.txt无法更改:
< <(tr ' ' '\n' < hosts.txt) xargs -I % <ssh-command>
我正在编写一个 shell 脚本,它将通过 ssh 连接到多个主机,并对它们执行一些操作。
我的脚本 test.sh,如下所示:
cat < | xargs -e -d ' ' -I % ssh % grep "example" /opt/example/test.log
我运行它通过下面的命令
./test.sh prod_hosts.txt
和prod_hosts.txt的内容:
hostname1 hostname2 hostname3 hostname4
我已确认此文件末尾没有 carraige return,但我收到以下错误:
[ryan@hostname1 ~]$ ./test.sh prod_hosts.txt
ssh: hostname4
: Name or service not known
xargs: ssh: exited with status 255; aborting
看起来它成功地通过 ssh 连接到 4 台主机,但是它尝试通过 ssh 连接时有一个空白条目,因此出现错误。
知道我在这里遗漏了什么吗?好像我遗漏了一些明显的东西!
echo '1 2' | xargs -d ' ' -I % echo %
产生:
1
2
<blank line>
而 echo -n '1 2' | xargs -d ' ' -I % echo %
returns:
1
2
即xargs
如果输入字符串以换行符结束,则决定再生成一个输出条目。
解决方法:
- 在 hosts.txt 和
<hosts.txt xargs -I % <ssh-command>
中使用换行符分隔的条目
- 如果hosts.txt无法更改:
< <(tr ' ' '\n' < hosts.txt) xargs -I % <ssh-command>