1

So I have a Ubuntu 16.04 system that's supposed to be running an SSH script that I wrote, every time the system boots up. This is my first time trying to get it to work, so it never has before.

The script is very simple:

while true; do sleep 60; ssh root@ip -i ~/.ssh/key -R xxxx:localhost:22; done

It's inside of a file called autossh.sh.

To get the script to run automatically, I've tried to include it inside of /etc/rc.local (before exit 0), I've tried to add it to the list of startup applications from Ubuntu's GUI.

During both times I reboot the computer, I can see that the script is actually running, but it's not mapping a remote port to localhost 22 like the command is supposed to do. If I run the command manually, it works, but it just doesn't work upon boot.

Is there something obvious that I'm missing here that's preventing this script from working as it should?

user3447014
  • 623
  • 3
  • 9
  • 22

1 Answers1

0

1. The tilde (~) will resolve to your home directory, but it hasn't a meaning while you are not logged in. This is not so important according to the next suggestion but is good to be emphasised. Related answer. My suggestion here is to rewrite the script in this way:

#!/bin/bash
while true; do sleep 60; ssh root@ip -i "$HOME/.ssh/key" -N -f -R xxxx:localhost:22; done
  • or better use /the/full/path/to/ instead of $HOME.

  • -f Requests ssh to go to background just before command execution.

  • -N Do not execute a remote command. This is useful for just forwarding ports.

2. SSH keys are readable only for their owner, so other users can't use them and they cannot be used system wide. So my suggestion is to use a Cron for this task.

Log in with the user that is owner of the SSH key and run crontab -e (-e means edit), or use sudo -u <user-name> crontab -e (-u means execute as the user called <user-name>) and add this line at the bottom:

@reboot /full/path/to/the/script/autossh.sh > /tmp/autossh.log 2>&1

Save and close Crontab. This line should execute the script at system startup and will write a log.

References:


Update:

pa4080
  • 29,831