Created
August 4, 2023 06:16
-
-
Save gnyman/a7f5e9efc4a14d199ec9257b0032fe13 to your computer and use it in GitHub Desktop.
Very simple network checking script which reboots your Huawei 5G modem when internet goes down. It will also print the signal statistics as csv every 30 seconds which might help you figure out why things break. Mostly untested, might or might not work, no returns, all purchases are final :-)
This file contains 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
import os | |
import time | |
import sys | |
import csv | |
import datetime | |
import subprocess | |
from huawei_lte_api.Client import Client | |
from huawei_lte_api.Connection import Connection | |
def ping(host): | |
""" | |
Returns True if host responds to a ping request | |
""" | |
process = subprocess.Popen(['ping', '-c', '1', host], stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
stdout, stderr = process.communicate() | |
# If the call was successful there will be output in stdout | |
return bool(stdout) | |
def write_dict_to_stdout(data_dict, first_time): | |
""" | |
Writes a dictionary to stdout in CSV format | |
""" | |
data_dict['time'] = datetime.datetime.now() | |
writer = csv.DictWriter(sys.stdout, fieldnames=data_dict.keys()) | |
if first_time: | |
writer.writeheader() # write a header | |
writer.writerow(data_dict) | |
def main(): | |
host = "8.8.8.8" | |
failed_pings = 0 | |
connection = Connection('http://admin:PASSWORD@192.168.8.1/') | |
client = Client(connection) | |
write_dict_to_stdout(client.device.signal(), True) | |
while True: | |
if ping(host): | |
failed_pings = 0 | |
else: | |
print(f"Failed to reach {host}.", file=sys.stderr) | |
failed_pings += 1 | |
if failed_pings >= 3: | |
print("Failed to reach host 3 times. Restarting modem...", file=sys.stderr) | |
client.device.set_control(ControlModeEnum.REBOOT) | |
print("Modem restart command executed. Waiting 5 minutes before retrying...", file=sys.stderr) | |
time.sleep(300) # wait 5 minutes before retrying | |
failed_pings = 0 | |
time.sleep(30) # wait 30 seconds before next ping | |
write_dict_to_stdout(client.device.signal(), False) # Can be accessed without authorization | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment