Created
June 28, 2018 10:08
-
-
Save skunkie/4a45aa9d00bbf997468de76059063d55 to your computer and use it in GitHub Desktop.
This script adds rules to the routing policy database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- encoding: utf-8; py-indent-offset: 4 -*- | |
# | |
# This script adds rules to the routing policy database | |
# | |
import ConfigParser | |
import os | |
import socket | |
import sys | |
from pyroute2 import IPRoute | |
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'routing.conf') | |
config = ConfigParser.RawConfigParser() | |
try: | |
config.readfp(open(config_file)) | |
except: | |
print('Cannot read the config file %s' % config_file) | |
sys.exit(1) | |
ip = IPRoute() | |
ipv4 = socket.AF_INET | |
rules = ip.get_rules(family=ipv4) | |
interfaces = {} | |
for k,v in [(x.get_attr('IFLA_IFNAME'), x['index']) for x in ip.get_links()]: | |
interfaces[k] = v | |
for section in config.sections(): | |
if section not in interfaces.keys(): | |
continue | |
try: | |
table = int(config.get(section, 'table')) | |
gw = config.get(section, 'gw') | |
vip = config.get(section, 'vip').split(',') | |
except: | |
continue | |
if not ip.get_routes(family=ipv4, table=table): | |
ip.route('add', family=ipv4, gateway=gw, table=table) | |
ip.route('add', family=ipv4, dst='127.0.0.0', oif=interfaces['lo'], dst_len=8, table=table) | |
for ip_addr in vip: | |
if not [x for x in rules if x.get_attr('RTA_TABLE') == table and x.get_attr('RTA_SRC') == ip_addr]: | |
ip.rule('add', family=ipv4, src=ip_addr, table=table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment