Files
mikrotik-olsr/tools/configure-device.py
T
feedc0de 5bb6e0fe55
Check source / check (push) Successful in 16s
Initial version (not finished, work in progress)
2026-11-18 10:10:39 +01:00

172 lines
8.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Configure the experimental OLSR service through authenticated RouterOS REST."""
import argparse
import base64
import ipaddress
import json
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
OWNER = 'mikrotik-olsr'
class Router:
def __init__(self, url, username, password):
parsed = urllib.parse.urlsplit(url)
if parsed.scheme not in ('http', 'https') or not parsed.netloc or parsed.username or parsed.query or parsed.fragment:
raise ValueError('Use an http(s) router URL without credentials, query or fragment')
self.url = url.rstrip('/') + '/rest/'
self.auth = 'Basic ' + base64.b64encode((username + ':' + password).encode()).decode()
def api(self, path, method='GET', body=None):
request = urllib.request.Request(self.url + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={'Authorization': self.auth, 'Content-Type': 'application/json'})
try:
with urllib.request.urlopen(request, timeout=20) as response:
data = response.read()
return json.loads(data) if data else None
except urllib.error.HTTPError as error:
raise RuntimeError(f'{method} {path}: {error.read().decode()}') from error
def named(self, path, name):
return next((row for row in self.api(path) if row.get('name') == name), None)
def owned(self, path, name, values):
old = self.named(path, name)
if old and old.get('comment') != OWNER:
raise ValueError(f'{path}/{name} belongs to another configuration')
body = dict(name=name, comment=OWNER, **values)
return self.api(path + '/' + old['.id'] if old else path,
'PATCH' if old else 'PUT', body)
def shell(self, command):
return self.api('system/shell', 'POST', {'cmd': command}).get('ret', '')
def stop(self):
row = self.named('system/scheduler', 'OLSR')
if row:
if row.get('comment') != OWNER:
raise ValueError('OLSR scheduler belongs to another configuration')
self.api('system/scheduler/' + row['.id'], 'PATCH', {'disabled': 'true'})
self.shell('/pckg/option/bin/bash /pckg/olsr/bin/olsrctl stop')
for _ in range(20):
routes = self.api('ip/route')
remaining = any(row.get('comment') in ('OLSR', 'OLSR-link', '"OLSR link"') for row in routes)
private = self.shell('/pckg/option/bin/busybox ip route show table 201 proto 100')
if not remaining and not private:
return
time.sleep(1)
raise RuntimeError('OLSR shutdown timed out; left disabled. Check service logs.')
def file(self, name, contents):
old = self.named('file', name)
if old:
current = self.api('file/print', 'POST', {'.query': ['name=' + name], '.proplist': ['contents']})
if current and current[0].get('contents') == contents:
return
self.api('file/' + old['.id'] if old else 'file', 'PATCH' if old else 'PUT',
{'contents': contents} if old else {'name': name, 'contents': contents})
def settings(interface, address, prefixes, debug):
if not re.fullmatch(r'[A-Za-z0-9_.:-]+', interface):
raise ValueError('Interface name must contain only letters, digits, _, ., : or -')
address = str(ipaddress.IPv4Address(address))
networks = [ipaddress.IPv4Network(value, strict=True) for value in prefixes]
if not networks or any(network.prefixlen == 0 for network in networks):
raise ValueError('Specify accepted IPv4 networks; default routes are excluded')
allowed = ' || '.join(f'dst in {network}' for network in networks)
rule = (f'if (({allowed}) && bgp-communities includes 64513:698) {{ '
f'if (bgp-communities includes 64513:1) {{ set gw {interface}; set scope 10; '
'set scope-target 10; set comment OLSR-link; } else { '
f'set gw-interface {interface}; set scope-target 11; set comment OLSR; '
'} set distance 110; accept; } else { reject; }')
config = f'''DebugLevel {debug}
IpVersion 4
AllowNoInt no
MainIp {address}
Pollrate 0.05
UseHysteresis no
LinkQualityLevel 2
LinkQualityAlgorithm "etx_ff"
LinkQualityFishEye 0
Interface "@INTERFACE@"
{{
Mode "mesh"
IPv4Broadcast 255.255.255.255
}}
'''
return address, rule, config
def configure(router, args):
address, rule, config = settings(args.interface, args.address, args.accept_network or ['10.0.0.0/8'], args.debug)
interfaces = router.api('interface')
if not any(row.get('name') == args.interface for row in interfaces):
raise ValueError('Create the OLSR interface in RouterOS first')
if not any(row.get('interface') == args.interface and row.get('address', '').split('/')[0] == address
and row.get('disabled') != 'true' for row in router.api('ip/address')):
raise ValueError('Assign the node address to the selected interface in RouterOS first')
# Validate ownership before changing any configuration.
for path in ('system/scheduler', 'routing/bgp/instance', 'routing/bgp/connection'):
row = router.named(path, 'OLSR')
if row and row.get('comment') != OWNER:
raise ValueError(f'Existing {path}/OLSR belongs to another configuration')
filters = [row for row in router.api('routing/filter/rule') if row.get('chain') in ('OLSR-in', 'OLSR-out')]
if any(row.get('comment') != OWNER for row in filters):
raise ValueError('Existing OLSR filter chain contains foreign rules')
router.stop()
router.file('flash/olsrd.conf', config)
router.owned('routing/bgp/instance', 'OLSR', {'as': '64512', 'router-id': '127.0.0.1'})
for row in filters:
router.api('routing/filter/rule/' + row['.id'], 'DELETE')
for chain, text in [('OLSR-in', rule), ('OLSR-out', 'reject;')]:
router.api('routing/filter/rule', 'PUT', {'chain': chain, 'rule': text, 'comment': OWNER})
router.owned('routing/bgp/connection', 'OLSR', {'instance': 'OLSR', 'local.role': 'ebgp',
'local.address': '127.0.0.1', 'remote.address': '127.0.0.2/32', 'remote.as': '64513',
'remote.port': '1179', 'multihop': 'yes', 'listen': 'no', 'connect': 'yes',
'hold-time': '9s', 'keepalive-time': '3s', 'input.filter': 'OLSR-in', 'output.filter-chain': 'OLSR-out'})
router.owned('system/scheduler', 'OLSR', {'interval': '2s', 'start-time': 'startup',
'disabled': 'false' if args.enable else 'true', 'policy': 'read,write,policy,test,sensitive',
'on-event': '/system/shell cmd="/pckg/option/bin/bash /pckg/olsr/bin/olsrctl pulse"'})
print('Configured OLSR: ' + ('enabled' if args.enable else 'disabled; enable in OLSR > Service or System > Scheduler'))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--router', required=True, help='Router URL; use HTTPS when configured')
parser.add_argument('--username', default='admin')
parser.add_argument('--password-env', default='ROUTEROS_PASSWORD')
sub = parser.add_subparsers(dest='command', required=True)
config = sub.add_parser('configure')
config.add_argument('--interface', required=True)
config.add_argument('--address', required=True, help='Already assigned node IPv4 address')
config.add_argument('--accept-network', action='append', help='Repeat for each accepted network; default 10.0.0.0/8')
config.add_argument('--debug', type=int, choices=[0, 1], default=0)
config.add_argument('--enable', action='store_true')
sub.add_parser('disable')
sub.add_parser('logs')
sub.add_parser('status')
args = parser.parse_args()
if args.password_env not in os.environ:
parser.error(f'Set {args.password_env}; an explicitly empty value is allowed for a lab router')
router = Router(args.router, args.username, os.environ[args.password_env])
if args.command == 'configure':
configure(router, args)
elif args.command == 'disable':
router.stop()
print('OLSR disabled; native and private routes withdrawn')
elif args.command == 'logs':
print(router.shell('/pckg/option/bin/bash /pckg/olsr/bin/olsrctl logs'))
else:
routes = [r for r in router.api('ip/route') if r.get('comment') in ('OLSR', 'OLSR-link')]
print(json.dumps({'scheduler': router.named('system/scheduler', 'OLSR'),
'routes': len(routes), 'active': sum(r.get('active') == 'true' for r in routes)}, indent=2))
if __name__ == '__main__':
main()