Search code examples
linuxamazon-ec2clouddigital-oceanscreensaver

How can I check a user's idle time in Linux?


I have a cluster of virtual machines on cloud (Digital Oceans), and I want to find a way to turn them off if they are idle for at least 1 hour.

I imagine it is similar to how a screensaver decides to kick in after an appointed duration of idle, or how some cloud services like Snowflake or Databricks can turn off resources if they are not used for a duration.

I have checked the w command and do not find any info that can tell me idle time, although that command's output has an idle column.

If you know how a screensaver kicks in, or how cloud services turn off resources, please share. Much appreciated.

=== UPDATE ===

After running w | awk '{if (NR!=1) {print $1,$5 }}', my output is like this

kha 10days
kha -

Solution

  • The idle time measured by w is simply indicating how long since something was typed on the terminal a process is attached to. As seen e.g. here this is inaccurate for actually measuring user activity, since they might be using solely graphical input and not typing anything.

    If your users are logged into an X11 session, the X client library has its own idle timer which can be queried; see e.g. User idle time being reset to 0 after 30 secs on Linux

    Cloud monitoring systems appear to examine things like CPU load and network traffic to decide when to declare an instance as idle. They probably have a baseline of system processes which can be ignored, and then simply add a tick whenever a non-system process is detected.

    For your use case, perhaps a simple network monitoring tool would be the easiest to set up. If your users are always logged in over SSH, check for traffic on port 22; if there is none over several minutes, the instance is idle. For X11 sessions, something similar could be set up for X protocol traffic (ports typically in the range from 6000 up).