起動時にSSHコマンドを実行するには?

起動時にSSHコマンドを実行するには?

sshコマンドを入力してみましたが、/etc/rc.local動作しません。

/etc/rc.local:

#!/bin/bash
ssh -fN -R 8080:localhost:80 -i /home/pi/.ssh/id_rsa [email protected] >> /tmp/ssh-nginx.out 2>>/tmp/ssh-nginx.err

/tmp/ssh-nginx.err:

pi@raspberrypi:~ $ cat /tmp/ssh-nginx.err 
ssh: connect to host 50.0.0.1 port 22: Network is unreachable

crontab(line is ) に同じコマンドを追加すると、@reboot /etc/init.d/ssh-nginx同じ出力が生成されます。

これを行う正しい方法は何ですか?

ベストアンサー1

効果的な解決策があります。どんな意見でも大変感謝いたします。

このようなSSHスクリプトを作成します。/usr/local/bin/autossh-tunnel

#!/bin/bash
ssh -N -R 11001:localhost:80 -o ServerAliveInterval=30 -i /home/pi/.ssh/id_rsa [email protected]
# not necessary, but you may want to use autossh instead: /usr/bin/autossh -M 0 -q -N -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 11001:localhost:80 -i /home/pi/.ssh/id_rsa [email protected]

そしてサービスファイル/etc/systemd/system/autossh-tunnel.service

[Unit]
Description=AutoSSH tunnel
After=network.target

[Service]
ExecStart=/usr/local/bin/autossh-tunnel
# Remove restarts if the command is just a one-off
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target

sudo systemctl enable autossh-tunnel.service起動時に起動するには実行してください。 (今すぐ始めてくださいsudo systemctl start autossh-tunnel.service

また、SSHトンネルの代わりにVPNを使用することも検討してください。

おすすめ記事