How do I write a shell script to get a given process idle time?
Here you are:
#! /bin/bash
# Assumptions:
# Process is attached to a tty.
#
[[ -z "$1" ]] && echo "Usage: $0 pid" && exit 1
[[ "$1" != +([0-9]) ]] && echo "$1 is not a valid pid" && exit 1
PID="$1"
W=$(which w)
PS=$(which ps)
SED=$(which sed)
AWK=$(which awk)
TTY=$($PS -o tty4 $PID)
TTNo=$(echo "$TTY" | $SED -e '/TTY/d')
TIME=$($W | $SED -n -e "/pts\/$TTNo/p" | $AWK '{ print $5 }')
echo $PID has been idle for $TIME
How can I check a user's idle time in Linux?
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).
Related Topics
Will Process Lost Wake-Up Chance in a Preemptive Kernel
Ssh Connection to Ubuntu Open Ssh-Server Requires Login on (Physical) Server via Password First
Using Scanf into Global or Local Variables (On the Stack), 32-Bit Calling Convention
"Command Not Found" Piping a Variable to Cut When Output Stored in a Variable
Print the Directory Where the 'Find' Linux Command Finds a Match
Hard Time Installing Ia32-Lib on MAC Osx
Perf Top Result About Nested Functions
How to Set Firefox Binary Path of Firefox in Selenium in Linux
File Glob Patterns in Linux Terminal
Why Does Autoconf Erroneously Find a Function Which Isn't Available Later
Webpack Build Fails with Gitlab-Ci
How to Modify Eip's Tracee Forked Procee
Qserialport Cannot Open Tty After Application Has Previously Been Run by 'Root'
Bash: Checking If Files Are Duplicates Within a Directory
How to Find the File Which Contains a Specific Text in Linux