2
2

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 5 years have passed since last update.

【SSH】whileとの併用

Last updated at Posted at 2020-01-31

何をしたいか

複数台あるサーバーにsshで入って処理するようなスクリプトを書きたい!
サーバーのip自体はlstファイルから呼び出せるようにして管理しやすいようにしたい!
そこでこういうスクリプトを作成しました。

server_ip.lst
192.168.10.1

そしてシェルはこういう感じで実装。

ssh.sh
listfile=server_ip.lst
while read ip
do
	ssh test@ip ~~~
done < ${listfile}

よしよし出来た。
あとはserver_ip.lstに対象ipアドレス増やしておーわり。
設定...実行...
...
...
1サーバーしか出来ない...

何が起きたか

sshを使用すると、標準入力がsshによるリモートからのものに切り替わり、
ローカルのファイルが閉じられるようです。(2020/01/31にコメントを頂いて修正)
標準入力がsshにリダイレクトされることで、
sshがローカルのファイルを標準入力で読み取りきってしまうそうです。

なので1行目しか読み込まれずループが終了するという仕組みのようです。
同じようなトラップに引っかかった方が多いようですね

どうすればよいか

sshに対して標準入力からの読み込みを禁止にするとよい。
これにはオプションがあって「-n」をつけると良いそうです。

(正常なやつ)ssh.sh
listfile=server_ip.lst
while read ip
do
	ssh -n test@ip ~~~
done < ${listfile}

これは勉強になりました。

2
2
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?