2

I would like to implement a solution to a specific instance of the generic problem wherein idle users tie up resources. I know the user list can be retrieved with w, the associated PID with ps, and the final step with kill. However, I'd like to automate this process for those users who have been idle for over an hour.

The idea is to read the output of w line-by-line, selecting those lines that contain the regular expression [0-9]m (finding the users with an idle time greater than 1:00m). Then, the TTY associated with the line is extracted and sent to ps -t, the output of which contains a list of the PIDs to send to kill -9. I'm simply not sure how to string all this together.

A final caveat: nothing associated with the root user is interpreted.

  • 1
    I would stay away from kill -9 except as a last resort. Most processes will properly terminate upon receipt of interrupt (INT 2) or hangup (HUP 15) signals. Those that care will take steps to shutdown cleanly before terminating, those that don't care will terminate. kill -9 gives them no chance to clean up and is more likely to cause data loss. – RobertL Nov 23 '15 at 20:03
  • The HUP signal would be a far nicer way to get a shell to, well, hang up. – thrig Nov 23 '15 at 20:38
2

w uses the access time of the tty to determine how idle someone is, this is covered in idletime() which stats the tty file and subtracts its atime from the current time. pkill can use a terminal as the filter to kill processes.

So, you want to kill anyone who isn't root and idle for over 5 minutes?

for t in `w -h | grep -v '^root' | awk '{print $2}'`; do find /dev/$t -amin +5 -exec pkill -t $t \; ; done

What is going on here:

  • Use w with no headers to find all users
  • Filter out root
  • print out the ttys which is column 2
  • for each line, do a find to test the access time is more than 5 minutes
  • if it is, kill all processes on that terminal with pkill
  • This is exactly what I was looking for. Thanks also for the concise explanation. – Jake Brown Nov 24 '15 at 14:29
  • What should I use if I want to get the idle time of a background process that is not attached to any terminals? Comand w will not list these processes... – Gergely Lukacsy Feb 20 '18 at 16:17
2

Might be better to use shell timeouts for this. For bash export TMOUT variable as read-only

TMOUT=<seconds>; readonly TMOUT; export TMOUT

for tcsh use

set -r autologout <seconds>

in scripts in /etc/profile.d/. Shells reaching the above timeout will terminate. The output from 'w' is not always accurate (for example it cannot report time in x sessions).

If you have users logging in via ssh than use ClientAliveInterval (see sshd_config(5)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.