示例#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))
示例#2
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]

        devices = get_array(kwargs['device'])
        if kwargs['randomise']:
            shuffle(devices)

        # get lock
        manager = Manager()
        mutex = manager.Lock()

        # map/reduce
        target_args = [
            kwargs['config'], mutex, kwargs, options, kwargs['quiet']
        ]
        res = self.map(api,
                       devices,
                       num_workers=kwargs['workers'],
                       target_args=target_args)
        for hostname, status in self.fold(devices, res):
            # don't bother if not changed
            logging.info("%s: %s" % (hostname, status))
示例#3
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))
示例#4
0
    def _run( self, write_config=True, **kwargs):

        init_loggers(**kwargs)

        num_workers = int(kwargs['workers'])
        options = {}
        for i in ( 'password', 'username', 'cache_group' ):
            if kwargs[i]:
                options[i] = kwargs[i]
        
        devices = get_array( kwargs['device'] )
        if kwargs['randomise']:
            shuffle(devices)

        # get lock
        manager = Manager()
        mutex = manager.Lock()
        
        # map/reduce
        target_args = [ kwargs['config'], mutex, kwargs['file_store_path'], options, kwargs['quiet'], True, kwargs['commit'] ]
        res = self.map( backup, devices, num_workers=kwargs['workers'], target_args=target_args )
        for hostname, status in self.fold( devices, res, ignore=kwargs['donotreport'] ):
            config = status['config']
            del status['config']
            yield hostname, config, status

        return
示例#5
0
 def run(self, *args, **kwargs):
     init_loggers(**kwargs)
     self.netconfig = NetConfig(kwargs['config'])
     options = {}
     rename_ap_on_wlc(kwargs['controller'], kwargs['ap_name'],
                      kwargs['ap_mac_address'], self.netconfig, options,
                      kwargs['quiet'], kwargs['apgroup'], kwargs['dry_run'])
示例#6
0
    def run(self, *args, **kwargs):
        init_loggers(**kwargs)
        self.netconfig = NetConfig(kwargs['config'])

        # get lock
        manager = Manager()
        mutex = manager.Lock()

        fw = FirmwareHelper(kwargs['settings'].server,
                            kwargs['settings'].firmware)

        options = {}
        target_args = [
            kwargs['config'], mutex, fw, options, kwargs['quiet'],
            kwargs['apgroup'], kwargs['dry_run']
        ]
        res = self.map(migrate,
                       kwargs['device'],
                       num_workers=kwargs['workers'],
                       target_args=target_args)
        for hostname, status in self.fold(kwargs['device'], res):
            msg = ''
            # if status['error']:
            #     msg = status['error']
            # else:
            msg = status
            print "%s\t%s" % (hostname, msg)
示例#7
0
    def run(self, *args, **kwargs):
        init_loggers(**kwargs)
        nc = NetConfig(kwargs['config'])

        wlc = nc.get(kwargs['device'])
        wlc.connect()

        # 1) get list of all registered ap's
        aps = []
        for i in wlc.tell('show ap summary'):
            m = search(
                '(?P<name>\S+)\s+\d+\s+(?P<model>\S+)\s+(?P<mac>\S+)\s+', i)
            if m:
                d = m.groupdict()
                aps.append(d)
        logging.debug("%s" % (aps, ))

        # 2) for each, determine for each 'slot' it's bssid
        for ap in aps:
            for slot in kwargs['slots']:
                for i in wlc.tell('show ap wlan %s %s' % (slot, ap['name'])):
                    m = search(
                        r'(?P<wlan_id>\d+)\s+(?P<interface>\S+)\s+(?P<bssid>\S+)\s*$',
                        i)
                    if m:
                        d = m.groupdict()
                        ap[slot] = d['bssid']
        logging.debug("%s" % (aps, ))

        # 3) report!
        print "# ap\t%s" % '\t'.join(s for s in kwargs['slots'])
        for ap in aps:
            bssids = "%s" % '\t'.join([ap[s] for s in kwargs['slots']])
            print "%s\t%s" % (ap['name'], bssids)
示例#8
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))
示例#9
0
    def run(self, *args, **kwargs):
        init_loggers(**kwargs)

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

        report = {}

        # get lock
        manager = Manager()
        mutex = manager.Lock()

        devices = get_array(kwargs['device'])

        fix_only = []
        if kwargs['fix_only']:
            fix_only = [i[0] for i in kwargs['fix_only']]

        target_args = [
            kwargs['config'], mutex, kwargs['interfaces'],
            kwargs['baselines']['BASELINES'],
            kwargs['baselines']['EXCEPTIONS'], options, kwargs['fix'], fix_only
        ]
        # logging.debug("TARGET: %s" % (target_args,))
        res = self.map(port_baseline,
                       devices,
                       num_workers=kwargs['workers'],
                       target_args=target_args)
        for hostname, status in self.fold(devices, res):
            for d in status['deltas']:
                fixed = '-'
                if d['fixed'] == True:
                    fixed = 'Y'
                elif d['fixed'] == False:
                    fixed = 'N'
                profile = d['profile']
                if profile == None:
                    profile = 'UNKNOWN'
                delta = report_baseline_delta(d['delta'])
                output = False if kwargs[
                    'delta_only'] == True and delta == {} else True
                if output:
                    print("%-16s\t%-9s\t%26s\t%s\t%s" %
                          (hostname, d['physical_port'], d['profile'], fixed,
                           delta))
                    if not hostname in report:
                        report[hostname] = {}
                    report[hostname][d['physical_port']] = {
                        'profile': d['profile'],
                        'delta': d['delta']
                    }

        disk(report, kwargs['report_dir'])
示例#10
0
    def run( self, *args, **kwargs):

        init_loggers(**kwargs)
        
        frm = DeviceConfigurations( )
        config_class = frm.get_config_obj( kwargs['type'] )
        frm.setConfig( kwargs['from'], config_type=kwargs['type'] )
        
        to = DeviceConfigurations( )
        to.setConfig( kwargs['to'], config_type=kwargs['type'] )

        print pformat( frm.diff( to ) )
示例#11
0
    def setup(self, *args, **kwargs):

        init_loggers(**kwargs)

        self.fw = FirmwareHelper(kwargs['settings'].server,
                                 kwargs['settings'].firmware)
        self.group = kwargs['group']
        self.release = kwargs['release']

        options = {}
        for i in ('profile', ):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        self.netconfig = NetConfig(kwargs['config'])
        self.options = options
示例#12
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))
示例#13
0
    def run(self, *args, **kwargs):
        init_loggers(**kwargs)
        options = {}
        for i in ('profile', 'password'):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        self.netconfig = NetConfig(kwargs['config'])
        self.options = options

        results = {}

        target_args = [kwargs['config'], options, kwargs['quiet']]
        res = self.map(eth_mac,
                       kwargs['device'],
                       num_workers=kwargs['workers'],
                       target_args=target_args)
        for hostname, mac in self.fold(kwargs['device'], res):
            print "%s\t%s" % (hostname, mac)
示例#14
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:
示例#15
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))
示例#16
0
    def run(self, *args, **kwargs):
        init_loggers(**kwargs)

        # find out all known redact matches required
        scrubs = []
        for m in all_config_klasses():
            k = underscore_to_camelcase(m)
            c = 'netconfig.backup.configuration.%s' % camel_case_to_underscore(
                k)
            try:
                d = import_module(c, k)
                f = '%s.%s' % (c, k)
                s = create_klass(f).scrub_matches
                # logging.debug("> %s: %s" % (f,s))
                for i in s:
                    scrubs.append(i)
            except:
                pass
        # logging.error("scrubs: %s" % scrubs)

        for f in kwargs['files']:
            logging.debug("processing %s" % (f, ))

            fn = open(f, 'r')
            this = []
            for l in fn.readlines():
                this.append(l.rstrip())

            conf = Configuration(this)
            conf.scrub_matches = scrubs

            if 'replace' in kwargs and kwargs['replace']:
                with open(f, 'w') as fh:
                    for i in conf.scrub(this):
                        fh.write(i + "\n")
            else:
                for i in conf.scrub(this):
                    print i
示例#17
0
    def run(self, *args, **kwargs):

        init_loggers(**kwargs)

        # get list of commands from stdin
        commands = [l.rstrip() for l in sys.stdin]

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

        mode = None
        # set up enable acess
        if kwargs['enable']:
            mode = 'enable'
        if kwargs['confterm']:
            mode = 'config'

        devices = get_array(kwargs['device'])

        target_args = [kwargs['config'], mode, commands, options]
        res = self.map(pipe,
                       devices,
                       num_workers=kwargs['workers'],
                       target_args=target_args)
        for hostname, status in self.fold(devices, res):
            for s in status:

                if kwargs['echo']:
                    print "! %s: %s" % (hostname, s['command'])

                output = s['output']
                # print "%s: %s" % (status,output)
                if kwargs['report']:
                    print "%s\t%s" % (hostname, '\n'.join(output).strip())
                else:
                    print '\n'.join(output)
示例#18
0
    def run(self, *args, **kwargs):
        init_loggers(**kwargs)
        options = {}
        for i in ('profile', 'password'):
            if i in kwargs and kwargs[i]:
                options[i] = kwargs[i]
        self.netconfig = NetConfig(kwargs['config'])
        self.options = options

        results = {}

        target_args = [kwargs['config'], options, kwargs['quiet']]
        res = self.map(bssid,
                       kwargs['device'],
                       num_workers=kwargs['workers'],
                       target_args=target_args)
        for hostname, status in self.fold(kwargs['device'], res):
            msg = ''
            if status['error']:
                msg = status['error']
            else:
                msg = '\t'.join(v['bia']
                                for k, v in status['interfaces'].iteritems())
            print "%s\t%s" % (hostname, msg)