Skip to content

Instantly share code, notes, and snippets.

@chozabu
Created June 22, 2016 09:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chozabu/405655e5f322819bee6e281f3d012f8b to your computer and use it in GitHub Desktop.
Save chozabu/405655e5f322819bee6e281f3d012f8b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
"""picofix.py: reboot the a router when it fails to contact a distant node."""
__author__ = "Alex 'Chozabu' P-B"
import pyping
from time import sleep
from datetime import datetime
import pxssh
def reboot_router():
try:
s = pxssh.pxssh()
s.login('192.168.2.209', 'root', 'thereisapassword')
s.sendline('reboot') # run a command
s.prompt() # match the prompt
print(s.before) # print everything before the prompt.
s.logout()
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(e)
def main_loop():
reboots = [None]
fail_count = 0
ok_count = 0
while True:
if pyping.ping('192.168.32.1').ret_code:
ok_count = 0
fail_count += 1
print("FAIL", fail_count)
if fail_count > 10:
reboots.append(datetime.now().strftime("%Y-%m-%m %H:%M"))
print("rebooting router!")
reboot_router()
print("rebooted router, waiting 60 seconds")
print('reboots:', reboots)
sleep(60)
print("OK, back to normal")
fail_count = 0
else:
fail_count = 0
ok_count += 1
print("seems OK, ok_count:", ok_count, 'last_reboot:', reboots[-1], 'of', len(reboots)-1)
sleep(2)
if __name__ == "__main__":
main_loop()
@cjhoyle
Copy link

cjhoyle commented Feb 8, 2020

Is there any preparation on the router side that would normally need to be done for pxssh to be able to access it? My router is a dlink, and when accessing it from my web browser the username is "admin" and the password is the one that I set. I have tried the above code with the correct IP Address, username and password, but I'm getting a "Could not establish connection to host" error.

Any suggestions?

@chozabu
Copy link
Author

chozabu commented Feb 9, 2020

Your router must support SSH for this script, you may be able to enable it via the web interface, otherwise you may need a different script, or different router.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment