在多個主機上執行命令,但如果成功則只列印命令?

在多個主機上執行命令,但如果成功則只列印命令?

這就是我想做的事。

我想檢查 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

理想的輸出是:

### 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我正在嘗試用大括號來包含and吐出的輸出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

相關內容