2

I have looked at various questions but none seems to work...

I have a remote Pi that for various reasons tends to lose power occasionally and then boot back up. I don't have physical access to this thing very often so I set up an ssh tunnel to access it remotely. I need this tunnel to start when the Pi reboots so that I can always have access, even if the power goes in and out.

I have the following script create_tunnel.sh running in a cronjob (user and hostname removed obviously):

/usr/bin/ssh -i /home/user/.ssh/id_rsa -N -R 4445:localhost:22 user@hostname &
if [[ $? -eq 0 ]]; then
    echo "Tunnel to host created successfully"
else
    echo "An error occurred creating a tunnel to host. RC was $?"
fi

And here is the crontab:

@reboot /usr/local/sbin/create_tunnel.sh > /usr/local/sbin/tunnel.log

When I reboot manually, I can see in tunnel.log that the job ran:

Tue  4 Apr 13:34:27 EDT 2017
Tunnel to host created successfully

But the tunnel does not exist. And when I go to run the command manually, after the Pi has booted, the tunnel comes up fine and I can connect to it without any hassle. What's going on? Is the tunnel getting created and then later destroyed somehow?

  • I have used autossh for this purpose in the past. It has a number of convenience features that might make it simpler than rolling your own with bare ssh, including keepalives and reestablishing dropped connections. – bobstro Apr 4 '17 at 19:13
3
/usr/bin/ssh -i /home/user/.ssh/id_rsa -N -R 4445:localhost:22 user@hostname &

You start the process in the background, which is always successful regardless the result. You should use -f switch instead, which will make the process go to background just after the connection and port forwarding is established (or failed):

/usr/bin/ssh -f -i /home/user/.ssh/id_rsa -N -R 4445:localhost:22 user@hostname
  • Thanks! This didn't fix the problem but it did reveal that the tunnel was not being created properly by showing the correct result in the log file. – ClydeTheGhost Apr 6 '17 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.