Operating System - Linux
1821638 Members
2973 Online
109633 Solutions
New Discussion юеВ

persistent ssh tunnel in a script

 
SOLVED
Go to solution
Gilbert Standen_1
Frequent Advisor

persistent ssh tunnel in a script

Ok, I create a tunnel from "home" to "work" via "gate":

ssh -l myuserid -L 7777:work:22 gate

and leave this terminal session open and now I can make use of my tunnel for scp etc.

But suppose I want to create a persistent tunnel but I want to do it in a script or something? I saw one author who recommended this:

ssh -l myuserid -L 7777:work:22 gate cat -

where the author has used "cat" to keep the connection open (or other command which does not finish could be used). If no "non-finishing" command is provided, then a shell opens and then you need a controlling terminal and cannot use the ssh command in a script. Moreover, some servers have protections against running things like "cat -" and so on a well-secured server you won't easily be able to use some "non-finishing" command like that.

So how do you create a persistent tunnel in a script without having a controlling terminal? Is that possible?

Thanks, Gil
If I could take one thing with me into the next world it would be my valid login to HP ITRC Forums
2 REPLIES 2
Matti_Kurkela
Honored Contributor
Solution

Re: persistent ssh tunnel in a script

If your SSH client is reasonably up to date, something like this might do the trick:

ssh -l myuserid -L 7777:work:22 gate -o ExitOnForwardFailure=yes -n -N &
# capture the PID of the SSH process:
TUNNELPID=$!

To remove the tunnel when you're done, use "kill $TUNNELPID".

Options:
-n removes the need for a controlling terminal.
-N says we are running SSH to get port forwardings only, remote command is not needed.
-o ExitOnForwardFailure=yes means that SSH will terminate if a tunnel cannot be set up.

You might use the "-f" option instead of "&", but then capturing the PID will be more difficult...

SSH has a lot of useful options: reading the man page helps.

MK
MK
Gilbert Standen_1
Frequent Advisor

Re: persistent ssh tunnel in a script

Thanks Matt
If I could take one thing with me into the next world it would be my valid login to HP ITRC Forums