2 Answers
2

Important: See the NOTES section in the man page for w. The line above produces something like this:

username1 0.00s
username2 48.08s

Then use cron to execute the script that you created to utilize the output from w.
Use whichever scripting language you prefer. Perhaps you do not care about usernames, only idle times?

w | tr -s " " | cut -d " " -f 5 | tail -n +3

Any result < 3600 seconds does not meet the one-hour idle time requirement.

My server should shutdown after 01:00 am, if there was no activity in the past hour. Lets say there was the last connection at 00:43 then it should check again at 01:43.

Doesn't that require a dynamic modification of the cron job itself? I think I might be satisfied to run it once hourly; otherwise, I would have to run the script every minute to acquire that precision.

Here is a script in PHP that works well on Linux Mint 13. It should be fine for Ubuntu or any other Linux.

#!/usr/bin/env php
<?php
/* Shutdown Script
*
* If idle times exceed a defined value or if no users are logged in,
* shutdown the computer. If running from cron there should be no "dot"
* in the script file name. Make the script executable.
*
* Caveat: running the script as root in an interactive shell will cause
* immediate shutdown, as though typing 'shutdown -P now'.
* (It should only be run from cron.)
*/
$max_idle_time = 3600; // seconds
$cmd_idle_time = 'w|tr -s " "|cut -d " " -f 5|tail -n +3'; // idle times
$shutdown_now = true; // boolean
function shutdown() {
exec('/sbin/shutdown -P now'); // or -h
}
// Form an array from the output of $cmd_idle_time
$idle_times = explode('\n', shell_exec($cmd_idle_time));
foreach ($idle_times as $idle_time) {
// Are there no users logged on, or did root run this from a shell?
if (empty($idle_time)) {
shutdown();
}
// Remove trailing "s" from idle time and round to nearest second
$idle_time = round(substr($idle_time, 0 , -2));
// Cancel shutdown if any user's idle time is less than $max_idle_time
if ($idle_time < $max_idle_time) {
$shutdown_now = false;
}
}
// If the $shutdown_now boolean is still true, shutdown.
if ($shutdown_now === true) {
shutdown();
}
?>