1

If I ssh to a server and i open top packets are being sent over the network, so the normal ssh timeout(because of idling) will not work.
This means an ssh connection can stay open forever if a top process is running from the user.

Is there a way to force ssh to timeout( or drop the connection ) after a certain time, to avoid having connections stay forever just because top is opened?

Update: Scenario is people ssh in a server open top and as long as they don't close top on their own ssh will stay open forever, this means that it can be done multiple times and when I login to a server and execute "w" command (to show who is logged in) there are many ssh sessions with top open older than weeks

Boyan
  • 113

2 Answers2

1

Unfortunately, top is a foreground process. And while such a foreground process is working, you can't really know whether the user is active or away. That is why any connection/shell timeout mechanics (ssh timeout, shell timeout, etc.) cannot work in this case.

The only way I can think of accomplishing what you (probably) want is to timeout the process/command itself. It works for a single and specific command, you'd need to execute this solution for any command you want to be timed out.

To timeout a command in a shell:

timeout 60 command

Where 60 is the time (in seconds) that the shell waits before forcefully stopping the process.

You could use the timeout command to avoid forgetting foreground processes like top open which leads to endlessly open SSH connections:

timeout 3600 top

Of course it is a nuisance to always write out the whole command with timeout every single time and you can easily forget to do it, so you can just alias the top command, or in another case - if you want it global, you can move the top binary somewhere else and replace /usr/bin/top with a script that starts the top command with a timeout. Note that if you want to use it in a script like that, you'd need to use the --foreground switch of timeout, otherwise it'll start the command in a subshell. Contents of /usr/bin/top for example:

/usr/bin/timeout --foreground 3600 /path/to/real/top

Another note: If you decide to use the "global solution", you should give it a little bit more thought. What I've given is simply a suggestion and a direction. The solution will stop working after a package update to top or it could even potentially break the update.

Fanatique
  • 5,153
0

Open up another ssh connection to the server and identify the process, followed by a sigint kill command.

ps -g
kill psid

look for something like "/bash top" and that will be the process you can kill. this is all assuming you have superuser privileges on the server, because if you dont you cant do that to other processes like that.

On other news, the reason why i came to this thread is i like to have multiple terminals open and sometimes ssh times out and i was looking for a way for it to not time out so thanks for pointing out in your question a solution for me.