opensource(2)mpssh批量执行

mpssh(Mass Parallel SSH)是一个并行 SSH 工具,方便同时对多台服务器执行命令。它对批量管理服务器非常实用,尤其适用于运维场景。

GitHub 仓库
https://github.com/ndenev/mpssh

代码特点

  • 使用 C 编写,性能轻量。
  • 支持 SSH 密钥验证。
  • 输出日志支持自定义路径。

1.安装方法

1.1从源码安装(推荐)

1
2
3
4
git clone https://github.com/ndenev/mpssh.git
cd mpssh
make
sudo make install

依赖:需要系统上安装 sshmake,一般默认都有。

1.2Debian/Ubuntu(可能存在)

1
sudo apt install mpssh

注意:某些发行版仓库可能未包含该工具,建议使用源码安装。

1.3Mac

    brew install mpssh

2.基本语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
➜  joplin-blog git:(main) mpssh -h

Usage: mpssh [-u username] [-p numprocs] [-f hostlist]
[-e] [-b] [-o /some/dir] [-s] [-v] <command>

-b, --blind enable blind mode (no remote output) ### 不输出执行详细结果
-d, --delay delay between each ssh fork (default 10 msec)
-e, --exit print the remote command return code
-E, --no-err suppress stderr output
-f, --file=FILE file with the list of hosts or - for stdin ### ssh host file
-h, --help this screen
-l, --label=LABEL connect only to hosts under label LABEL
-o, --outdir=DIR save the remote output in this directory
-O, --no-out suppress stdout output
-p, --procs=NPROC number of parallel ssh processes (default 100)
-q, --quiet run ssh with -q
-r, --script copy local script to remote host and execute it ### 执行脚本
-s, --nokeychk disable ssh strict host key check
-t, --conntmout ssh connect timeout (default 30 sec)
-u, --user=USER ssh login as this username ### 指定登录用户
-v, --verbose be more verbose (i.e. show usernames used)
-V, --version show program version

3.使用示例

3.1 创建主机列表

1
2
3
4
5
cat > hosts.txt <<EOF
192.168.215.2
192.168.215.3
192.168.215.4
EOF

3.2基本使用

批量检查服务器的磁盘使用情况:

1
mpssh -u dev -f hosts.txt  "df -h"

3.3查看内核版本

➜  /tmp mpssh -u dev  -f hosts.txt  "uname -r"
MPSSH - Mass Parallel Ssh Ver.1.3.3
(c)2005-2013 Nikolay Denev <[email protected]>

  [*] read (3) hosts from the list
  [*] executing "uname -r" as user "dev"
  [*] spawning 3 parallel ssh sessions

192.168.215.2 -> 6.13.7-orbstack-00283-g9d1400e7e9c6
192.168.215.3 -> 6.13.7-orbstack-00283-g9d1400e7e9c6
192.168.215.4 -> 6.13.7-orbstack-00283-g9d1400e7e9c6

  Done. 3 hosts processed.