Exemple #1
0
    def run( self, *args, **kwargs ):
        init_loggers( **kwargs )
        
        options = {}
        for i in ( 'profile', ):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        netconfig = NetConfig( kwargs['config'] )        

        # logging.error("EL %s " % (kwargs['device'],))
        for d in kwargs['device']:

            try:

                # get device
                device = netconfig.get( d, options=kwargs )
                netconfig.connect( device, **kwargs )     
                
                # do it
                delete_vlan_if_exists( device, int(kwargs['delete_vlan']), int(kwargs['other_vlan']) )
                
                
            except Exception,e:
                t = traceback.format_exc()
                logging.error("%s: %s\n%s" % (type(e),e,t))
Exemple #2
0
    def run( self, *args, **kwargs ):
        """
        plan:
          1) log onto device to determine current settings
          2) write new config partial to tftp
          3) upload new management config to switch
          4) try to log onto new device
        """
        init_loggers( **kwargs )
        
        options = {}
        for i in ( 'profile', ):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        netconfig = NetConfig( kwargs['config'] )        

        # logging.error("EL %s " % (kwargs['device'],))
        for d in kwargs['device']:

            try:
                
                # get device
                device = netconfig.get( d, options=kwargs )
                netconfig.connect( device, **kwargs )     
                # create
                create_vlan( device, **kwargs )
                # add vlans
                add_vlan_to_uplinks( device, **kwargs )

                
            except Exception,e:
                t = traceback.format_exc()
                logging.error("%s: %s\n%s" % (type(e),e,t))
Exemple #3
0
def pipe(hostname, netconfig_conf, mode, commands, options):

    data = []
    device = None
    try:
        netconfig = NetConfig(netconfig_conf)
        device = netconfig.get(hostname, options=options)
        netconfig.connect(device, **options)
        # disable buffering
        device.prompt.terminal_buffer(0)

        if mode == 'enable':
            device.prompt.mode_enable()
        elif mode == 'config':
            device.prompt.mode_config()

        for cmd, d in execute_commands(device, *commands):
            data.append({
                'command': cmd,
                'output': d['output'],
                'error': d['error']
            })

    except Exception, e:
        logging.debug("Err: %s: %s\n%s" % (type(e), e, traceback.format_exc()))
        error = str(e)
Exemple #4
0
def api(hostname, netconfig_conf, mutex, kwargs, options, quiet):
    device = None
    error = None
    res = []
    if not quiet:
        logging.info("%s" % hostname)
    try:
        netconfig = NetConfig(netconfig_conf, mutex=mutex)
        device = netconfig.get(hostname, options=options)
        netconfig.connect(device, **options)

        component = device.get_component(kwargs['component'])
        # logging.info("C: %s" % component)
        # component lists allow __iter__
        # if kwargs['arg']:
        #     logging.info( "%s" %  component( kwargs['arg'] ) )
        # else:
        done = component()
        if isinstance(done, bool):
            done = [True]
        for d in done:
            # logging.info("%s" % (d,))
            # for i in d:
            res.append(d)
    except Exception, e:
        logging.error("Err: %s: %s %s" % (hostname, type(e), e))
        error = str(e)
Exemple #5
0
    def run( self, *args, **kwargs ):
        """
        plan:
          1) log onto device to determine current settings
          2) write new config partial to tftp
          3) upload new management config to switch
          4) try to log onto new device
        """
        init_loggers( **kwargs )
        
        options = {}
        for i in ( 'profile', ):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        netconfig = NetConfig( kwargs['config'] )        

        # logging.error("EL %s " % (kwargs['device'],))
        for d in kwargs['device']:

            try:
                
                # get device
                device = netconfig.get( d, options=kwargs )
                netconfig.connect( device, **kwargs )        

                # create vlan
                if not create_vlan( device, **kwargs ):
                    raise Exception, 'could not create vlan'
                    
                # add to uplinks and add svi
                if not add_vlan_to_uplinks( device, **kwargs ):
                    raise Exception, 'did not add vlan to any new uplinks'
                    
                # prepare the svi
                if not setup_management_ip( device, **kwargs ):
                    raise Exception, 'could not create new svi'
                        
                # switch the old and new svi's
                

                # # change default gateway
                # try:
                #     device.prompt.ask( 'ip default-gateway %s' % (kwargs['new_gateway'],), cursor=device.prompt.cursor('mode','config'), timeout=2 )
                # except Exception, e:
                #     logging.debug("required timeout... %s %s" % (type(e),e))
                
                # we're now kicked out because of change in default gateway, so try to reconnect to new ip      
                # new_device = netconfig.get( kwargs['new_ip'], options=kwargs, profiles=[ 'ios' ], use_cache=True )
                # netconfig.connect( new_device )

                # if 'old_vlan' in kwargs:
                #     new_device.prompt.ask('no interface vlan %s' % (kwargs['old_vlan'],))
                # new_device.system.config.commit()
            
            
            except Exception,e:
                logging.error("%s: %s" % (type(e),e))
Exemple #6
0
    def run(self, *args, **kwargs):

        init_loggers(**kwargs)

        options = {}
        for i in ('profile', 'port', 'prime', 'password', 'username',
                  'cache_group'):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]

        netconfig = NetConfig(kwargs['config'])
        device = None
        try:

            device = netconfig.get(kwargs['device'], options=options)
            netconfig.connect(device, **options)

            # init
            if kwargs['no_user_check']:
                try:
                    users = {}
                    t = device.system.users.get()
                    if not t == None:
                        for i in t:
                            if not 'user' in i:
                                i['user'] = '******'
                            if not i['user'] in users:
                                users[i['user']] = []
                            users[i['user']].append(i['line'])
                        for k, v in users.iteritems():
                            print('WARNING: %s is connected on %s' %
                                  (k, ', '.join(v)))
                except:
                    pass

            if device.ports.conf_sync:
                print("NOTICE: device is using conf sync profile %s" %
                      device.ports.conf_sync)

            # set up enable acess
            if kwargs['enable']:
                device.prompt.mode_enable()

            device.prompt.mode_interactive()
        except Exception, e:
            logging.error("%s: %s" % (type(e), e))
Exemple #7
0
    def run(self, *args, **kwargs):

        init_loggers(**kwargs)

        # organise by device
        by_device = {}
        for i in parse_file(**kwargs):
            logging.debug(" >= %s" % i)
            if not i['device'] in by_device:
                by_device[i['device']] = []
            by_device[i['device']].append(i)

        options = {}
        for i in ('profile', ):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        netconfig = NetConfig(kwargs['config'])

        for d in by_device:

            dev = None
            try:

                dev = netconfig.get(d)
                netconfig.connect(dev)

                # disable buffering
                dev.prompt.terminal_buffer(0)

                for d, port, action, data in set_ports(dev, by_device[d]):
                    if action == True:
                        logging.info(" updated")
                    elif action == None:
                        logging.info(" no changes required")
                    else:
                        raise Exception("%s %s failed: %s" %
                                        (d, port['port'], data))

            except Exception, e:
                t = traceback.format_exc()
                logging.error("%s: %s\n%s" % (type(e), e, t))
            finally:
Exemple #8
0
def backup( hostname, netconfig_conf, mutex, storage_path, options, quiet, write_config, commit ):
    # logging.error("hostname: %s, netconfig=%s, storage=%s" % (hostname,netconfig_conf,storage_path))
    res, person, diff, error = None, None, {}, None
    device = None
    config = None
    if not quiet:
        logging.info("%s"%hostname)
    try:
        netconfig = NetConfig( netconfig_conf, mutex=mutex )
        storage = FileStore( path=storage_path )
        device = netconfig.get( hostname, options=options )
        netconfig.connect( device, **options )
        if commit:
            try:
                device.system.config.commit()
            except Exception,e:
                logging.info("%s: %s" % (hostname,e) )
                device.prompt.ask("", fail_okay=True)
        config = device.system.config.get()
        res, person, diff = storage.insert( hostname, config, commit=write_config )
Exemple #9
0
    def run(self, *args, **kwargs):

        init_loggers(**kwargs)

        options = {}
        for i in ('profile', ):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        netconfig = NetConfig(kwargs['config'])

        for d in get_array(kwargs['device']):

            try:
                # get device
                device = netconfig.get(d, options=options)
                netconfig.connect(device, **options)

                # reload device and make sure it comes back!
                msg_per_loop = '.'
                for e in reload_and_monitor(netconfig,
                                            device,
                                            options=options,
                                            wait=int(kwargs['wait']),
                                            delay=int(kwargs['delay']),
                                            message_per_loop=msg_per_loop):
                    if isinstance(e, str):
                        if e == msg_per_loop:
                            print "%s" % (e, ),
                        else:
                            print "%s" % (e, )
                    else:
                        print
                        device = e

                logging.info("%s" % (device.system.get(), ))

            except Exception, e:
                logging.error("%s: %s" % (type(e), e))
Exemple #10
0
def port_baseline(hostname,
                  netconfig_conf,
                  mutex,
                  interfaces,
                  baselines,
                  exceptions,
                  options,
                  fix,
                  fix_only=None):
    """
    if len(fix_only) == 0, assume fix all
    """

    device = None
    deltas = []

    if fix_only == None:
        fix_only = []

    try:

        logging.info('processing %s' % (hostname, ))
        netconfig = NetConfig(netconfig_conf, mutex=mutex)
        device = netconfig.get(hostname, options=options)
        netconfig.connect(device, **options)
        device.prompt.terminal_buffer()

        # find all the ports
        ports = []
        if interfaces == None:
            ports = device.ports.filter()
        else:
            for i in interfaces:
                ports.append(device.ports.get(i))

        # do something with each port
        for p in ports:

            profile = None
            delta = {}
            multiple = False
            try:
                logging.info('analysing %s %s' % (hostname, p['port']))
                profile, delta, multiple = compare_to_baselines(
                    device, p, baselines, exceptions)
            except Exception, e:
                logging.warn("%s\t%s: %s" % (hostname, p['port'], e))

            # logging.info("%-16s\t%-9s\t%26s%s\tdelta: %s" % (hostname, p['port'], profile, "*" if multiple else '', report_baseline_delta(delta),))

            fixed = False if len(delta.keys()) else None
            fix_this = True if len(
                fix_only) == 0 or profile in fix_only else False
            logging.debug(" fix: %s / %s" % (fix_this, fix_only))
            if profile and len(delta.keys()) and fix and fix_this:
                try:
                    logging.info('fixing %s %s with %s' %
                                 (hostname, p['port'], profile))
                    baseline = {}
                    for k, d in delta.iteritems():
                        if not 'baseline' in d:
                            raise Exception, 'profile %s does not contain a baseline stanza' % (
                                profile, )
                        baseline[k] = d['baseline']
                    # always add the type to force cleaning of the configs
                    baseline['type'] = p['type']
                    baseline['port'] = p['port']
                    fixed, _tmp = device.ports.set(port=p,
                                                   port_object=baseline,
                                                   initial_check=False)
                except Exception, e:
                    logging.error(
                        "Err: %s\n%s" %
                        ('could not fix %s' % p, traceback.format_exc()))

            report = True
            if len(fix_only) and not profile in fix_only:
                report = False

            if report:
                deltas.append({
                    'physical_port': p['port'],
                    'profile': profile,
                    'delta': delta,
                    'fixed': fixed
                })