def do_login(): apicUrl = 'https://198.18.133.200' loginSession = LoginSession(apicUrl, 'admin', 'C1sco12345') active_session = MoDirectory(loginSession) active_session.login() # print loginSession.cookie return active_session
def apic_login(self): """Login to APIC""" lsess = LoginSession('https://' + self.host, self.user, self.password) modir = MoDirectory(lsess) modir.login() print lsess.cookie return modir
def login_gui(): root =Tk() root.minsize(700,400) root.title("Cisco APIC Login") ment_1 = StringVar() ment_2 = StringVar() ment_3 = StringVar() label_1 = Label(root, text = "ip address").pack() mentry = Entry(root,textvariable = ment_1 ).pack() label_2 = Label(root, text = "username").pack() mentry_2 = Entry(root,textvariable = ment_2 ).pack() label_3 = Label(root, text = "password").pack() mentry_3 = Entry(root, show="*", width=20, bg = "gray",textvariable = ment_3 ).pack() frame = Frame(root) frame.pack() button = Button(frame,text = "ok", command = lambda: close_device(root), bg = "gray",fg = "black") button.pack() root.mainloop() apicIP = ment_1.get() user = ment_2.get() pw = ment_3.get() try: ## login to APIC apicUrl = 'https://'+apicIP # defaulting to https loginSession = LoginSession(apicUrl, user, pw,secure=False) moDir = MoDirectory(loginSession) moDir.login() except: print "the username and/or password you entered is incorrect" return apicUrl,moDir
def apic_login(hostname, username, password): """Login to APIC""" epoint = EndPoint(hostname, secure=False, port=80) lsess = LoginSession(username, password) modir = MoDirectory(epoint, lsess) modir.login() return modir
class APICHandler(): def __init__(self): self.host = 'https://192.168.1.100' self.user = '******' self.pwd = 'GDTlabs123' self.session = None def do_login(self): loginSession = LoginSession(self.host, self.user, self.pwd) self.session = MoDirectory(loginSession) self.session.login() # print loginSession.cookie return self.session def target_location_lookup(self, active_session, location): change_location = self.session.lookupByDn(location) return change_location def update_config(self, active_session, change_location): configReq = ConfigRequest() configReq.addMo(change_location) self.session.commit(configReq) def logout(self, active_session): self.session.logout()
def moDir(request): url, user, password, secure = request.param secure = False if secure == 'False' else True session = LoginSession(url, user, password, secure=secure, requestFormat='json') md = MoDirectory(session) md.login() return md
def login_cli(apicUrl, user, password): try: loginSession = LoginSession(apicUrl,user,password) moDir = MoDirectory(loginSession) moDir.login() except: print "the username and/or password you entered is incorrect" return moDir
def apic_login(self): """Login to APIC""" if not self.host.startswith(('http', 'https')): self.host = 'https://' + self.host lsess = LoginSession(self.host, self.user, self.password) modir = MoDirectory(lsess) modir.login() self.modir = modir
def apic_login(hostname, username, password): url = "http://" + hostname sess = LoginSession(url, username, password) modir = MoDirectory(sess) try: modir.login() except: print 'Login error' exit(1) return modir
def main(host, username, password, node, interface): apic = "https://%s" % host print("Connecting to APIC : %s" % apic) moDir = MoDirectory(LoginSession(apic, username, password)) moDir.login() nodeblk_dict = defaultdict(list) nodeblk_list = moDir.lookupByClass("infraNodeBlk") node_found = False for nodeblkMO in nodeblk_list: if int(nodeblkMO.from_) > int(node) or int(nodeblkMO.to_) < int(node): continue else: node_found = True node_dn = '/'.join(str(nodeblkMO.dn).split('/')[:3]) nodeblk_dict[node_dn].append(str(nodeblkMO.dn)) if node_found is False: print("Switch Node {", node, "} DOES NOT exist!") exit(1) if debug is True: print("Printing nodeblk_dict.......") for key, value in nodeblk_dict.items(): print(key, ":", value) print("-----------------------------") port_dict = {} RsAccPortP_list = moDir.lookupByClass("infraRsAccPortP") for RsAccPortPMO in RsAccPortP_list: portk = str(str(RsAccPortPMO.dn).split('[')[1])[:-1] port_dict[portk] = '/'.join(str(RsAccPortPMO.dn).split('/')[:3]) if debug is True: print("Printing port_dict.......") for key, value in port_dict.items(): print(key, ":", value) print("-----------------------------") Portblk_list = moDir.lookupByClass("infraPortBlk") interface_found = False for temp_port in Portblk_list: if int(interface) == int(temp_port.fromPort): interface_found = True intP = '/'.join(str(temp_port.dn).split('/')[:3]) if port_dict[intP] in nodeblk_dict: m = re.match("accportprof-(?P<first>.+)", str(temp_port.dn).split('/')[2]) print("Interface Profile Name => ", m.group("first")) print("Interface Profile DN =>", intP) n = re.match("nprof-(?P<first>.+)", str(port_dict[intP]).split('/')[2]) print("Switch Node Profile Name =>", n.group("first")) print("Switch Node Profile DN =>", port_dict[intP]) if interface_found is False: print("Interface {", interface, "} DOES NOT exist!") exit(1)
def main(host, username, password, tenant): apic = "https://%s" % host print("Connecting to APIC : %s" % apic) moDir = MoDirectory(LoginSession(apic, username, password)) moDir.login() dn_name = "uni/tn-" + tenant print(dn_name) dnq = DnQuery(dn_name) dnq.subtree = 'children' tenantMO = moDir.query(dnq) for bdMO in tenantMO.BD: print("BD NAME => {", bdMO.name, "}")
def mo_apic_login(hostname, username, password): # Login to the APIC using cobra module url = hostname sess = LoginSession(url, username, password) modir = MoDirectory(sess) try: modir.login() except: print 'Login error' exit(1) return modir
def test_cleanup_user(self, apics, certobject, userobject): apic = apics[0] user = apics[2] password = apics[3] secure = False if apics[1] == 'False' else True userobject.aaaUser.delete() session = LoginSession(apic, user, password, secure=secure) moDir = MoDirectory(session) moDir.login() cr = ConfigRequest() cr.addMo(userobject.aaaUser) r = moDir.commit(cr) assert r == []
def apic_login(hostname, username, password): ''' Function that creates a session to communicate with the APIC ''' url = "https://" + hostname login_session = cobra.mit.session.LoginSession(url, username, password) modir = MoDirectory(login_session) print 'connecting to ' + hostname try: modir.login() except: print 'Login error' exit(1) return modir
def login_cli(apicIP,userID,pw): try: ## login to APIC if apicIP == False: apicIP = raw_input("\nWhat is the APIC IP ? Format xxx.xxx.xxx.xxx\n") userID = raw_input("\nUser ID: ") pw = getpass.getpass().strip("/\r") apicUrl = 'https://'+apicIP # defaulting to https loginSession = LoginSession(apicUrl, userID, pw,secure=False) moDir = MoDirectory(loginSession) moDir.login() except: print "the username and/or password you entered is incorrect" return apicUrl,moDir
def get_tenant(): with open("/home/app/data/logs.txt", "a") as log_file: log_file.write("==================================================" + "\n") log_file.write("Received API Request from Client. Sending Response" + "\n") log_file.write("==================================================" + "\n") apicUrl = 'https://172.17.0.1/' loginSession = createCertSession() #loginSession = LoginSession(apicUrl, 'admin', 'ins3965!') #loginSession = cobra.mit.session.LoginSession('https://10.22.47.171', 'admin', 'ins3965!') moDir = MoDirectory(loginSession) moDir.login() tenantMo = moDir.lookupByClass('fvTenant'); moDir.logout() #print json.dumps(tenantMo) return respFormatJsonMos(tenantMo, tenantMo.totalCount)
def main(host, username, password, pool_name, from_vlan, to_vlan): apic = "https://%s" % host print("Connecting to APIC : %s" % apic) moDir = MoDirectory(LoginSession(apic, username, password)) moDir.login() topMO = moDir.lookupByDn('uni') moDir.lookupByDn infraInfra = cobra.model.infra.Infra(topMO) fvnsVlanInstP = VlanInstP(infraInfra,name=pool_name, allocMode="static") temp_from_vlan = "vlan-" + from_vlan temp_to_vlan = "vlan-" + to_vlan fvnsEncapBlk = EncapBlk(fvnsVlanInstP, temp_from_vlan, temp_to_vlan) print(toXMLStr(topMO)) c = ConfigRequest() c.addMo(infraInfra) moDir.commit(c)
def main(host, username, password, tenant): apic = "https://%s" % host print("Connecting to APIC : %s" % apic) moDir = MoDirectory(LoginSession(apic, username, password)) moDir.login() t_obj_list = moDir.lookupByClass("fvTenant") for t_mo in t_obj_list: print("Tenant name =>",t_mo.dn) if t_mo.name == tenant: bd_list = moDir.lookupByClass("fvBD", t_mo.dn) for mo in bd_list: print("NAME: {:10s}".format(mo.name)) print("DN: {:10s}".format(mo.dn)) print("MAC: {:10s}".format(mo.mac)) print("UID: {:10s}".format(mo.uid)) print("arpFlood: {:10s}".format(mo.arpFlood)) print("MUT: {:10s}".format(mo.mtu)) print() return
def test_tn_cleanup(self, apics, certobject, userobject): if userobject.user == 'rouser': return apic = apics[0] user = apics[2] password = apics[3] secure = False if apics[1] == 'False' else True uni = Uni('') fvTenant = Tenant(uni, name='t') fvTenant.delete() fvBD = BD(fvTenant, 't-bd') fvBD.delete() fvAp = Ap(fvTenant, 't-app') fvAp.delete() session = LoginSession(apic, user, password, secure=secure) moDir = MoDirectory(session) moDir.login() cr = ConfigRequest() cr.addMo(fvTenant) r = moDir.commit(cr) assert r == []
def apic_login_cobra(hostname, username, password): """Login to APIC""" lsess = LoginSession('http://'+hostname, username, password) modir = MoDirectory(lsess) modir.login() return modir
def apic_logon(url, username, password): my_session = LoginSession(url, username, password) modir_local = MoDirectory(my_session) modir_local.login() return modir_local
def apic_login(self): """Login to APIC""" lsess = LoginSession('https://' + self.host, self.user, self.password) modir = MoDirectory(lsess) modir.login() self.modir = modir
def apic_login_cobra(hostname, username, password): """Login to APIC""" lsess = LoginSession('http://' + hostname, username, password) modir = MoDirectory(lsess) modir.login() return modir
def home(): with open("/home/app/data/logs.txt", "a") as log_file: log_file.write("==================================================" + "\n") log_file.write("Received API Request from Client. Sending Response" + "\n") log_file.write("==================================================" + "\n") reply = None try: apicUrl = 'https://172.17.0.1/' loginSession = createCertSession() #loginSession = cobra.mit.session.LoginSession('https://10.22.47.171', 'admin', 'ins3965!') moDir = MoDirectory(loginSession) moDir.login() tableList = [] #row = ('TN', 'AP/L2OUT', 'EPG/InstP', 'CEP', 'IP', 'Type', 'PATH', 'PORT', 'POD', 'ENCAP', 'BD:CTX') #tableList.append(row) try: row ={} q = ClassQuery('fvCEp') q.subtree = 'children' tenantMo = moDir.query(q) except cobra.mit.request.QueryError as e: log('Reason: ' + e.reason) log('Error: ' + e.error) log('HTTP code: ' + e.httpCode) log(traceback.format_exc()) data = {} for mo in tenantMo: for child in mo.rscEpToPathEp: #print child.dn ip = mo.ip tn, ap, epg, cep, varPod, varStrPath, varStrPort = tDnToPath(child.dn) if 'protpaths' in child.tDn: portType = 'vPC' elif 'paths' in child.tDn and 'eth' in child.tDn: portType = '-' else: portType = 'PC' encap = (mo.encap).split('-')[1] #if args.macSearch: bd,ctx = getAncestorDnStrFromDnString(md, str(mo.dn), 1) #else: bd='-'; ctx='-' bd='-'; ctx='-' #row = (tn,ap,epg,cep,mo.ip,portType,varStrPath,varStrPort,varPod,encap,'%s:%s' %(bd,ctx)) row = { "tn": tn, "ap/l2out":ap, "epg":epg, "cep":cep, "ip":mo.ip, "type":portType, "path":varStrPath, "port":varStrPort, "pod":varPod, "encap":encap, "bd":"-:-" } tableList.append(row) #data[child.tDn]= row moDir.logout() #print json.dumps(data) #return render_template('home.html', table=tableList) #return respFormatJsonMos(data, len(data)) log(tableList) reply = jsonify({'results': tableList}) except Exception as e: log(traceback.format_exc()) return reply
def main(host, port, user, password): # CONNECT TO APIC print('Initializing connection to APIC...') apicUrl = 'http://%s:%d' % (host, port) moDir = MoDirectory(LoginSession(apicUrl, user, password)) moDir.login() # Get the top level Policy Universe Directory uniMo = moDir.lookupByDn('uni') uniInfraMo = moDir.lookupByDn('uni/infra') # Create Vlan Namespace nsInfo = VMM_DOMAIN_INFO['namespace'] print("Creating namespace %s.." % (nsInfo['name'])) fvnsVlanInstPMo = VlanInstP(uniInfraMo, nsInfo['name'], 'dynamic') #fvnsArgs = {'from': nsInfo['from'], 'to': nsInfo['to']} EncapBlk(fvnsVlanInstPMo, nsInfo['from'], nsInfo['to'], name=nsInfo['name']) nsCfg = ConfigRequest() nsCfg.addMo(fvnsVlanInstPMo) moDir.commit(nsCfg) # Create VMM Domain print('Creating VMM domain...') vmmpVMwareProvPMo = moDir.lookupByDn('uni/vmmp-VMware') vmmDomPMo = DomP(vmmpVMwareProvPMo, VMM_DOMAIN_INFO['name']) vmmUsrMo = [] for usrp in VMM_DOMAIN_INFO['usrs']: usrMo = UsrAccP(vmmDomPMo, usrp['name'], usr=usrp['usr'], pwd=usrp['pwd']) vmmUsrMo.append(usrMo) # Create Controllers under domain for ctrlr in VMM_DOMAIN_INFO['ctrlrs']: vmmCtrlrMo = CtrlrP(vmmDomPMo, ctrlr['name'], scope=ctrlr['scope'], hostOrIp=ctrlr['ip']) # Associate Ctrlr to UserP RsAcc(vmmCtrlrMo, tDn=vmmUsrMo[0].dn) # Associate Domain to Namespace RsVlanNs(vmmDomPMo, tDn=fvnsVlanInstPMo.dn) vmmCfg = ConfigRequest() vmmCfg.addMo(vmmDomPMo) moDir.commit(vmmCfg) print("VMM Domain Creation Completed.") print("Starting Tenant Creation..") for tenant in TENANT_INFO: print("Creating tenant %s.." % (tenant['name'])) fvTenantMo = Tenant(uniMo, tenant['name']) # Create Private Network Ctx(fvTenantMo, tenant['pvn']) # Create Bridge Domain fvBDMo = BD(fvTenantMo, name=tenant['bd']) # Create association to private network RsCtx(fvBDMo, tnFvCtxName=tenant['pvn']) # Create Application Profile for app in tenant['ap']: print('Creating Application Profile: %s' % app['name']) fvApMo = Ap(fvTenantMo, app['name']) # Create EPGs for epg in app['epgs']: print("Creating EPG: %s..." % (epg['name'])) fvAEPgMo = AEPg(fvApMo, epg['name']) # Associate EPG to Bridge Domain RsBd(fvAEPgMo, tnFvBDName=tenant['bd']) # Associate EPG to VMM Domain RsDomAtt(fvAEPgMo, vmmDomPMo.dn) # Commit each tenant seperately tenantCfg = ConfigRequest() tenantCfg.addMo(fvTenantMo) moDir.commit(tenantCfg) print('All done!')
class cobra_apic_base: def __init__(self): self.session = None self.moDir = None self.configReq = None self.uniMo = None """ Authentication """ def login(self, url, user, password): """ Login to the APIC :param url: :param user: :param password: :return: """ self.apic_url = url self.apic_user = user self.session = LoginSession(url, user, password) self.moDir = MoDirectory(self.session) self.moDir.login() self.configReq = ConfigRequest() self.uniMo = self.moDir.lookupByDn('uni') def logout(self): """ Logout from the APIC :return: """ self.moDir.logout() """ Commits """ def commit(self, commit_object): """ Commits object changes to controller :param commit_object: :return: """ self.configReq = ConfigRequest() self.configReq.addMo(commit_object) self.moDir.commit(self.configReq) """ Queries """ def query_child_objects(self, dn_query_name): """ Retrieve the object using the dn and return all the children under it :param dn_query_name: dn of the management object :return: """ dn_query = DnQuery(dn_query_name) dn_query.queryTarget = QUERY_TARGET_CHILDREN child_mos = self.moDir.query(dn_query) return child_mos """ Generic Deletes """ def delete_dn_by_pattern(self, dn_object_list, dn_pattern, recursive): """ Travers a dn list and compare each member with a pattern. If there is a match that object will be removed. If recursive is true, the algorithm will also do a recursive look for the children of each object looking for the pattern: will stop only when there is no more children to look for. :param dn_object_list: :param dn_pattern: :param recursive: :return: """ for dn_object in dn_object_list: if dn_pattern in str(dn_object.dn): try: self.delete_by_dn(str(dn_object.dn)) except CommitError as e: print 'Could not delete ' + str( dn_object.dn) + ' -> ' + str(e) elif recursive: children = self.query_child_objects(dn_object.dn) if children is not None: self.delete_dn_by_pattern(children, dn_pattern, recursive) def delete_by_dn(self, dn_name): """ Retrieve a mo and it removes it from the APIC :param dn_name: :return: """ dn_object = self.moDir.lookupByDn(dn_name) if dn_object is not None: dn_object.delete() self.commit(dn_object) """ Tenants """ def create_tenant(self, tenant_name): """ Creates a tenant and commit changes to controller :param tenant_name: :return: """ fv_tenant_mo = Tenant(self.uniMo, tenant_name) self.commit(fv_tenant_mo) return fv_tenant_mo def delete_tenant(self, tenant_dn): """ Deletes a tenant and commit changes to controller :param tenant_dn: :return: """ self.delete_by_dn(tenant_dn) def get_all_tenants(self): """ Searches all tenants within apic :return: """ class_query = ClassQuery('fvTenant') tn_list = self.moDir.query(class_query) return tn_list """ Switch Profiles """ def delete_switch_profile(self, switch_profile_name): """ Deletes an access policy switch profile :param switch_profile_name: :return: """ self.delete_by_dn('uni/infra/nprof-' + switch_profile_name) """ Bridge domains """ def create_bd(self, bd_name, tenant_dn, default_gw, **creation_props): """ Creates a BD object. Creates a subnet for the default gateway if it is not None :param bd_name: :param tenant_dn: :param default_gw: :param creation_props: :return: """ fv_bd_mo = BD(tenant_dn, bd_name, creation_props) self.commit(fv_bd_mo) if default_gw is not None and len(default_gw) > 0: fv_subnet_mo = Subnet(fv_bd_mo, default_gw) self.commit(fv_subnet_mo) return fv_bd_mo def delete_bd(self, bd_dn): """ Removes a bridge domain :param bd_dn: :return: """ self.delete_by_dn(bd_dn) def get_bds_by_tenant(self, tenant_dn): """ Retrieve a list with all bridge domains under a tenant :param tenant_dn: :return: """ # Queries all the children and then filter them in memory looking for the ones that belongs to the BD class tn_children = self.query_child_objects(tenant_dn) return filter(lambda x: type(x).__name__ == 'BD', tn_children) def get_all_bds(self): """ Returns a list of all bridge domains in the fabric :return: """ class_query = ClassQuery('fvBD') bd_list = self.moDir.query(class_query) return bd_list """ Filters """ def create_filter(self, tenant_dn, filter_name): """ Creates a filter under a tenant :param tenant_dn: :param filter_name: :return: """ vz_filter_mo = Filter(tenant_dn, filter_name) self.commit(vz_filter_mo) return vz_filter_mo def delete_filter(self, filter_dn): """ Removes a filter from the APIC :param filter_dn: :return: """ self.delete_by_dn(filter_dn) def get_filters_by_tenant(self, tenant_dn): """ Query the filters that are children of a tenant :param tenant_dn: :return: """ tn_children = self.query_child_objects(tenant_dn) # Queries all the children and then filter them in memory looking for the ones that belongs to the Filter class return filter(lambda x: type(x).__name__ == 'Filter', tn_children) """ Contracts """ def create_contract(self, tenant_dn, contract_name): """ Creates a contract under a tenant :param tenant_dn: :param contract_name: :return: """ vz_contract = BrCP(tenant_dn, contract_name) self.commit(vz_contract) return vz_contract def delete_contract(self, contract_dn): """ Removes a contract from the APIC :param contract_dn: :return: """ self.delete_by_dn(contract_dn) def get_contracts_by_tenant(self, tenant_dn): """ Return a list with all the contracts under a tenant :param tenant_dn: :return: """ tn_children = self.query_child_objects(tenant_dn) # Queries all the children and then filter them in memory looking for the ones that belongs to the BrCP class return filter(lambda x: type(x).__name__ == 'BrCP', tn_children) def assign_contract(self, epg_dn, provider_dn, consumer_dn): """ Assign contracts to an end point group :param epg_dn: :param provider_dn: Provider contract :param consumer_dn: Consumer contract :return: """ epg_mo = self.moDir.lookupByDn(epg_dn) if len(provider_dn) > 0: # Retrieve the provider contract provider_mo = self.moDir.lookupByDn(provider_dn) # Create the provider relationship with EPG rsprov_mo = RsProv(epg_mo, provider_mo.name) self.commit(rsprov_mo) if len(consumer_dn) > 0: # Retrieve the consumer contract consumer_mo = self.moDir.lookupByDn(consumer_dn) # Creates the consumer relationship with EPG rscons_mo = RsCons(epg_mo, consumer_mo.name) self.commit(rscons_mo) def delete_assign_contract(self, epg_dn): """ Removes the EPG's assigned contracts :param epg_dn: :return: """ # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the # RsProv class epg_providers = filter(lambda x: type(x).__name__ == 'RsProv', self.query_child_objects(epg_dn)) # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the # RsCons class epg_consumers = filter(lambda x: type(x).__name__ == 'RsCons', self.query_child_objects(epg_dn)) # For each consumer and provider contract removes the relationship for provider in epg_providers: provider.delete() self.commit(provider) for consumer in epg_consumers: consumer.delete() self.commit(consumer) """ Subjects """ def create_subject(self, filter_dn, contract_dn, subject_name): """ Creates a subject between a contract and a filter :param filter_dn: :param contract_dn: :param subject_name: :return: """ subject_dn = Subj(contract_dn, subject_name) self.commit(subject_dn) filter_mo = self.moDir.lookupByDn(filter_dn) rs_filter_subject = RsSubjFiltAtt(subject_dn, filter_mo.name) self.commit(rs_filter_subject) return rs_filter_subject def get_subjects_by_contract(self, contract_dn): """ Returns all subject under a given contract :param contract_dn: :return: """ contract_children = self.query_child_objects(contract_dn) # Queries all the children and then filter them in memory looking for the ones that belongs to the Subj class return filter(lambda x: type(x).__name__ == 'Subj', contract_children) def delete_subject(self, subject_dn): """ Removes a subject from the APIC :param subject_dn: :return: """ self.delete_by_dn(subject_dn) """ End Point Groups """ def create_epg(self, ap_dn, bd_dn, epg_name): """ Creates a EPG and, if the bd_dn parameter is not None, will associate that bridge domain to the EPG :param ap_dn: application profile to be used as parent :param bd_dn: bridge domain to be associated with the EPG :param epg_name: :return: """ epg_mo = AEPg(ap_dn, epg_name) self.commit(epg_mo) if bd_dn is not None and len(bd_dn) > 0: # Queries all the children and then filter them in memory looking for the ones that belongs to the RsBd # class. Choose the first one and assign it to the rsbd_mo variable rsbd_mo = filter(lambda x: type(x).__name__ == 'RsBd', self.query_child_objects(str(epg_mo.dn)))[0] # The tnFvBDName is the attribute that sets the relationship between the bridge domain and the EPG. # Looks for the bd_dn object and then assign its name to the tnFvBDName attribute of the rsdb_mo object rsbd_mo.tnFvBDName = self.moDir.lookupByDn(bd_dn).name self.commit(rsbd_mo) return epg_mo def delete_epg(self, epg_dn): """ Removes an EPG from the APIC :param epg_dn: :return: """ self.delete_by_dn(epg_dn) def get_epg_by_ap(self, ap_dn): """ Returns a list of end point groups under an application profile :param ap_dn: :return: """ ap_children = self.query_child_objects(ap_dn) # Queries all the children and then filters them in memory looking for the ones that belongs to the AEPg class. return filter(lambda x: type(x).__name__ == 'AEPg', ap_children) """ Application Profiles """ def create_ap(self, tenant_dn, ap_name): """ Creates an application profile :param tenant_dn: :param ap_name: :return: """ ap_mo = Ap(tenant_dn, ap_name) self.commit(ap_mo) return ap_mo def delete_ap(self, ap_dn): """ Removes an application profile :param ap_dn: :return: """ self.delete_by_dn(ap_dn) def get_ap_by_tenant(self, tenant_dn): """ Returns a list of application profiles under a tenant :param tenant_dn: :return: """ tn_children = self.query_child_objects(tenant_dn) # Queries all the children and then filters them in memory looking for the ones that belongs to the Ap class. return filter(lambda x: type(x).__name__ == 'Ap', tn_children) def __repr__(self): return 'Connected to %s with userid: %s' % (self.apic_url, self.apic_user) def create_entry(self, filter_dn, entry_name, ether_type): vz_entry = Entry(filter_dn, entry_name) vz_entry.etherT = ether_type self.commit(vz_entry) return vz_entry def create_ntp_server(self, ntp_ip, pol_name): """ Creates a NTP pool and provider according to the IP and Pol that are sent via parameters :param ntp_ip: :return: """ # Creates the pool ntp_pol = Pol('uni/fabric', name=pol_name) # Creates the provider NtpProv(ntp_pol, name=ntp_ip, preferred='yes') # Commit objects self.commit(ntp_pol) # Return pol return ntp_pol @staticmethod def get_cobra_version(): """ :return: acicobra package version """ installed_packages = pip.get_installed_distributions() for package in installed_packages: if package.key == 'acicobra': return package.version
import logging, json from cobra.mit.access import MoDirectory from cobra.mit.session import LoginSession # uncomment the below to get more verbose output # for debugging """ import httplib as http_client http_client.HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True """ session = LoginSession('https://*****:*****@lw@y') moDir = MoDirectory(session) moDir.login() tenant1Mo = moDir.lookupByClass("dhcpClient") for c in tenant1Mo: print(c.dn, c.model, c.name, c.ip) moDir.logout()
class apic_base: def __init__(self): self.session = None self.moDir = None self.configReq = None self.uniMo = None """ Authentication """ def login(self, url, user, password): """ Login to the APIC :param url: :param user: :param password: :return: """ self.session = LoginSession(url, user, password) self.moDir = MoDirectory(self.session) self.moDir.login() self.configReq = ConfigRequest() self.uniMo = self.moDir.lookupByDn('uni') def logout(self): """ Logout from the APIC :return: """ self.moDir.logout() """ Commits """ def commit(self, commit_object): """ Commits object changes to controller :param commit_object: :return: """ self.configReq = ConfigRequest() self.configReq.addMo(commit_object) self.moDir.commit(self.configReq) """ Queries """ def query_child_objects(self, dn_query_name): """ Retrieve the object using the dn and return all the children under it :param dn_query_name: dn of the management object :return: """ dn_query = DnQuery(dn_query_name) dn_query.queryTarget = QUERY_TARGET_CHILDREN child_mos = self.moDir.query(dn_query) return child_mos """ Generic Deletes """ def delete_dn_by_pattern(self, dn_object_list, dn_pattern, recursive): """ Travers a dn list and compare each member with a pattern. If there is a match that object will be removed. If recursive is true, the algorithm will also do a recursive look for the children of each object looking for the pattern: will stop only when there is no more children to look for. :param dn_object_list: :param dn_pattern: :param recursive: :return: """ for dn_object in dn_object_list: if dn_pattern in str(dn_object.dn): try: self.delete_by_dn(str(dn_object.dn)) except CommitError as e: print 'Could not delete ' + str(dn_object.dn) + ' -> ' + str(e) elif recursive: children = self.query_child_objects(dn_object.dn) if children is not None: self.delete_dn_by_pattern(children, dn_pattern, recursive) def delete_by_dn(self, dn_name): """ Retrieve a mo and it removes it from the APIC :param dn_name: :return: """ dn_object = self.moDir.lookupByDn(dn_name) if dn_object is not None: dn_object.delete() self.commit(dn_object) """ Tenants """ def create_tenant(self, tenant_name): """ Creates a tenant and commit changes to controller :param tenant_name: :return: """ fv_tenant_mo = Tenant(self.uniMo, tenant_name) self.commit(fv_tenant_mo) return fv_tenant_mo def delete_tenant(self, tenant_dn): """ Deletes a tenant and commit changes to controller :param tenant_dn: :return: """ self.delete_by_dn(tenant_dn) def get_all_tenants(self): """ Searches all tenants within apic :return: """ class_query = ClassQuery('fvTenant') tn_list = self.moDir.query(class_query) return tn_list """ Switch Profiles """ def delete_switch_profile(self, switch_profile_name): """ Deletes an access policy switch profile :param switch_profile_name: :return: """ self.delete_by_dn('uni/infra/nprof-' + switch_profile_name) """ Bridge domains """ def create_bd(self, bd_name, tenant_dn, default_gw, **creation_props): """ Creates a BD object. Creates a subnet for the default gateway if it is not None :param bd_name: :param tenant_dn: :param default_gw: :param creation_props: :return: """ fv_bd_mo = BD(tenant_dn, bd_name, creation_props) self.commit(fv_bd_mo) if default_gw is not None and len(default_gw) > 0: fv_subnet_mo = Subnet(fv_bd_mo, default_gw) self.commit(fv_subnet_mo) return fv_bd_mo def delete_bd(self, bd_dn): """ Removes a bridge domain :param bd_dn: :return: """ self.delete_by_dn(bd_dn) def get_bds_by_tenant(self, tenant_dn): """ Retrieve a list with all bridge domains under a tenant :param tenant_dn: :return: """ # Queries all the children and then filter them in memory looking for the ones that belongs to the BD class tn_children = self.query_child_objects(tenant_dn) return filter(lambda x: type(x).__name__ == 'BD', tn_children) def get_all_bds(self): """ Returns a list of all bridge domains in the fabric :return: """ class_query = ClassQuery('fvBD') bd_list = self.moDir.query(class_query) return bd_list """ Filters """ def create_filter(self, tenant_dn, filter_name): """ Creates a filter under a tenant :param tenant_dn: :param filter_name: :return: """ vz_filter_mo = Filter(tenant_dn, filter_name) self.commit(vz_filter_mo) def delete_filter(self, filter_dn): """ Removes a filter from the APIC :param filter_dn: :return: """ self.delete_by_dn(filter_dn) def get_filters_by_tenant(self, tenant_dn): """ Query the filters that are children of a tenant :param tenant_dn: :return: """ tn_children = self.query_child_objects(tenant_dn) # Queries all the children and then filter them in memory looking for the ones that belongs to the Filter class return filter(lambda x: type(x).__name__ == 'Filter', tn_children) """ Contracts """ def create_contract(self, tenant_dn, contract_name): """ Creates a contract under a tenant :param tenant_dn: :param contract_name: :return: """ vz_contract = BrCP(tenant_dn, contract_name) self.commit(vz_contract) def delete_contract(self, contract_dn): """ Removes a contract from the APIC :param contract_dn: :return: """ self.delete_by_dn(contract_dn) def get_contracts_by_tenant(self, tenant_dn): """ Return a list with all the contracts under a tenant :param tenant_dn: :return: """ tn_children = self.query_child_objects(tenant_dn) # Queries all the children and then filter them in memory looking for the ones that belongs to the BrCP class return filter(lambda x: type(x).__name__ == 'BrCP', tn_children) def assign_contract(self, epg_dn, provider_dn, consumer_dn): """ Assign contracts to an end point group :param epg_dn: :param provider_dn: Provider contract :param consumer_dn: Consumer contract :return: """ epg_mo = self.moDir.lookupByDn(epg_dn) if len(provider_dn) > 0: # Retrieve the provider contract provider_mo = self.moDir.lookupByDn(provider_dn) # Create the provider relationship with EPG rsprov_mo = RsProv(epg_mo, provider_mo.name) self.commit(rsprov_mo) if len(consumer_dn) > 0: # Retrieve the consumer contract consumer_mo = self.moDir.lookupByDn(consumer_dn) # Creates the consumer relationship with EPG rscons_mo = RsCons(epg_mo, consumer_mo.name) self.commit(rscons_mo) def delete_assign_contract(self, epg_dn): """ Removes the EPG's assigned contracts :param epg_dn: :return: """ # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the # RsProv class epg_providers = filter(lambda x: type(x).__name__ == 'RsProv', self.query_child_objects(epg_dn)) # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the # RsCons class epg_consumers = filter(lambda x: type(x).__name__ == 'RsCons', self.query_child_objects(epg_dn)) # For each consumer and provider contract removes the relationship for provider in epg_providers: provider.delete() self.commit(provider) for consumer in epg_consumers: consumer.delete() self.commit(consumer) """ Subjects """ def create_subject(self, filter_dn, contract_dn, subject_name): """ Creates a subject between a contract and a filter :param filter_dn: :param contract_dn: :param subject_name: :return: """ subject_dn = Subj(contract_dn, subject_name) self.commit(subject_dn) filter_mo = self.moDir.lookupByDn(filter_dn) rs_filter_subject = RsSubjFiltAtt(subject_dn, filter_mo.name) self.commit(rs_filter_subject) def get_subjects_by_contract(self, contract_dn): """ Returns all subject under a given contract :param contract_dn: :return: """ contract_children = self.query_child_objects(contract_dn) # Queries all the children and then filter them in memory looking for the ones that belongs to the Subj class return filter(lambda x: type(x).__name__ == 'Subj', contract_children) def delete_subject(self, subject_dn): """ Removes a subject from the APIC :param subject_dn: :return: """ self.delete_by_dn(subject_dn) """ End Point Groups """ def create_epg(self, ap_dn, bd_dn, epg_name): """ Creates a EPG and, if the bd_dn parameter is not None, will associate that bridge domain to the EPG :param ap_dn: application profile to be used as parent :param bd_dn: bridge domain to be associated with the EPG :param epg_name: :return: """ epg_mo = AEPg(ap_dn, epg_name) self.commit(epg_mo) if bd_dn is not None and len(bd_dn) > 0: # Queries all the children and then filter them in memory looking for the ones that belongs to the RsBd # class. Choose the first one and assign it to the rsbd_mo variable rsbd_mo = filter(lambda x: type(x).__name__ == 'RsBd', self.query_child_objects(str(epg_mo.dn)))[0] # The tnFvBDName is the attribute that sets the relationship between the bridge domain and the EPG. # Looks for the bd_dn object and then assign its name to the tnFvBDName attribute of the rsdb_mo object rsbd_mo.tnFvBDName = self.moDir.lookupByDn(bd_dn).name self.commit(rsbd_mo) return epg_mo def delete_epg(self, epg_dn): """ Removes an EPG from the APIC :param epg_dn: :return: """ self.delete_by_dn(epg_dn) def get_epg_by_ap(self, ap_dn): """ Returns a list of end point groups under an application profile :param ap_dn: :return: """ ap_children = self.query_child_objects(ap_dn) # Queries all the children and then filters them in memory looking for the ones that belongs to the AEPg class. return filter(lambda x: type(x).__name__ == 'AEPg', ap_children) """ Application Profiles """ def create_ap(self, tenant_dn, ap_name): """ Creates an application profile :param tenant_dn: :param ap_name: :return: """ ap_mo = Ap(tenant_dn, ap_name) self.commit(ap_mo) return ap_mo def delete_ap(self, ap_dn): """ Removes an application profile :param ap_dn: :return: """ self.delete_by_dn(ap_dn) def get_ap_by_tenant(self, tenant_dn): """ Returns a list of application profiles under a tenant :param tenant_dn: :return: """ tn_children = self.query_child_objects(tenant_dn) # Queries all the children and then filters them in memory looking for the ones that belongs to the Ap class. return filter(lambda x: type(x).__name__ == 'Ap', tn_children)
parser = argparse.ArgumentParser(description="Display CEp by EPG") parser.add_argument('tenantName', help='tenant name') parser.add_argument('apName', help='ap name') parser.add_argument('epgName', help='EPG name') parser.add_argument('-m', dest='macAddress', help='MAC address') args = parser.parse_args() # open yaml files f = open('credentials.yaml', 'r') credentials = yaml.load(f) f.close() apicUrl = credentials['host'] loginSession = LoginSession(apicUrl, credentials['user'], credentials['pass']) moDir = MoDirectory(loginSession) moDir.login() dnQuery = DnQuery('uni/tn-' + args.tenantName + '/ap-' + args.apName + '/epg-' + args.epgName) dnQuery.queryTarget = 'children' dnQuery.subtreeClassFilter = 'fvAEPg' epgMo = moDir.query(dnQuery) for epg in epgMo: #print epg.dn if isinstance(epg, CEp): if (args.macAddress): if (args.macAddress == epg.name): cepQuery = DnQuery(epg.dn) cepQuery.queryTarget = 'children' cepMo = moDir.query(cepQuery) for cep in cepMo:
def apic_login(hostname, username, password): """Login to APIC""" lsess = LoginSession("https://" + hostname, username, password) modir = MoDirectory(lsess) modir.login() return modir
from cobra.mit.request import ClassQuery if __name__ == '__main__': if len(sys.argv) != 5: print 'Usage: apic_show-mac-address.py <hostname> <username> <password> <mac-address>' sys.exit() else: hostname, username, password, macaddress = sys.argv[1:] url = 'https://' + hostname print "Logging on APIC..." try: # lls = LoginSession(url, username, password, secure=False) md = MoDirectory(lls) md.login() q = ClassQuery('fvCEp') q.subtree = 'children' q.subtreeClassFilter = 'fvRsCEpToPathEp' mos = md.query(q) #Other variables hasmacaddress = False epglists = {} i = -1 ## Verifying all mac address: for mo in mos: for child in mo.rscEpToPathEp: line = str(child.dn) i = i + 1