Python 3 Script for Automatic Shutdown on Network Outage

python shutdown scriptnetwork outage shutdownNAS power managementcrontab automationUPS backup power
Published·Modified·

Both the home mini PC and NAS are connected to a UPS backup power supply. The QNAP NAS supports normal shutdown on power loss via its default USB UPS communication interface. However, since the NAS occupies the only USB UPS communication port, the mini PC cannot achieve automatic shutdown on power loss. Therefore, an alternative approach using a network outage shutdown solution was adopted.

Implementation Principle

Once a power outage occurs at home, the router stops working, and the network connection is interrupted. Since the mini PC is connected to the UPS, it continues to run after the power outage, but the UPS cannot sustain it for long. To ensure a normal shutdown during a network outage, a Python script combined with a crontab scheduled task is used to periodically check for network connectivity. If the network is down, the shutdown command is executed.

Script Content

Save the following script as auto-shutdown.py:

#!/usr/bin/python3
import requests
import os

# Modify file
def err_num(num):
    # Open a file for writing. If the file exists, it opens the file and starts editing from the beginning, deleting existing content. If the file does not exist, a new file is created.
    fo = open("/tmp/err_num", "w")
    # Convert to string
    num = str(num)
    # fo = open("D:/temp/123.txt", "w")
    fo.write(num)
    # Close the file
    fo.close()


# Get input parameters
try:
    # Request Baidu
    r = requests.get('https://www.baidu.com/', timeout=10)
    code = r.status_code
except:
    code = -1
    pass

if code >= 200:
    err_num('0')
else:
    # Read current error count
    fo = open("/tmp/err_num", "r")
    num = fo.read()
    # Reset count to 0
    if num == '':
        num = 0
    fo.close()
    # Increment current error count
    num = int(num) + 1
    # print(num)
    
    err_num(num)
    if num >= 5:
        # Execute shutdown operation
        os.system('/usr/bin/sync && /usr/sbin/shutdown -h now')
  • Access Baidu: https://www.baidu.com/ to determine if the network is available.
  • If more than 5 consecutive attempts fail, the shutdown operation is executed.

Scheduled Task

Add a crontab -e scheduled task to check every 2 minutes:

*/2 * * * * /root/code/python/auto-shutdown.py >> /dev/null

Combined with the script above, it runs every 2 minutes on average. If it fails 5 consecutive times, it triggers a shutdown. This means a shutdown will occur after 10 minutes of network outage, but you can adjust the crontab detection frequency according to actual needs. While a shell script could also achieve this, Python 3 is more convenient to write.