Python Script to Reboot the LinkSys EA3500 router

Warning: This article was published many years ago (greater than two) Oct 11, 2013. Some information may be outdated.

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():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("www.google.com", 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
            logging.info('-EA3500 SHH Key Accepted')
            self.child.sendline(password)
            #response = self.child.before
        elif i==1:
            #print "1"    # uncomment to debug
            logging.info('-EA3500 SHH Key not yet Accepted')
            self.child.sendline("yes")
            self.child.expect("assword:", timeout=120)
            self.child.sendline(password)

        self.child.expect(PROMPT)
        #print self.child.before

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

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

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 192.168.1.1 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, "192.168.1.1")
        # 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
        logging.info(ssh.command("reboot"))   # comment to debug ie check if other command work
        ssh.close()

save the script in /volume1/myScripts/rebootEA.py 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
task

Step 2: Create a new Task Scheduler > user script
create

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
schedule

Step 5: to Test the script by clicking RUN
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 rebootEA.py

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

One comment

Leave a Reply

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