1
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 1 year has passed since last update.

シェルスクリプトでSSH接続してユーザーを切り替えてコマンド実行する

Last updated at Posted at 2022-12-04

結論

以下のように、ssh接続してヒアドキュメントで実行したいコマンドを書いてやれば、
SSH接続してユーザーを切り替えてコマンド実行できます。

run.sh
ssh loginuser@target-server -tt << EEOOSS

sudo su - anotherloginuser << EOS
ls # ここに実行したいコマンドを書く
EOS

exit 0

EEOOSS

--ttオプションについて

-ttオプションをつけないと以下のようにコマンドが失敗します。

$ sh run.sh
Pseudo-terminal will not be allocated because stdin is not a terminal.
sudo: 残念ですが、sudo を実行するには tty が必要です
1
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
1
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?