複数のホストでコマンドを実行しますが、成功した場合にのみコマンドを印刷しますか?

複数のホストでコマンドを実行しますが、成功した場合にのみコマンドを印刷しますか?

私がやりたいことはこれです。

100 台以上のホストをチェックして、そのホストにファイルが存在するかどうかを確認したいと思います。ファイルが存在する場合は、ホスト名とコマンドの出力を印刷します。

この例では、 host1.example.org、 host2.example.org、 host3.example.org の 3 つのホストがあると仮定します。ファイルは/etc/foobarhost2.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

理想的な出力は次のようになります。

### host2.example.org
drwx------ 3 root root 4096 Apr 10 16:57 /etc/foobar

しかし、実際の出力は次のようになります。

### host1.example.org
### host2.example.org
drwx------ 3 root root 4096 Apr 10 16:57 /etc/foobar
### host3.example.org

host1.example.org または host3.example.org の行を印刷したくありません。

echo私は、およびによって吐き出された出力を中括弧で囲む実験をしていますsshが、私が望むことを行うための魔法の構文がわかりません。私は過去にこれを制御文字なしで行ったことがあると確信しています。

HOSTLIST="host1.example.org host2.example.org host3.example.org"
for HOST in $HOSTLIST
do
    # If 'ls' shows nothing, don't print $HOST or output of command
    # This doesn't work
    { echo "### $HOST" && ssh $HOST "ls -ld /etc/foobar" ; } 2>/dev/null
done

答え1

この号では使用をお勧めしますプシュ. pssh さん、ありがとうございます。一度に複数のリモート サーバーでコマンドを簡単に実行できます。

ホストを(つまりhosts_fileに)入力します - 各サーバーを1行で入力します(例:
host1.tld
host2.tld)

使用法:

pssh -h hosts_file "COMMAND"

あなたの例ではそれは

pssh -h hosts_file "ls -l /etc/foobar"

答え2

これは私にとってはうまくいきました:

for HOST in $HOSTLIST; do
  ssh $HOST '[ -f /etc/passwd ] && echo $(hostname) has file'
done

答え3

set -- host1.example.org host2.example.org
for host; do
        ssh "$host" sh -c '[ -e /etc/foobar ] && { printf %s\\n "$1"; ls -ld /etc/foobar; }' _ "$host"
done

答え4

for host in host1 host2 host3 ;do ssh $host 'echo -n "[$(hostname -s)]"; /sbin/ifconfig |grep Bcast' ;done

[host1] inet addr:xxx.xxx.138.30 Bcast:xxx.xxx.143.255 Mask:255.255.248.0 [host2] inet addr:xxx.xxx.138.14 Bcast:xxx.xxx.143.255 Mask:255.255.248.0 [host3] inet addr:xxx.xxx.82.146 Bcast:xxx.xxx.82.255 Mask:255.255.255.128

関連情報