Run SSH Tunnel in background

I. start the tunnel in background

To open a SSH tunnel (port forwarding) in background, the following options for ssh command will be used:
  • -L [bind_address:]port:host:hostport
    • Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side.  This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address.  Whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the remote machine.
  • -N
    • Do not execute a remote command.  This is useful for just forwarding ports (protocol version 2 only).
  • -f 
    • Requests ssh to go to background just before command execution.

Suppose I want to access the intranet site at work from home, and I have ssh access to the gateway host at work.

ssh -L -f -N
The command above will start the tunnel (and the ssh process is running)in background.

II. kill the ssh process running in background

To kill the ssh process running in background, we can run ps aux to find the pid but that is not an elegant solution. ssh has -M -S and -O options to control the ssh process. It is ideal for this purpose.
  • -M 
    • Places the ssh client into "master" mode for connection sharing.
  • -S ctl_path 
    •  Specifies the location of a control socket for connection sharing, or the string ``none'' to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details.
  • -O ctl_cmd 
    • Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: ``check'' (check that the master process is running), ``forward'' (request forwardings without command execution) and ``exit'' (request the master to exit).

# starts the tunnel
ssh -L -f -N -M -S ~/

# checks the ssh process (pid)
ssh -S ~/ -O check

# exits the ssh process (stops the tunnel)
ssh -S ~/ -O exit

III. A example shell script

The following shell script (Tested on Mac OS X) starts the ssh tunnel in background, then open the intranet web site, when the browser application is closed, it stops the ssh tunnel.




LOCAL_HOST=$(ifconfig | grep "inet " | grep -v | awk '{print $2}')




open -W http://${LOCAL_HOST}:${LOCAL_PORT}/


See also

No comments:

Post a Comment