Yesterday I went back home, hoping I can work remotely on my laptop which is set at the lab.
But because of my laptop got rebooted, its IP address changed (It connects to wifi, IP address always change).
I have one desktop set in the lab and have a wired connection. So its IP address is mostly fixed.
I want my laptop to connect to my desktop and establishes a reverse tunnel. So later I can ssh to my desktop and forward to my laptop.
First, a reverse ssh tunnel.
It could be simple as :
ssh -R 9999:localhost:22 user@x.x.x.x
I need it to be done in a shell script so no password would be the best.
I found this tutorial, following steps:
Step 1: Create Authentication SSH-Keygen Keys on localhost
$ ssh-keygen -t rsa
It generates ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub
Step 2: Create .ssh Directory on remote x.x.x.x
$ ssh user@x.x.x.x mkdir -p .ssh
Step 3: Upload Generated Public Keys to remote x.x.x.x
$ cat .ssh/id_rsa.pub | ssh user@x.x.x.x 'cat >> .ssh/authorized_keys'
Step 4: Set Permissions on remote x.x.x.x
$ ssh user@x.x.x.x "chmod 700 .ssh; chmod 640 .ssh/authorized_keys"
Step 5: Login without password
$ ssh user@x.x.x.x
I need the reverse tunnel to establish when the system boots up, and reestablish when the network recovers from a breakdown. It seems system daemon is a good choice.
$sudo vi /etc/systemd/system/sshreversetunnel.service
[Unit]
Description=SSH Reverse Tunnel
After=network.target
[Service]
Restart=always
RestartSec=20
User=user
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o "ExitOnForwardFailure yes" -R 9999:localhost:22 user@x.x.x.x
[Install]
WantedBy=multi-user.target
It runs as the user 'user'.
"$ systemctl enable sshreversetunnel" to set it to start at boot time.
"$ systemctl start sshreversetunnel" to start immediately.
"$ systemctl daemon-reload" to update once config file is changed.
Also options on ssh:
-N Do not execute a remote command. This is useful for just for‐
warding ports.
-T Disable pseudo-terminal allocation.
"ExitOnForwardFailure yes" if 9999 is occupied on the remote host then ssh exits.
It works well.
One little detail, if network connectivity is down silently, ssh shell will look like froze. It won't take Ctrl-C. Enter ~ . press these three keys will terminate it
没有评论:
发表评论