I was wondering if it's possible to detect a shutdown due to power loss on a Linux system. (Power loss defined as: pressing reset button, pressing power button, pulling the power cord) If so, how? (ie, if this is already something that people can do, what commands do I run?)
The way I would imagine something like this working:
- When system comes back up, checks for an issued shutdown or reboot command, finds none.
- System checks for any sort of errors that have been logged that would require a reboot, such as kernel panic, etc (OOM maybe?) and
finds none. - If no smoking gun found as described above, the system logs something like "No cause for shutdown found, potential power loss detected."
Best Answer
It depends on your implementation of
last
but if your system crashed you'll see a message to this effect in thelast
output.Example
Notice the
crash
lines? These are as a result of the power going out or someone hitting the power switch on this particular system.More esoteric method
One that I've seen used quite well is if you have a laptop, you can use the command line tool
acpi
to query the system's ACPI interface. This will tell you, among other things, when the system is on-line with power or running off of its battery.Example
Here's the output from that command on my laptop.
Simply checking the contents of the line
Adapter
will tell the system's current status. This could be wrapped into a monitor, if for example, you wanted to monitor a group of machines to see if they've experienced their power being cut as a group.plugged in
unplugged