Saturday, December 17, 2016

script to check gateway reachability

the script below will check gateways readabilities and update route accordingly

1- script name checkgateway-updatemetric.py
#!/usr/bin/python
import thread
import time
import re
import subprocess
import threading
import sys
import os
import yaml
# Define a function for the thread
n = 0
exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter,baseAddr,metric):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.baseAddr = baseAddr
        self.metric = metric
    def run(self):
        print "Starting " + self.name
        handler_mgmt(self.name, self.counter, self.baseAddr, self.metric)
        print "Exiting " + self.name

def testconn(address):
    command = ["ping", address, "-c", "1", "-i", "0.2", "-W", "1"]
    testresult = subprocess.Popen(command ,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if re.search(r"1\sreceived", testresult.stdout.read()):
        return True
    return False
 

def handler_mgmt( threadName, delay, baseAddr, metric):
    count = 0
    global n
    counter = 20
    while counter:
        if exitFlag:
            threadName.exit()
        result = testconn(baseAddr)
        time.sleep(3)
        print baseAddr + " reachable " + str(result)
        if result == False:
            comm = "ip route del default via " + baseAddr
            os.system(comm)
        else:
            comm = "ip route add default via " + baseAddr + " metric " + str(metric)
            os.system(comm)

configf = "checkgateway-updatemetric.conf"
c = 20
with open(configf, "r") as f:
    config = yaml.load(f)
gw1ip = config['gw1']['ip']
gw1metric = config['gw1']['metric']
print gw1ip
print gw1metric
gw2ip = config['gw2']['ip']
gw2metric = config['gw2']['metric']
print gw2ip
print gw2metric

thread1 = myThread(1, "Thread-1" , 1,gw1ip,gw1metric)
thread2 = myThread(2, "Thread-2" , 1,gw2ip,gw2metric)

thread1.start()
thread2.start()




2- configure your gateways on the file checkgateway-updatemetric.conf on the same directory as script and the content below
gw1:
  ip: 1.1.1.1
  metric: 20
gw2:
  ip: 1.1.1.2
  metric: 30


3-  to start it run the command like below
$ sudo python checkgateway-updatemetric.py

if both gateways are reachable the route look similar to below
$ ip route show
default via 1.1.1.1 dev eth1  metric 20
default via 1.1.1.2 dev eth1  metric 30
192.168.56.0/24 dev eth0  proto kernel  scope link  src 192.168.56.23 




and it will remove the one that become unreachable.

No comments:

Post a Comment