How do I kill a backgrounded/detached ssh session?

前端 未结 11 1262
刺人心
刺人心 2020-12-01 00:02

I am using the program synergy together with an ssh tunnel

It works, i just have to open an console an type these two commands:

ssh -f -N -L localhos         


        
11条回答
  •  我在风中等你
    2020-12-01 00:35

    There are many interesting answers here, but nobody mentioned that the manpage of SSH does describe this exact case! (see TCP FORWARDING section). And the solution they offer is much simpler:

    ssh -fL 12345:localhost:12345 user@remoteserver sleep 10
    synergyc localhost
    

    Now in details:

    1. First we start SSH with a tunnel; thanks to -f it will initiate the connection and only then fork to background (unlike solutions with ssh ... &; pid=$! where ssh is sent to background and next command is executed before the tunnel is created). On the remote machine it will run sleep 10 which will wait 10 seconds and then end.
    2. Within 10 seconds, we should start our desired command, in this case synergyc localhost. It will connect to the tunnel and SSH will then know that the tunnel is in use.
    3. After 10 seconds pass, sleep 10 command will finish. But the tunnel is still in use by synergyc, so SSH will not close the connection connection until the tunnel is released (i.e. until synergyc closes socket).
    4. When synergyc is closed, it will release the tunnel, and SSH in turn will terminate itself, closing a connection.

    The only downside of this approach is that if the program we use will close and re-open connection for some reason then SSH will close the tunnel right after connection is closed, and the program won't be able to reconnect. If this is an issue then you should use an approach described in @doak's answer which uses control socket to properly terminate SSH connection and uses -f to make sure tunnel is created when SSH forks to the background.

提交回复
热议问题