
以前、TeratermマクロやPerlスクリプトで、指定したホストに連続してログインし、コマンドを実行させるプログラムについて記述したが、今回は各ホストに対し「同時に」SSH接続してコマンドを実行させるプログラム『Parallel SSH』について記述する。
1.インストール
まずはインストールをしないと始まらない。
各OSごとのインストール方法について、以下に記述する。
Debian/Ubuntu
bashapt-get install pssh
RHEL系
bashyum install pssh
Windows
こちらのリンクからzipファイルをダウンロードし、解凍したファイルの中にある「nssh.exe」を用いる。
2.コマンド実行
まずは、以下にUbuntuで実行した際のヘルプを記載する。
shellroot@Test-Ubuntu001:~# parallel-ssh --help Usage: parallel-ssh [OPTIONS] command [...] Options: --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 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 root@Test-Ubuntu001:~#
なお、Ubuntuの場合コマンドは「parallel-ssh」だが、CentOSの場合は「pssh」となっていたので、OSのディストリビューション別に実行コマンド名が違うようだ。
それでは、実際にコマンドを実行していこう。「parallel-ssh」を用いる際は、IPアドレスを記述した外部ファイルが必要となる。
ここでは、「hostip.list」というファイルを作成し、これを用いるものとする。
以下の例では、「hostip.list」に記述されたホスト名に対し、touchコマンドで「test」ファイルを作成し、lsコマンドでその存在有無を確認している。
shellroot@Test-Ubuntu001:~# parallel-ssh -l root -h hostip.list -A touch test Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 02:55:05 [SUCCESS] 192.168.0.240 [2] 02:55:06 [SUCCESS] 192.168.0.33 [3] 02:55:06 [SUCCESS] 192.168.0.41 root@Test-Ubuntu001:~# parallel-ssh -l root -h hostip.list -A -i ls -la test Warning: do not enter your password if anyone else has superuser privileges or access to your account. Password: [1] 02:56:10 [SUCCESS] 192.168.0.41 -rw-r--r-- 1 root root 0 Jul 20 02:55 test [2] 02:56:10 [SUCCESS] 192.168.0.33 -rw-r--r-- 1 root root 0 Jul 20 02:55 test [3] 02:56:10 [SUCCESS] 192.168.0.240 -rw-r--r-- 1 root root 0 Jul 20 11:55 test root@Test-Ubuntu001:~#
ここで実行している各オプションについて解説する。
- -l…sshでログインするユーザ名を指定する。「-l ユーザ名」
- -h…ホスト名(IPアドレス)を記述したファイルを指定する。「-h ホスト名を記述したファイル」
- -A…ログインするユーザのパスワードを入力出来る。なお、全てのホストが同じパスワードである必要がある。
- -i…各ホストにコマンド実行結果を表示させる。
全ホストで使用するユーザ名とパスワードが同じである必要はあるが、これは便利だ。