LoginSignup
0
1

More than 5 years have passed since last update.

大量のRaspberry PiにSSH経由で任意のコマンドを実行する

Last updated at Posted at 2017-12-13

大量のRaspberry PiにSSH経由で任意のコマンドを実行する

LAN上に配置した大量のRaspberry Piに任意のコマンドを実行できるシェルスクリプトを組んだのでメモ.コレを使うと,大量の端末を一度にシャットダウンできて便利.
SSH経由なのでLinux端末なら大丈夫だと思いますが,Raspberry Pi(OS:Raspbian Jessie 8)でのみ動作確認しています.

スクリプト

#!/bin/sh

run_node_ssh() {
host=$1
id=$2
pass=$3

expect -c "
set timeout 10
spawn ssh ${id}@${host}   \"$4\"
expect \"Are you sure you want to continue connecting (yes/no)?\" {
    send \"yes\n\"
    expect \"${id}@${host}'s password:\"
    send \"${pass}\n\"
} \"${id}@${host}'s password:\" {
    send \"${pass}\n\"
}
interact
"
}

#コマンドライン引数の個数チェック
if [ $# -ne 1 ]; then
    echo "指定された引数は$#個です。" 1>&2
    echo "実行するには1個の引数が必要です。" 1>&2
    echo "Usage: ./run_command_node.sh \"COMMAND\"" 1>&2
    exit 1
fi

##### settings #####
run_node_ssh '192.168.1.AAA' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.BBB' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.CCC' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.DDD' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.EEE' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.FFF' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.GGG' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.HHH' 'user' 'pass' "${command}"
run_node_ssh '192.168.1.ZZZ' 'user' 'pass' "${command}"

使い方

設定

スクリプトの末尾にコマンドを実行したい端末のIPアドレスとユーザ名,パスワードを列挙します
末尾には"${command}"を付加します

run_node_ssh ['IPADDRESS'] ['USER'] ['PASS'] "${command}"

実行

実行時にはコマンドライン引数に実行したいコマンドを指定します

$ ./run_command_by_ssh.sh [COMMAND]

例:全ての端末をシャットダウンしたい時

$ ./run_command_by_ssh.sh "shutdown -h now"

複数のコマンドを実行したい時(セミコロン";"でつなぎます)

$ ./run_command_by_ssh.sh "cd /home/agri-mineno/; ./run_system.sh"
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1