Quinn’s Brain, aka QBrain

Quinn’s Brain, aka QBrain

Finance, Food, Fitness

Quinn’s Brain, aka QBrain RSS Feed
 
 
 
 

How do you get remote interactive commands initiated ssh commands to die when the ssh connection dies?

This would have been called “How the fuck do I get remote commands to die” but I wanted to make sure I had all the keywords in the title, so I could find the answer later.

First the problem. When a running a command remotely using ssh, there is no local ptty associated with that remote command. So if the connection dies, or someone kills the ssh itself, the command continues running on the remote box.

For example, you have several servers and you want to monitor a log file on each of them from a central location. There are other solutions to this problem, but for the sake of the argument, we want to use tail -f on the remote box and the tail will be run over ssh.

ssh login tail -f log file

If the ssh is killed, the tail -f will live forever on the remote box.

The solution is simple, once you know where to look for it. In the ssh man pages there is a flag, -t, that will associate the local ptty with the remote command. So if the ssh goes away, the ptty goes away for the remote command, triggering the remote command to terminate on its own. This is the desired behavior.

But now, you want to write a perl script to monitor all these remote tails you have going. The problem now is that you don’t have a ptty because your command is started from inside the perl script. Oh no, what to do?

Run around, scream and shout!

Actually, the hard part was finding -t. Going back to that wonderful bit of knowledge and reading the last bit of the paragraph explaining -t, the mention Multiple -t options force tty allocation, even if ssh has no local tty. Really, that was nice of them. That is exactly what I needed.

So the command becomes

ssh -tt login tail -f log file

and I can stick it in whatever script I want, and it will clean up nicely is the ssh connection is ever lost.

Leave a Reply

You must be logged in to post a comment.