LoginSignup
21
19

More than 5 years have passed since last update.

SystemdでSSHのLocalForwardをサービス化

Last updated at Posted at 2016-05-16

systemdを使って、SSHのLocalFowardの接続をサービス化する。
再起動時の自動接続や、接続が切れた場合の再接続ができるようになる。

Unit設定ファイルの作成

/lib/systemd/system/forward-example.service
[Unit]
Description=Forward Example
After=network.target

[Service]
#User=ubuntu # ユーザ指定したい場合
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -i /path/to/identity -L 8080:localhost:80 user@host

RestartSec=3 # 3秒ごとに再接続
Restart=always

[Install]
WantedBy=multi-user.target

SSHコマンドのオプション

-N

コマンドを実行せず、ポートフォワードのためだけに接続する

-T

pseudo ttyを割り当てない

-o ServerAliveInterval=60

接続が切れることを回避するため、60秒に1回サーバにkeep-aliveを送る

-o ExitOnForwardFailure=yes

フォワードに失敗した場合にexitさせる。
これによりフォワードだけが失敗した場合でもsystemdが再起動してくれる。

Unitの読み込み

sudo systemctl daemon-reload 

サービスの有効化

再起動時に自動実行されるようになる。

sudo systemctl enable forward-example

サービス開始

sudo service forward-example start
21
19
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
21
19