Ssh ncat keeps ncat process running after disconnect; how to prevent that

processssh

If I run the command

$ ssh othermachine ncat localhost 10000

that opens an ssh session to "othermachine" and pipes it into an ncat process. (There's something else listening on "othermachine" port 10000).

Now if I disconnect the ssh session (with Ctrl+C) the ncat process on "othermachine" keeps running. How do I prevent that? I want ncat to die if its parent ssh exits.

Best Answer

Technically when you ssh to "othermachine" you're remotely running ncat localhost 10000 on "othermachine". There is no piping going on here.

As to something else "listening" I do not believe there is anything. Rather you're running ncat localhost 10000 attempting to connect to something that's listening on port 10000 and there isn't anything there.

Example

$ ncat localhost 10000
Ncat: Connection refused.

If you tell ncat to listen then it will stay open.

$ ncat localhost -l 10000

Putting this together your command works as is, with the addition of the -l switch.

$ ssh othermachine ncat localhost -l 10000

ncat continues to run?

After performing a Ctrl+C ncat localhost -l 10000 too continues to run on the remote server for me as well.

To stop this behavior you could wrap the call to "othermachine" inside of a shell, such as sh.

Example

$ ssh othermachine -t 'sh -c "ncat localhost -l 10000"'
...stays up...

Now in another shell if I login to "othermachine" and confirm it's running:

$ pgrep -l ncat
8479 ncat

If I Ctrl+C the original ssh connection ncat stops running as well.

$ ssh othermachine -t 'sh -c "ncat localhost -l 10000"'
Ctrl + C
Shared connection to othermachine closed.

Confirming it's gone:

$ pgrep -l ncat
$

Why does this work?

The key piece in this setup is the -t switch. This forces the connection to setup a pseudo-tty (ptty) terminal as part of the connection.

excerpt from ssh man page

 -t     Force pseudo-tty allocation.  This can be used to execute arbitrary
        screen-based programs on a remote machine, which can be very useful,
        e.g. when implementing menu services.  Multiple -t options force tty 
        allocation, even if ssh has no local tty.

This ptty allows us to send the Ctrl+C through to ncat which is then terminated, resulting in the closing of the ssh connection entirely.

References

Related Question