0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ssh ログインをして、リモート先で sudo コマンドを一斉に行う方法

Last updated at Posted at 2021-03-06

ssh ログインをして、リモート先で sudo コマンドを一斉に行う方法です。

sshpass だけ必要になりますので先にインストールを行います

sudo apt install -y sshpass ;

シェルファイルの作成

gedit login_and_cmd.sh;

以下のコードを保存します。

login_and_cmd.sh
# !/bin/bash

# 環境変数の指定。ユーザー名とIPアドレスの指定
LOGIN_USER_NAME=myloginname
IP_ADDRESS_ARR=(
  "192.168.0.xxx"
  "192.168.0.xxx"
  "192.168.0.xxx"
)

# コマンド実行にパスワードを格納する
echo -n "Type your password: "
read -s SSHPASS

# IPアドレスの分だけfor文を回す
for IP_ADDRESS in ${IP_ADDRESS_ARR[@]}
do

  # 実際のコマンド
  sshpass -p $SSHPASS ssh $LOGIN_USER_NAME@$IP_ADDRESS -tt << EOL

    echo "${SSHPASS}" | sudo -S hostname
    echo "${SSHPASS}" | sudo -S apt update
    echo "${SSHPASS}" | sudo -S apt upgrade -y
    echo "${SSHPASS}" | sudo -S apt autoremove -y

    exit
EOL

done

実行

bash login_and_cmd.sh ;

ちょっとターミナルにパスワードが表示されるのでアレですが、もしかしたらもっとうまく隠せるかもしれません。

参考リンク

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?