服务器批量执行工具 PSSH

操作一台服务器的时候可以 ssh,操作多台服务器可以开多个窗口多个 ssh,那操作很多台服务器呢?

我们的一个 Oracle Gird Engine 集群上大概有60多台 Ubuntu 服务器作执行节点,这些服务器操作系统和软件配置完全一样(上线后由 puppet 统一配置),有时候我们需要在这些服务器上做同样的操作,这个时候特别适合使用 PSSH 这种 ssh 批量操作工具。

当然,如果对 Python 不恐惧的话也可以用 Fabric 批量执行服务器任务。

下载和安装 pssh:

$ git clone http://code.google.com/p/parallel-ssh/
$ cd parallel-ssh/
$ sudo python setup.py install

批量执行

首先新建一个服务器列表文件,把需要操作的服务器的 hostname(或者 IP 地址)加进去,然后就可以批量执行 uptime 命令了,-l 指定登录用户名,-A 询问密码,-h 指定服务器列表文件:

$ vi grids
grid01
grid02
grid03
grid04
grid05

$ pssh -i -l root -A -h grids 'uptime'
Warning: do not enter your password if anyone else has superuser
privileges or access to your account.
Password:
[1] 05:42:09 [SUCCESS] grid01
11:42:09 up 620 days, 20:30, 0 users, load average: 6.09, 6.14, 6.13
[2] 05:42:09 [SUCCESS] grid03
11:42:09 up 620 days, 20:29, 0 users, load average: 9.01, 9.04, 9.05
[3] 05:42:09 [SUCCESS] grid05
11:42:09 up 620 days, 20:10, 0 users, load average: 8.46, 8.18, 8.10
[4] 05:42:09 [SUCCESS] grid04
11:42:09 up 620 days, 20:25, 0 users, load average: 6.00, 6.01, 6.05
[5] 05:42:10 [SUCCESS] grid02
11:42:10 up 606 days, 2:07, 0 users, load average: 6.03, 6.02, 6.01

批量上传

批量上传本地文件 linux-3.14.3.tar.xz 到服务器上的 /tmp 目录:

$ pscp -l root -A -h grids linux-3.14.3.tar.xz /tmp/
Warning: do not enter your password if anyone else has superuser
privileges or access to your account.
Password:
[1] 05:56:16 [SUCCESS] grid01
[2] 05:56:16 [SUCCESS] grid03
[3] 05:57:04 [SUCCESS] grid05
[4] 05:57:04 [SUCCESS] grid04
[5] 05:57:05 [SUCCESS] grid02

批量下载

批量下载服务器上的某文件到本地,不用担心重名问题,因为 pssh 已经建立了 grid01, grid02, …, grid05 目录来存放下载的文件:

$ pslurp -l root -h grids -A /tmp/linux-3.14.3.tar.xz .
Warning: do not enter your password if anyone else has superuser
privileges or access to your account.
Password:
[1] 06:06:01 [SUCCESS] grid01
[2] 06:06:01 [SUCCESS] grid03
[3] 06:06:06 [SUCCESS] grid04
[4] 06:06:06 [SUCCESS] grid02
[5] 06:06:06 [SUCCESS] grid05

$ ls
grid01 grid02 grid03 grid04 grid05 grids linux-3.14.3.tar.xz parallel-ssh

批量同步

有时候我们需要保持开发机上(某目录里)的数据和服务器上的数据一致:

$ prsync -l root -h grids -A -r develop/ /tmp/production/
Warning: do not enter your password if anyone else has superuser
privileges or access to your account.
Password:
[1] 06:12:52 [SUCCESS] grid05
[2] 06:12:52 [SUCCESS] grid01
[3] 06:12:52 [SUCCESS] grid04
[4] 06:12:52 [SUCCESS] grid02
[5] 06:12:52 [SUCCESS] grid03