3

I have a Raspberry Pi 2 running behind a firewall that prevents inbound SSH connections, so I get the Raspberry Pi to create a reverse SSH tunnel to an external server so that I can get an SSH connection to the Pi via that external server. The command the Pi runs is something like this:

#!/bin/bash

while true; do
    ssh -R 19998:localhost:22 user1@www.user1website.pro
sleep 30
done

Then, on the server to which it connects, I can access the Pi using a command like the following:

ssh -X pi@localhost -p 19998

What I want is for the Raspberry Pi simply to boot to its terminal and then to run automatically this connection procedure for the user pi, i.e. not as root. What would be a good way to do this?

1 Answer 1

1

Let's say the path to that script is /home/pi/bin/tunnel.sh.

Add this to /etc/rc.local:

export PATH=/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin

( exec sudo -H -u pi /home/pi/bin/tunnel.sh ) &

If this last line doesn't work, you could try instead:

nohup sudo -H -u pi /home/pi/bin/tunnel.sh &

This may solve issues related to the backgrounding.

And to the top of tunnel.sh:

export PATH=$HOME/bin:$PATH
exec &> /home/pi/tunnel.log
echo Starting $(date)

The purpose of that is explained here.

3
  • Thanks very much for your suggestion there. It looks to be definitely along the right track. However, when I try to do this, the system seems to make an attempt to run my script, but then the system hangs at login. I note also that no output is saved to the log file (as you added to your code). What could be going wrong? Is there something else needed to handle my script that features its continuous loop? I thought that adding the & seemed reasonable, but maybe it isn't. What do you think? Jun 6, 2017 at 14:45
  • I tweaked that a bit to use a subshell (the parantheses); see if that makes any difference.
    – goldilocks
    Jun 6, 2017 at 16:53
  • I've also added a suggestion about using nohup; if that doesn't work I think you will need to create a systemd service (there's a User= option there).
    – goldilocks
    Jun 6, 2017 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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