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 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 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 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 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 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 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(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 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 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 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 apic_login(url, username, password): # Create Session session = LoginSession(url, username, password) moDir = MoDirectory(session) #Login moDir.login() 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(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 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 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 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 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 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 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 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 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(): ls = LoginSession(apicURL, apicUN, apicPW) md = MoDirectory(ls) md.login() # Print LLDP Adjacent Endpoints printClass(md, 'lldpAdjEp', 'mgmtIp') # Print all tenants printClass(md, 'fvTenant', 'name') # Print all L2OUT printClass(md, 'l2extOut', 'name') # Print all fabric Nodes printClass(md, 'fabricNode', 'name') printClass(md, 'fabricNode', 'model') printClass(md, 'fabricNode', 'id') printClass(md, 'aaaUser', 'name') # Print BGP Peer printClass(md, 'bgpPeerP', 'addr') # Create tenants createTenant(md, 'EvictMe', 'My First Eviction') # Create VRF in EvictMe createVRF(md, 'EvictMe', 'VRF-Eviction', 'My VRF for eviction') # Create BD in EvictMe createBD(md, 'EvictMe', 'BD-Eviction', 'My BD for eviction') # Create L2OUT in EvictMe createL2OUT(md, 'EvictMe', 'L2OUT-Eviction', 'My L2OUT for eviction') # Create L3OUT Logical Node Profile createLogicalNodeProfile(md, 'EvictMe', 'DC-L3OUT', 'MyProfile', 'My LNP') # Create L3OUT BGP Peer createBGPPeer(md, 'EvictMe', 'DC-L3OUT', 'MyProfile', '9.9.9.9', 'My BGP Peer') md.logout()
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.status_code == 200