Linux – Command to reboot machine when no users are logged in

linuxrebootscriptingusers

Is there a command to reboot a machine whenever the next time that there are no current users logged in occur?

Currently, I have to SSH to machines and use the "w" command to see the users logged in so I know if its okay to reboot or not. If there is a user logged in, I simply can’t reboot because they might have unsaved work left on their Linux box, which is often the case. This can come very time consuming when I have to SSH to the same machine multiple times a week waiting for a time when there are no users logged in.

To make this really simple, I need the following.

A command that will reboot the computer when no users are currently logged in.

Best Answer

This should help... but it's not a command but short script. I believe there is no command for it. It's a script for use with cron, but you can execute it remotely on your machines ofcourse.
I'm using it for rebooting after updates.

#!/bin/bash
#  Run this script as a cronjob at some suitable time in the PM, e.g. 10pm.
# Turns off workarea machine if no one is logged on, if someone is logged on
# then checks at 15 minute intervals until a set hour is reached.
# Must be used in conjuntion with the following BIOS settings:
# - Machine powers on in event of AC power being restored after loss
# - Machines turns itself on at a time at least 1 hour after the hour specified
# for $giveupat


# time to give up checking if anyone is logged on at. Specify as an hour on 
#24 clock  e.g. for 7am set to 07. for 7pm set to 19 (though you probably 
#do not want to specify a time in the evening!)
giveupat="07"



# while someone is logged in to the machine...
while [ -n "$(who)" ];do
   if [ "$(date +%H)" != "$giveupat" ];then
   # if time hasn't read the hour at which to give up, sleep 15 minutes
      sleep 900 
   else
     # otherwise stop the script
      exit
   fi
done


# turn off gui login screen
service xdm stop


# reboot
reboot now

Source: linuxquestions.org

Related Question