You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.7 KiB
Python

#!/usr/bin/python3
import argparse
import librouteros
import progress.bar
import ssl
import os
import yaml
def connection( host, username = None, password = None, port = 8729 ):
if ':' in host:
( host, port ) = host.split( ":", 1 )
port = int( port )
kwargs = { 'username': username or os.environ.get( 'AUTOMONTY_USERNAME', None ),
'password': password or os.environ.get( 'AUTOMONTY_PASSWORD', None ),
'host': host,
'port': port,
}
kwargs[ 'ssl' ] = True
ssl_ctx = ssl.create_default_context()
ssl_ctx.check_hostname = False # XXX figure out how
ssl_option = 'CERT_REQUIRED'
ssl_ctx.verify_mode = getattr( ssl, ssl_option, ssl.CERT_REQUIRED )
ssl_ctx.set_ciphers( 'DHE-RSA-AES256-GCM-SHA384' )
kwargs[ 'ssl_wrapper' ] = ssl_ctx.wrap_socket
return librouteros.connect( **kwargs )
def connect_routers( config, args ):
rval = {}
if args:
with progress.bar.PixelBar( 'Connecting', max = len( args ) ) as bar:
for router in args:
rval[ router ] = connection( router )
bar.next()
elif config:
with progress.bar.PixelBar( 'Connecting', max = len( config ) ) as bar:
for ( name, kwargs ) in config.items():
if 'host' not in kwargs:
kwargs[ 'host' ] = name
rval[ name ] = connection( **kwargs )
bar.next()
return rval
def monty_check( args ):
for addr in args.addr:
for name, api in args.router.items():
for item in api( cmd ="/ip/address/print", detail = True ):
if item[ 'network' ] == addr:
print( name, ":", 'ENABLED' if not item[ 'disabled' ] else 'disabled', item[ 'interface' ], '#', item[ 'comment' ] )
def load_configuration():
try:
config = open( os.path.expanduser( '~/.automonty.yaml' ), 'r' )
except IOError:
return {}
return yaml.load( config.read(), yaml.SafeLoader )
def main():
config = load_configuration()
parser = argparse.ArgumentParser( prog = "automonty",
description = 'AutoMonty (re-)configures routers',
)
subparsers = parser.add_subparsers()
parser.add_argument( '--router', action = 'append' )
parser_check = subparsers.add_parser( 'check' )
parser_check.add_argument( 'addr', action = 'append' )
parser_check.set_defaults( func = monty_check )
args = parser.parse_args()
args.router = connect_routers( config = config.get( 'router', {} ), args = args.router )
args.func( args )
if __name__ == '__main__':
main()