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(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 test_ConfigRequest_requestargs(self): expected1 = { 'data': '<?xml version="1.0" encoding="UTF-8"?>\n' + '<fvTenant name=\'testing\' ' + 'status=\'created,modified\'></fvTenant>', 'headers': { 'Cookie': 'APIC-cookie=None' }, 'timeout': 90, 'verify': False } expected2 = { 'data': '<?xml version="1.0" encoding="UTF-8"?>\n' + '<fvTenant status=\'created,modified\' ' + 'name=\'testing\'></fvTenant>', 'headers': { 'Cookie': 'APIC-cookie=None' }, 'timeout': 90, 'verify': False } polUni = Uni('') fvTenant = Tenant(polUni, 'testing') session = LoginSession('http://1.1.1.1', 'admin', 'password') cr = ConfigRequest() cr.addMo(fvTenant) assert (cr.requestargs(session) == expected1 or cr.requestargs(session) == expected2)
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_ConfigRequest_getUrl(self, sessionUrl, mo, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) expected = sessionUrl + '/api/mo/' + str(mo.dn) + '.' + requestType cr = ConfigRequest() cr.addMo(mo) assert cr.getUrl(session) == expected
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(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 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 test_ClassQuery_getUrl(self, sessionUrl, dc, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) klass = 'fvTenant' cq = ClassQuery(klass) expected = sessionUrl + '/api/class/' + klass + '.' + requestType cq.id = dc expected += '?_dc=' + dc assert cq.getUrl(session) == expected
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 test_DnQuery_getUrl(self, sessionUrl, dc, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) dn = 'uni' dq = DnQuery('uni') expected = sessionUrl + '/api/mo/' + dn + '.' + requestType dq.id = dc expected += '?_dc=' + dc assert dq.getUrl(session) == expected
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)
class Test_mit_session_Success_LoginSession(object): # Test the properties get set properly on LoginSession instantiation @pytest.mark.parametrize("session, url, user, password, secure, timeout," "requestFormat", [ (LoginSession('http://2.2.2.2:7777', 'c', 'd'), 'http://2.2.2.2:7777', 'c', 'd', False, 90, 'xml'), # Test expected default (LoginSession('http://1.1.1.1:80', 'a', 'b', True, 180, requestFormat='json'), 'http://1.1.1.1:80', 'a', 'b', True, 180, 'json'), (LoginSession('http://1.1.1.1:80', 'a', 'b', True, 180, requestFormat='xml'), 'http://1.1.1.1:80', 'a', 'b', True, 180, 'xml'), ]) def test_LoginSession_init(self, session, url, user, password, secure, timeout, requestFormat): assert session.url == url assert session.user == user assert session.password == password assert session.secure == secure assert session.timeout == timeout assert session.formatStr == requestFormat
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 test_TraceQuery_getUrl(self, sessionUrl, dc, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) dnStr = 'uni' klass = 'fvTenant' cq = TraceQuery(dnStr, klass) expected = sessionUrl + '/api/trace/' + dnStr + '.' + requestType expected += '?target-class=' + klass cq.id = dc expected += '&_dc=' + dc assert cq.getUrl(session) == expected
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 test_ConfigRequest_getUriPathAndOptions(self, sessionUrl, mo, dc, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) cr = ConfigRequest() cr.addMo(mo) expected = '/api/mo/' + str(mo.dn) + '.' + requestType if dc is not None: cr.id = dc expected += '?_dc=' + dc assert cr.getUriPathAndOptions(session) == expected
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 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 test_TagsRequest_requestargs(self): expected = { 'data': '{}', 'headers': { 'Cookie': 'APIC-cookie=None' }, 'timeout': 90, 'verify': False } session = LoginSession('http://1.1.1.1', 'admin', 'password') dnStr = 'uni' tr = TagsRequest(dnStr) assert tr.requestargs(session) == expected
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 test_TagsRequest_getUrl(self, sessionUrl, dc, requestType): dnStr = 'uni' session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) tr = TagsRequest(dnStr) expectedUrl = sessionUrl + '/api/tag/mo/' + dnStr + '.' + requestType tr.add = [u'tag1', u'tag2'] tr.remove = u'tag3' tr.id = dc expectedUrl1 = expectedUrl + '?add=tag1,tag2&remove=tag3&_dc=' + dc expectedUrl2 = expectedUrl + '?remove=tag3&add=tag1,tag2&_dc=' + dc assert (tr.getUrl(session) == expectedUrl1 or tr.getUrl(session) == expectedUrl2)
def test_LoginRequest_requestargs(self): expected = { 'headers': { 'Cookie': 'APIC-cookie=None' }, 'allow_redirects': False, 'data': '{"aaaUser": {"attributes": ' + '{"name": "admin", "pwd": "password"}}}', 'timeout': 90, 'verify': False } session = LoginSession('http://1.1.1.1', 'admin', 'password') lr = LoginRequest('admin', 'password') assert lr.requestargs(session) == expected
def test_AbstractRequest_getUriPathAndOptions(self, sessionUrl, dc, uriBase, requestType): expected = '.' + requestType session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) ar = AbstractRequest() if dc is not None: ar.id = dc expected += '?_dc=' + dc if uriBase is None: uriBase = '' ar.uriBase = uriBase expected = uriBase + expected assert ar.getUriPathAndOptions(session) == expected