Python Script to Reboot the LinkSys EA3500 router

this is followup of How to SSH on LINKSYS ROUTER with USB Port, I shall now detail the Python Script which is running on my Synology NAS 712 connected to the LINKSYS EA3500 router.

pls read the post Rebooting the ADSL Router when it cannot Access Internet to ready the NAS for running the python script. module required is “pexpect”.

# python script to reboot the devices using SSH
import sys
import os
import socket
import logging
import re
import pexpect
# import getpass
pathname = os.path.dirname(sys.argv[0])        
# print 'path =', pathname
# print 'full path =', os.path.abspath(pathname)
fullpath = os.path.abspath(pathname)

logging.basicConfig(filename= fullpath + '/mxHomeEA3500.log',level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')

PROMPT = "$|%|>|#"  # add the prompt with |prompt

# check if google is reachable
def net_test():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("", 80))
        return True
    except socket.error:
        return False

# connect to Router via SSH
class SSH:
    def __init__(self, user, password, host):
        #print "test ssh"     # uncomment to debug
        self.child = pexpect.spawn("ssh %s@%s"%(user, host))
        i = self.child.expect(['assword:', r"yes/no"], timeout=120)
        if i==0:
            #print "0"    # uncomment to debug
  '-EA3500 SHH Key Accepted')
            #response = self.child.before
        elif i==1:
            #print "1"    # uncomment to debug
  '-EA3500 SHH Key not yet Accepted')
            self.child.expect("assword:", timeout=120)

        #print self.child.before

    def command(self, command):
        """send a command and return the response"""
        self.child.expect('Connection to closed.')
        # waiting for PROMPT returns error in pexpect after command reboot
        #response = self.child.before
        #return response
        return 'Connection to closed.'    # this is response from EA3500

    def close(self):
        """close the connection"""

if __name__=="__main__":
    network = net_test() # Testing network connection.
    #print network       # uncomment to debug
    if network == True:  # Used for Debug
        # if network == False: # this the true test, when google is not available reboot the router
        logging.error('-EA3500 Reboot due to hang') #print "Rebooting it!"
                # adsl_reboot() # Rebooting the modem. # check my post of PEXPECT module of Python
        #password = getpass.getpass("Password: ")
        password = "kamath17@"
        ssh = SSH("root", password, "")
        # print ssh.command("pwd")            # uncomment to debug ie check if other command work
        #print ssh.command("dir")             # uncomment to debug ie check if other command work"reboot"))   # comment to debug ie check if other command work

save the script in /volume1/myScripts/ a share folder and make a log file /volume1/myScripts/mxHomeEA3500.log. Now we can configure the NAS to Run the Python Script

Step 1: go to Control panel > Task Scheduler

Step 2: Create a new Task Scheduler > user script

Step 3: Follow the Step on Image
general tab

Step 4:Ensure you select the schedule as per the requirement; in this case a test every Hrs look reasonable and the reboot is initiated only if the google website is not reachable

Step 5: to Test the script by clicking RUN

If not working or error, ie you do not see the EA3500 rebooting, Follow the following Step

Step 6: SSH to the NAS as root and run the script from prompt

> ssh root@ipAddrNas
> Password: admin password
nas> cd /volume1/myScripts/
nas> python

check the outputs on the terminal for Error; maybe you should uncomment lines in script to make the debug easy.

Posted in Network Hardware, Storage and tagged , , , , , .

One Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.