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 test_post_tn(self, apics, certobject, userobject): apic = apics[0] secure = False if apics[1] == 'False' else True userobject.pkey = certobject.readFile( fileName=certobject.pkeyfile) session = CertSession(apic, userobject.certDn, userobject.pkey, secure=secure, requestFormat='xml') moDir = MoDirectory(session) uni = Uni('') fvTenant = Tenant(uni, name='t') fvBD = BD(fvTenant, 't-bd') fvAp = Ap(fvTenant, 't-app') cr = ConfigRequest() #cr.subtree = 'full' cr.addMo(fvTenant) if userobject.user == 'rouser': with pytest.raises(RestError) as excinfo: r = moDir.commit(cr) assert excinfo.value.reason == ('user rouser does not have ' + 'domain access to config Mo, ' + 'class fvTenant') elif userobject.user == 'rwuser': r = moDir.commit(cr) else: raise NotImplementedError
def test_post_tn(self, apics, certobject, userobject): apic = apics[0] secure = False if apics[1] == 'False' else True userobject.pkey = certobject.readFile( fileName=certobject.pkeyfile) session = CertSession(apic, userobject.certDn, userobject.pkey, secure=secure, requestFormat='xml') moDir = MoDirectory(session) uni = Uni('') fvTenant = Tenant(uni, name='t') fvBD = BD(fvTenant, 't-bd') fvAp = Ap(fvTenant, 't-app') cr = ConfigRequest() #cr.subtree = 'full' cr.addMo(fvTenant) if userobject.user == 'rouser': with pytest.raises(RestError) as excinfo: r = moDir.commit(cr) assert ((excinfo.value.reason == ('user rouser does not have ' + 'domain access to config Mo, ' + 'class fvTenant')) or (excinfo.value.reason == ('user rouser does not have ' + 'domain access to config Mo, ' + 'class fvBD'))) elif userobject.user == 'rwuser': r = moDir.commit(cr) else: raise NotImplementedError
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 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(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
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 login(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 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(self): # TODO handle multiple hosts LOG.info("ACI Login") login_session = LoginSession(self.api_base[0], self.user, self.password) self.mo_dir = MoDirectory(login_session) self.mo_dir.login() LOG.info("Login session created, will expire at {} in {} seconds".format(login_session.refreshTime,login_session.refreshTimeoutSeconds))
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(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 apic_login(host, user, password): """Login to APIC""" if not host.startswith(('http', 'https')): host = 'https://' + host lsess = LoginSession(host, user, password) moDir = MoDirectory(lsess) moDir.login() moDir = moDir return moDir
def apic_logon(): apicUrl = 'https://10.37.1.11' loginSession = LoginSession(apicUrl, 'admin', 'dr1ft3r*') moDir = MoDirectory(loginSession) moDir = MoDirectory(loginSession) moDir.login() # Use the connected moDir queries and configuration... #moDir.logout() return moDir
def login(url, name, password): session = LoginSession(url, name, password) mo = MoDirectory(session) try: mo.login() print '[+] Login successfull' except: print '[-] Login Error' exit(1) return mo
def apic_login(url, username, password): # Create Session session = LoginSession(url, username, password) moDir = MoDirectory(session) #Login moDir.login() return moDir
def apicLogin(): # Connection and authentication apicUrl = 'http://1.2.3.4' loginSession = LoginSession(apicUrl, 'user', 'password') moDir = MoDirectory(loginSession) try: moDir.login() except: print("Login error (wrong username or password?)") exit(1) return moDir
def add_servicegraph(): apicURL = os.getenv("CliqrCloud_AciApicEndpoint") apicUser = os.getenv("CliqrCloud_AciUsername") apicPwd = os.getenv("CliqrCloud_AciPassword") apicTenant = os.getenv("CliqrCloud_AciTenantName") apicServiceGraphTemplate = os.getenv("Cloud_Setting_serviceGraphTemplate") # Handle cases where APIC URL is configured without ssl (typically, in a lab). if apicURL.startswith("https"): loginSession = LoginSession(apicURL, apicUser, apicPwd) else: loginSession = LoginSession(apicURL, apicUser, apicPwd,secure=False) # CliqrTier_CentOS_1_Cloud_Setting_AciPortGroup_2 tmpString = "CliqrTier_" + os.getenv("CliqrDependencies") + "_Cloud_Setting_AciPortGroup_2" appProfileName = os.getenv(tmpString).split("|")[1] qTenant = "tn-" + apicTenant qString = "uni/" + qTenant + "/ap-" + appProfileName dnQuery = DnQuery(qString) dnQuery.queryTarget = 'subtree' dnQuery.classFilter = 'fvRsProv' dnQuery.subtree = 'children' #dnQuery.subtreePropFilter='eq(fvRsCons.tCl,"vzBrCP")' # Obtain Session from APIC. moDir = MoDirectory(loginSession) moDir.login() # Query to obtain data from Managed Object Directory. dmo = moDir.query(dnQuery) print str(dmo[0].tDn) # Debug String. Remove from running env. logging.debug(" Contract String Obtained :" + dmo[0].tDn) # Service Graph - Query String qStringAbsG = "uni/" + qTenant + "/AbsGraph-" + apicServiceGraphTemplate graphMO = moDir.lookupByDn(qStringAbsG) # Subject Query String qStringSubj = dmo[0].tDn + "/subj-cliqr-subject" subjMO = moDir.lookupByDn(qStringSubj) # Attach Graph to Contract. RsSubjGraphAtt(subjMO, tnVnsAbsGraphName=graphMO.name) # Create Commit Object. nsCfg = ConfigRequest() nsCfg.addMo(subjMO) moDir.commit(nsCfg) contractString = dmo[0].tDn tmpArr = contractString.split("/") apicContractName = tmpArr[len(tmpArr)-1].replace("brc-","") aviApicContractArg = apicContractName + ":" + apicServiceGraphTemplate aviApicEpgName = appProfileName + ":" + os.getenv(tmpString).split("|")[2] params = {} with open('params.json', 'r') as p: params = json.loads(p.read()) params['apic_contract_graph'] = aviApicContractArg params['apic_epg_name'] = aviApicEpgName logging.debug(" Dump Params :: " + json.dumps(params)) with open('params.json', 'w') as f: json.dump(params, f)
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 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.status_code == 200
def getMoDir(self): logging.debug('Inside ApicSession:getMoDir function') if self.sessionType == "KEY": certSession = CertSession(self.apicUrl, self.certDN, self.pKey) return MoDirectory(certSession) if self.sessionType == "PASSWORD": loginSession = LoginSession(self.apicUrl, self.apicUser, self.apicPassword) return MoDirectory(loginSession) if self.sessionType == "INVALID": return None
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 test_get_tn(self, apics, certobject, userobject): apic = apics[0] secure = False if apics[1] == 'False' else True userobject.pkey = certobject.readFile( fileName=certobject.pkeyfile) session = CertSession(apic, userobject.certDn, userobject.pkey, secure=secure, requestFormat='xml') moDir = MoDirectory(session) dnQuery = DnQuery('uni/tn-common') #dnQuery.subtree = "full" tq = moDir.query(dnQuery) assert len(tq) == 1 tq = tq[0] assert str(tq.parentDn) == 'uni' assert str(tq.dn) == 'uni/tn-common'
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 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')
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 get_tenant(): with open("/Users/clakits/Documents/ACI/AppCenter/log/log.txt", "a") as log_file: log_file.write("==================================================" + "\n") log_file.write("Received API Request from Client. Sending Response" + "\n") log_file.write("==================================================" + "\n") tableList = [] row = ('Tenant') tableList.append(row) apicUrl = 'https://10.22.47.171/' #loginSession = createCertSession() loginSession = LoginSession(apicUrl, 'admin', 'ins3965!') moDir = MoDirectory(loginSession) moDir.login() #tenantMo = moDir.lookupByClass('fvTenant'); q = ClassQuery('fvTenant') q.subtree = 'children' tenantMo = moDir.query(q) moDir.logout() print tenantMo.totalCount for item in tenantMo: row = str(item.dn) print row tableList.append(row) #return respFormatJsonMos(tenantMo, tenantMo.totalCount) return render_template('result1.html', table=tableList)
def aciLogin(): print('') apic_addr = six.moves.input("APIC IP Address/FQDN: ") is_ip = re.match(IP_ADDR, apic_addr) is_host = re.match(HOST_FQDN, apic_addr) if (is_ip): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) try: s.connect((apic_addr,443)) except: print("APIC IP Address unreachable!") sys.exit() if (is_host): try: socket.gethostbyname(apic_addr) except socket.gaierror: print("APIC FQDN unreachable!") sys.exit() if not is_ip and not is_host: print("Not a valid IP Address or FQDN!") sys.exit() apic_user = six.moves.input("APIC Username: "******"https://" + apic_addr session = LoginSession(apic_url, apic_user, apic_pass) moDir = MoDirectory(session) try: moDir.login() except requests.exceptions.RequestException: print("Cannot connect to APIC!") sys.exit() return moDir
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 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 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 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.status_code == 200
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 login(login_info): try: session = LoginSession(*login_info) mo_dir = MoDirectory(session) mo_dir.login() print("%s" % colored("\n Authentication successful!", color="green", attrs=["bold"])) sleep(2) clear() return mo_dir except HTTPError as error: print("There's an error in you APIC's username and/or password.\n", "Please verify and try again.\n", colored("Error: ", color="red"), colored(error, "yellow")) print() sys.exit() except ConnectionError as error: print("The provided APIC's IP Address is either unresponsive or wrong.\n", "Please verify and try again.\n", colored("Error: ", color="red"), colored(error, "yellow")) print() sys.exit()
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 home(): #apicUrl = 'https://10.29.198.36' # loginSession = LoginSession(apicUrl, 'admin', 'ins3965!') #loginSession = createCertSession() loginSession = cobra.mit.session.LoginSession('https://10.29.198.36', '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) q = ClassQuery('fvCEp') q.subtree = 'children' tenantMo = moDir.query(q) 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)) tableList.append(row) moDir.logout() return render_template('home.html', table=tableList)
def main(): oType, oName = arg_parse() session = LoginSession(apicUrl, userName, userPass) mo = MoDirectory(session) try: mo.login() print '[+] Login successfull' except: print '[-] Login Error' exit(1) if ',' in oName: oName = oName.split(',') tenantDN = 'uni/tn-' + TENANT fvTenant = mo.lookupByDn(tenantDN) for name in oName: if oType.lower() == 'bd': dn = tenantDN + '/BD-' + name if oType.lower() == 'epg': dn = tenantDN + '/ap-' + APP + '/epg-' + name if oType == 'ap': dn = tenantDN + '/ap-' + name obj = mo.lookupByDn(dn) if obj: try: obj.delete() print '[+] Object %s "%s" successfully deleted' % (str( oType.upper()), str(name)) c = ConfigRequest() c.addMo(obj) mo.commit(c) except: print '[-] Error deleting object %s "%s"' % (str( oType.upper()), str(name)) exit(1) else: print '[-] %s "%s". Error! No such Object! ' % (str( oType.upper()), str(name))
def main(): params = get_parameters() loginSession = LoginSession(params['apic-url'], params['apic-user'], params['apic-password']) md = MoDirectory(loginSession) md.login() create_remote_scp_location(md, params['backup-host'], params['backup-user'], params['backup-password'], params['backup-path']) import_backup(md, params['backup-filename']) check_backup_status(md, 'tmp_import_policy') delete_import_policy(md, 'tmp_import_policy') delete_backup_location(md, 'tmp_location') md.logout()
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)
# See the License for the specific language governing permissions and # limitations under the License. # ACI Cobra SDK Libraries from cobra.mit.access import MoDirectory from cobra.mit.session import LoginSession from cobra.model.fv import Ctx from cobra.model.fv import * from cobra.mit.request import * # APIC Login Credentials apicUrl = 'https://URL-of-APIC' loginSession = LoginSession(apicUrl, 'username', 'password') # APIC Managed Object Directory - starting at the top moDir = MoDirectory(loginSession) # Program asks for the name of the tenant to be created TenantName = raw_input("Tenant Name: ") moDir.login() # Create new Tenant uniMo = moDir.lookupByDn('uni') fvTenantMo = Tenant(uniMo, TenantName) # Create new Private network/VRF under the new Tenant fvContextMo = Ctx(fvTenantMo, 'myVRF') # Add the new Tenant and its VRF Configuration to the APIC and commit these changes cfgRequest = ConfigRequest()
from cobra.mit.request import ConfigRequest 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)
def apic_login_cobra(hostname, username, password): """Login to APIC""" lsess = LoginSession('http://'+hostname, username, password) modir = MoDirectory(lsess) modir.login() return modir
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)
# Initialize logging logging.basicConfig() # Set the logging level to DEBUG logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("requests.packages.urllib3") # Set just the URLLIB3 logging level to INFO requests_log.setLevel(logging.INFO) requests_log.propagate = True requests.packages.urllib3.disable_warnings() aci_class = sys.argv[1] session = LoginSession('https://172.21.208.173', 'admin','C1sc0123') moDir = MoDirectory(session) moDir.login() from cobra.mit.request import ConfigRequest #import the tenant class from the model from cobra.model.fv import Tenant # Get the top level policy universe directory uniMo = moDir.lookupByDn('uni') ## create the tenant object #fvTenantMo = Tenant(uniMo, 'test1111111111') #fvTenantMo.delete()# #configReq = ConfigRequest() #configReq.addMo(fvTenantMo)
def apic_login(hostname, username, password): """Login to APIC""" lsess = LoginSession("https://" + hostname, username, password) modir = MoDirectory(lsess) modir.login() return modir
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()
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!')