Sources:
https://stackoverflow.com/questions/2241063/bash-script-to-set-up-a-temporary-ssh-tunnel/15198031#15198031
https://lists.gt.net/openssh/dev/48040#48040
$ ssh -M -S my-ctrl-socket -fnNT [email protected]-M Places the ssh client into “master” mode for connection sharing.
-S Specifies the location of a control socket for connection sharing, or the string “none” to disable connection sharing.
-f Specifies an alternative per-user configuration file. The default for the per-user configuration file is ~/.ssh/config.
-n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background.
-N Do not execute a remote command. This is useful for just forwarding ports.
-T Disable pseudo-terminal allocation.
Port forwarding (example: MySQL):
$ ssh -M -S my-ctrl-socket -fnNT -L 50000:localhost:3306 [email protected]$ ssh -S my-ctrl-socket -O check [email protected]
Master running (pid=3517Means that an SSH session with a socket is running. The command returns the PID of the SSH process. don't kill the process using the PID!
$ ssh -S my-ctrl-socket -O exit [email protected]
Exit request sent.
$ ssh -S my-ctrl-socket -O check [email protected]
Control socket connect(my-ctrl-socket): No such file or directoryIf no file or directory associated with the socket string was found, it means the session was succesfully terminated.
Secure copy / scp
Setup an SSH connection to a host (host2) through an intermediate or proxy node (host1)
$ ssh -L 9999:host2:22 host1:22Now you can scp from/to host2 via localhost:9999:
$ ssh -P 9999 remoteuser@localhost:/home/remoteuser/foobar.txt foobar.txtForwarding ports
If you want to forward ports across a secure connection using a priv/pub key:
From your local machine:
$ ssh -A -L 8080:localhost:8080 host1 ssh -L 8080:localhost:8080 host2This will first initiate a tunnel to host1 and then automatically initiate a tunnel from host 1 to host2 Each time, port 8080 is being forwarded.
The -A switch is akin to ForwardAgent yes in .ssh/config. Since no interactive login session is started while tunneling, the ssh-agent on your remote hosts won't kick in and the tunnel will fail since it can't retrieve a passphrase from /dev/tty1. Using the -A switch means that, it forwards your SSH auth schema to the remote host. So you can use SSH over there as if you were on your local machine. Basically, it forwards the authentication agent connection between local machine and host1 towards host1 and host2. Of course, that's assuming you use the same priv/pub key here.
Connecting to localhost:8080 will forward your traffic to the application listening in host2:8080 over a secure connection.
More info: