Python 3 Script to Disable Internet and Shutdown

Publish: 2021-04-23 | Modify: 2021-04-23

Implementation Principle

Once the power is cut off at home, the router stops working and the network is interrupted. Since the mini host is connected to the UPS, it continues to run after a power outage, but the UPS can't last for too long. In order to ensure a proper shutdown when the network is disconnected, a Python script + crontab scheduled task is used to periodically check if the network is disconnected and execute the shutdown command if it is.

Script Content

Save the following script as auto-shutdown.py:

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

# Modify the file
def err_num(num):
    # Open a file for writing only. If the file exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
    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 the current error count
    fo = open("/tmp/err_num", "r")
    num = fo.read()
    # Reset the count to 0
    if (num == ''):
        num = 0
    fo.close()
    # Increase the current error count by 1
    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 there are 5 consecutive failures, execute the shutdown operation.

Scheduled Task

Add the scheduled task crontab -e, check every 2 minutes:

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

With the above script, it checks every 2 minutes on average, and performs a shutdown operation after 5 consecutive failures. This means that the shutdown operation will be executed after 10 minutes of network disconnection. You can modify the frequency of the crontab check according to the actual situation. In fact, it can also be implemented using a shell script, but Python 3 is more convenient to write.


Comments