Created
January 19, 2021 23:10
-
-
Save fellipec/b923c454bb4cf80e088c0933529957ff to your computer and use it in GitHub Desktop.
Python3 Watchdog to shutdown computer when power fails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
#Checks for hosts alive in the network. | |
#If all hosts are offline, assume that power has failed | |
#and initiate a shutdown | |
#Luiz Fellipe Carneiro - 01/2021 | |
import socket | |
import os | |
#Path of shutdown detection file | |
ShutdownFile = "/home/fellipec/watchdog/failure.log" | |
#Check if a shutdown file exists | |
def ShutdownFileExists(): | |
result = False | |
if os.path.isfile(ShutdownFile): | |
result = True | |
return(result) | |
# Try to connect to a socket | |
def isOpen(ip,port): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
try: | |
s.connect((ip, int(port))) | |
s.shutdown(2) | |
return True | |
except: | |
return False | |
# Issue the shutdown command in 30 minutes | |
# If a shutdown was detected before, do nothing | |
def shutdown(): | |
if not ShutdownFileExists(): | |
command = "/usr/bin/sudo /sbin/shutdown +30 Power Failure, shutting down" | |
import subprocess | |
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) | |
output = process.communicate()[0] | |
print("Power failure. Shutting down in 30 minutes") | |
#Write a file so we know later the power failure was already detected | |
F = open(ShutdownFile,"w") | |
F.write(str(output)) | |
F.close | |
# If a previous shutdown has detected, but now detected the hosts alive | |
# again, assume the power was restored and abort the shutdown, them | |
# delete the shutdown detection file. | |
def abortshutdown(): | |
if ShutdownFileExists(): | |
command = "/usr/bin/sudo /sbin/shutdown -c Power restored, abort shut down" | |
import subprocess | |
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) | |
output = process.communicate()[0] | |
print("Power restored, aborting shutdown") | |
os.remove(ShutdownFile) | |
#Device list | |
DeviceList = [ | |
("192.168.100.44",80), #Epson printer | |
("echodot.lan",1080), #Alexa | |
] | |
#Default no devices are online | |
isonline = False | |
#Test every device, if any is online change the status to True | |
for (device,port) in DeviceList: | |
isonline = isonline or isOpen(device,port) | |
#Call the functions as needed | |
if isonline: | |
abortshutdown() | |
else: | |
shutdown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment