pyControl BIG-IP Routes

Problem this snippet solves:

Summary: This script prints out the static TMM routing table from BIG-IP.

How to use this snippet:

Syntax / Usage

This script will sort and print out the static TMM routing table from BIG-IP. If you provide a file of routes with the format specified below with the - r flag, the routes will be deleted from BIG-IP.

Usage: getBIGIProutes.py - u < username> - d < device name> [- r < route_deletes.txt>] [- a < route_adds.txt>]

For deletes, route_deletes.txt should be formatted like:

destination,netmask
172.16.1.0,255.255.255.0
172.16.2.0,255.255.255.0
172.16.3.0,255.255.255.0

For adds, route_adds.txt should be formatted like:

destination,netmask,route_type,gateway
172.16.1.0,255.255.255.0,pool,
172.16.2.0,255.255.255.0,vlan,
172.16.3.0,255.255.255.0,gateway,
172.16.4.0,255.255.255.0,reject,

Script

getBIGIProutes.py

Code :

#!/usr/bin/env python

'''
----------------------------------------------------------------------------
 The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5
 Software Development Kit for iControl"; you may not use this file except in
 compliance with the License. The License is included in the iControl
 Software Development Kit.

 Software distributed under the License is distributed on an "AS IS"
 basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 the License for the specific language governing rights and limitations
 under the License.

 The Original Code is iControl Code and related documentation
 distributed by F5.

 The Initial Developer of the Original Code is F5 Networks,
 Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2004 F5 Networks,
 Inc. All Rights Reserved.  iControl (TM) is a registered trademark of F5 Networks, Inc.

 Alternatively, the contents of this file may be used under the terms
 of the GNU General Public License (the "GPL"), in which case the
 provisions of GPL are applicable instead of those above.  If you wish
 to allow use of your version of this file only under the terms of the
 GPL and not to allow others to use your version of this file under the
 License, indicate your decision by deleting the provisions above and
 replace them with the notice and other provisions required by the GPL.
 If you do not delete the provisions above, a recipient may use your
 version of this file under either the License or the GPL.
----------------------------------------------------------------------------
'''
def sort_ip_dict(ip_list):
    from IPy import IP
    ipl = [ (IP(i['destination']).int(),  i) for i in ip_list]
    ipl.sort()
    return [ip[1] for ip in ipl]

def add_tmmRoutes(obj,  filename, pool, vlan):
    pools = pool.get_list()['return']
    vlans = vlan.get_list()['return']
    routefile = open(filename, 'r')
    headers = routefile.readline().strip().split(',')
    rte_hdrs = headers[:2]
    atr_hdrs = ['gateway','pool_name','vlan_name']
    rtes = []
    atrs = []
    for line in routefile:
        ln = line.strip().split(',')
        rte = ln[:2]
        atr = ln[-2:]
        if atr[0] == 'pool':
            if atr[1] in pools:
                atrs.append(dict(zip(atr_hdrs, ['',atr[1],''])))
                rtes.append(dict(zip(rte_hdrs, rte)))
            else:
                print "Pool ", atr[1], " does not exist"
        elif atr[0] == 'vlan':
            if atr[1] in vlans:
                atrs.append(dict(zip(atr_hdrs, ['','',atr[1]])))
                rtes.append(dict(zip(rte_hdrs, rte)))
            else:
                print "Vlan ", atr[1], " does not exist"
        elif atr[0] == 'gateway':
            atrs.append(dict(zip(atr_hdrs, [atr[1],'',''])))
            rtes.append(dict(zip(rte_hdrs, rte)))
        elif atr[0] == 'reject':
            atrs.append(dict(zip(atr_hdrs, ['','',''])))
            rtes.append(dict(zip(rte_hdrs, rte)))
        
    combined = zip(rtes, atrs)
  
    for x in combined:
        xl = list(x)
        obj.add_static_route(routes = [xl[0]], attributes = [xl[1]]) 
       
     
def del_tmmRoutes(obj,  filename):
    
    routefile = open(filename,  'r') 
    headers = routefile.readline().strip().split(',')
    stored_rows = []
    
    for line in routefile:
        route = line.strip().split(',')
        stored_rows.append(dict(zip(headers,  route)))


    for route in stored_rows:
        obj.delete_static_route(routes = [route])
        print "Deleting Route ",  route
    
def get_tmmRoutes(obj):
    
    try:
        tmmStatic = obj.get_static_route()['return']
        tmmRtType = obj.get_static_route_type(routes = tmmStatic)['return']
    
    except:
        "Unable to fetch route information - check trace log"
    
    combined = zip(tmmStatic,  tmmRtType)
    
    ldict_gw_ip = []
    ldict_gw_pool = []
    ldict_gw_vlan = []
    ldict_gw_reject = []
    
    for x in combined:
            if x[1] == 'ROUTE_TYPE_GATEWAY':
                x[0]['gateway'] = obj.get_static_route_gateway(routes = [x[0]])['return']
                ldict_gw_ip.append(x[0])
            if x[1] == 'ROUTE_TYPE_POOL':
                x[0]['gateway'] = obj.get_static_route_pool(routes = [x[0]])['return']
                ldict_gw_pool.append(x[0])
            if x[1] == 'ROUTE_TYPE_INTERFACE':
                x[0]['gateway'] = obj.get_static_route_vlan(routes = [x[0]])['return']
                ldict_gw_vlan.append(x[0])
            if x[1] == 'ROUTE_TYPE_REJECT':
                ldict_gw_reject.append(x[0])
                
    gw_ip = sort_ip_dict(ldict_gw_ip)
    gw_pool = sort_ip_dict(ldict_gw_pool)
    gw_vlan = sort_ip_dict(ldict_gw_vlan)
    gw_reject = sort_ip_dict(ldict_gw_reject)
    
    print "\n"*2
    print "TMM IP Routes: (net mask ip)"
    for x in gw_ip:
            print "\t", x.get('destination') ,  x.get('netmask'),  x.get('gateway')[0]

    print "\n"*2
    print "TMM Pool Routes: (net mask pool)"
    for x in gw_pool:
            print "\t", x.get('destination') ,  x.get('netmask'),  x.get('gateway')[0]

    print "\n"*2
    print "TMM Vlan Routes: (net mask vlan)"
    for x in gw_vlan:
            print "\t",  x.get('destination') ,  x.get('netmask'),  x.get('gateway')[0]
            
    print "\n"*2
    print "TMM Rejected Routes: (net mask)"
    for x in gw_reject:
            print "\t",  x.get('destination') ,  x.get('netmask')
            

if __name__ == "__main__":

        import pycontrol.pyControl as pc
        import getpass
        

        from optparse import OptionParser
        parser = OptionParser()
        
        parser.add_option("-d",  "--device",  action="store", type="string",  dest="host")
        parser.add_option("-u", "--username",  action="store", type="string",  dest="uname")
        parser.add_option("-r",  "--delRoute",  action="store",  type="string",  dest="delrouteFileName")
        parser.add_option("-a",  "--addRoute",  action="store",  type="string",  dest="addrouteFileName")
        (options, args) = parser.parse_args()
 
        print "%s, enter your " % options.uname,
        upass = getpass.getpass()
        
        b = pc.BIGIP(
                 hostname = options.host, 
                 username   = options.uname, 
                 password   = upass, 
                 wsdl_files = ['Networking.RouteTable', 'LocalLB.Pool', 'Networking.VLAN']
                )
                
        rt = b.Networking_RouteTable
        p = b.LocalLB_Pool
        v = b.Networking_VLAN
                
        if options.delrouteFileName:
            del_tmmRoutes(rt,  options.delrouteFileName)
        
        if options.addrouteFileName:
            add_tmmRoutes(rt, options.addrouteFileName, p, v)

        get_tmmRoutes(rt)
Published Mar 09, 2015
Version 1.0

Was this article helpful?

1 Comment

  • Traceback (most recent call last): File "getBIGIProutes.py", line 170, in wsdl_files = ['Networking.RouteTable', 'LocalLB.Pool', 'Networking.VLAN'] TypeError: __init__() got an unexpected keyword argument 'wsdl_files'