如何在多台服务器上运行相同命令

利用工具 pssh (Parallel SSH)

  • 安装 pssh (Mac 版): 使用 Homebrew,直接执行命令 brew install pssh。(Reference)
  • 使用 pssh (Reference)
    • 创建 hosts 文件 (例如叫 pssh-hosts 的文件,包括每台服务器的 IP, 内容如下)

      117.50.16.49:22

      117.50.16.89:22

      117.50.13.202:22

      117.50.14.188:22

      117.50.16.72:22 
      117.50.16.117:22 

    • 执行单条命令 (例如要在每台服务器上执行命令 uptime,在 Mac 上的终端执行以下命令即可) 
      pssh -h pssh-hosts -l root -O StrictHostKeyChecking=no -A -i uptime

      其中 -l root 代表登录的用户名是 root,-A 会要求输入一次密码。这就要求所有服务器的 用户名 & 密码 必须是相同的。

    • 执行 shell script (例如要在每台服务器上执行 test.sh 脚本文件,在 Mac 上的终端执行以下命令即可)

      pssh -h pssh-hosts -l root -O StrictHostKeyChecking=no -A -I -i -x "-T" < ./test.sh

    • 完整的 pssh 命令参数说明
➜  ~ pssh --help
Usage: pssh [OPTIONS] command [...]

Options:
  --version             show program's version number and exit
  --help                show this help message and exit
  -h HOST_FILE, --hosts=HOST_FILE
                        hosts file (each line "[user@]host[:port]")
  -H HOST_STRING, --host=HOST_STRING
                        additional host entries ("[user@]host[:port]")
  -l USER, --user=USER  username (OPTIONAL)
  -p PAR, --par=PAR     max number of parallel threads (OPTIONAL)
  -o OUTDIR, --outdir=OUTDIR
                        output directory for stdout files (OPTIONAL)
  -e ERRDIR, --errdir=ERRDIR
                        output directory for stderr files (OPTIONAL)
  -t TIMEOUT, --timeout=TIMEOUT
                        timeout (secs) (0 = no timeout) per host (OPTIONAL)
  -O OPTION, --option=OPTION
                        SSH option (OPTIONAL)
  -v, --verbose         turn on warning and diagnostic messages (OPTIONAL)
  -A, --askpass         Ask for a password (OPTIONAL)
  -x ARGS, --extra-args=ARGS
                        Extra command-line arguments, with processing for
                        spaces, quotes, and backslashes
  -X ARG, --extra-arg=ARG
                        Extra command-line argument
  -i, --inline          inline aggregated output and error for each server
  --inline-stdout       inline standard output for each server
  -I, --send-input      read from standard input and send as input to ssh
  -P, --print           print output as we get it

Example: pssh -h hosts.txt -l irb2 -o /tmp/foo uptime
原文地址:https://www.cnblogs.com/wanghzh/p/8631491.html