在多台主机上执行一个命令,但如果成功只打印命令?

Ste*_*ski 4 ssh remote-management shell-script

这就是我想要做的。

我想检查 100 多个主机并查看该主机上是否存在文件。如果文件确实存在,那么我想打印主机名和命令的输出。

在这个示例中,假设我有三个主机: host1.example.org host2.example.org host3.example.org 。该文件/etc/foobar存在于 host2.example.org 上,但不存在于 host1.example.org 或 host3.example.org 上。

  1. 我想ls -l /etc/foobar在列表中的每个主机上运行。
  2. 如果该文件存在于该主机上,则打印主机名和命令的输出。
  3. 如果该文件在该主机上不存在,则不要打印任何内容。我不想要额外的噪音。
HOSTLIST="host1.example.org host2.example.org host3.example.org"
for HOST in $HOSTLIST
do
    echo "### $HOST"
    ssh $HOST "ls -ld /etc/foobar"
done
Run Code Online (Sandbox Code Playgroud)

理想的输出是:

### host2.example.org
drwx------ 3 root root 4096 Apr 10 16:57 /etc/foobar
Run Code Online (Sandbox Code Playgroud)

但实际输出是:

### host1.example.org
### host2.example.org
drwx------ 3 root root 4096 Apr 10 16:57 /etc/foobar
### host3.example.org
Run Code Online (Sandbox Code Playgroud)

我不想打印 host1.example.org 或 host3.example.org 的行。

我正在试验大括号来包含由echoand吐出的输出ssh,但我无法弄清楚做我想做的魔术语法。我确信我过去在没有控制字符的情况下这样做过,

### host2.example.org
drwx------ 3 root root 4096 Apr 10 16:57 /etc/foobar
Run Code Online (Sandbox Code Playgroud)

小智 5

在这个问题中,我建议使用pssh。Thx pssh 你可以很容易地一次在许多远程服务器上运行命令。

将主机放入(即 hosts_file)- 1 行中的每个服务器,例如:
host1.tld
host2.tld

用法:

pssh -h hosts_file "COMMAND"
Run Code Online (Sandbox Code Playgroud)

在你的例子中,它将是

pssh -h hosts_file "ls -l /etc/foobar"
Run Code Online (Sandbox Code Playgroud)