56

I have to set up a tunnel between two hosts.

For this I use ssh in this way:

ssh -L MY_LOCAL_PORT:FOREIGN_ADDRESS:FOREIGN_PORT MYUSER@SSH_SERVER

after that, I log in to my SSH_SERVER.

How can I avoid this feature?! I have only to set up a tunnel. I don't have to login into my SSH_SERVER...

I've tried the -N option, but it kept my shell busy.

  • SSH -N -L xx:xx:xx user@server & <-- have you tried that before ? – Lawrence Nov 12 '13 at 7:45
  • Hey, you have right. I've tried on another host and the -N option works. So I've discovered that the problem is on my ssh client (I don't know why, and I will search the reason). Thanks a lot! – Bau Miao Nov 12 '13 at 9:41
  • 1
    man ssh shows how: ssh -f -L 1234:localhost:6667 server.example.com sleep 10 && irc -c '#users' -p 1234 pinky 127.0.0.1 The -f option backgrounds ssh and the remote command ``sleep 10'' is specified to allow an amount of time (10 seconds, in the example) to start the service which is to be tunnelled. If no connections are made within the time specified, ssh will exit. ``` – lionello Jun 5 '17 at 7:02
66

As said in other posts, if you don't want a prompt on the remote host, you must use the -N option of SSH. But this just keeps SSH running without having a prompt, and the shell busy.

You just need to put the SSH'ing as a background task with the & sign :

ssh -N -L 8080:ww.xx.yy.zz:80 user@server &

This will launch the ssh tunnelling in the background. But some messages may appear, especially when you try to connect to a non-listening port (if you server apache is not launched). To avoid these messages to spawn in your shell while doing other stuff, you may redirect STDOUT/STDERR to the big void :

ssh -N -L 8080:ww.xx.yy.zz:80 user@server >/dev/null 2>&1 & 

Have fun with SSH.

  • 16
    You can also use ssh option -f instead of & and io redirection. – tkrennwa Nov 13 '13 at 13:49
42

-f -N is what you are looking for:

ssh -f -N -L MY_LOCAL_PORT:FOREIGN_ADDRESS:FOREIGN_PORT MYUSER@SSH_SERVER
  • 3
    Once the tunnel is set up, how do you close it with this method? – magnetik Dec 7 '15 at 8:02
  • @magnetik Find the process with ps and kill it – neu242 Dec 8 '15 at 8:45
  • 12
    @magnetik and @neu242 the better is to use "master socket" ssh -N -f -M -S /tmp/file-sock -L port:server:port_to user@... so you can kill the connexion later with ssh -S /tmp/file -o exit user@.... (or kill). That way, no need to ps. You can tell to automatically create that file in ~/.ssh/config. – Metal3d Dec 14 '15 at 13:47
  • 1
    I mean "control socket" and not "master socket" – Metal3d Dec 14 '15 at 13:56
  • 7
    It should be ssh -S /tmp/file-sock -O exit, not -o en.wikibooks.org/wiki/OpenSSH/Cookbook/… – fetsh Apr 1 '16 at 15:08

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.