def createdicts(cgx_session): resp = cgx_session.get.sites() if resp.cgx_status: sitelist = resp.cgx_content.get("items",None) for site in sitelist: sid = site['id'] sname = site['name'] siteid_sitename_dict[sid] = sname sitename_siteid_dict[sname] = sid else: print("ERR: Could not retrieve sites") cloudgenix.jd_detailed(resp) resp = cgx_session.get.elements() if resp.cgx_status: elemlist = resp.cgx_content.get("items",None) for elem in elemlist: eid = elem['id'] ename = elem['name'] sid = elem['site_id'] elemname_elemid_dict[ename] = eid if sid == "1": continue sname = siteid_sitename_dict[sid] elemname_sitename_dict[ename] = sname else: print("ERR: Could not retrieve sites") cloudgenix.jd_detailed(resp) return
def applySNMPConfig(cgx, site, element, snmp): for agent in snmp["agents"]: res = cgx.post.snmpagents(site, element, agent) if not res: jd_detailed(res) print(f"Can't create SNMP Agent config") sys.exit(-1) for trap in snmp["traps"]: #convert interface into import ip, if its a controller port, try diffrerent combinations if "controller" in trap["source_interface"]: s_interface = getInterfaceByName(cgx, site, element, "controller") if not s_interface: s_interface = getInterfaceByName(cgx, site, element, "controller 1") else: s_interface = getInterfaceByName(cgx, site, element, trap["source_interface"]) if not s_interface: print( f"Can't find interface {trap['source_interface']} in target element" ) sys.exit(-1) save_interface = trap['source_interface'] trap['source_interface'] = s_interface["id"] res = cgx.post.snmptraps(site, element, trap) if not res: jd_detailed(res) print(f"Can't create SNMP Traps config") sys.exit(-1) trap['source_interface'] = save_interface
def updatePerPrefixARP(cgx, args, sites): """ change per Prefix ARP according to the args input """ # for every elemnt, check if it should be changed and if it should do the required change for element in cgx.get.elements().cgx_content["items"]: # if element ID isn't in the sites list, its a hub and we can ignore it if not element["site_id"] in sites: continue # first check if extension exist log.info("{element} at {site} is being configured".format( element=element["name"], site=sites[element["site_id"]])) fcconfig = None for extension in cgx.get.element_extensions( element["site_id"], element["id"]).cgx_content["items"]: if extension["namespace"] == "fcconfig": fcconfig = extension log.info("-- already have fcconfig") break # if alg do not exists create on if not fcconfig: log.info("-- creating fcconfig namespace") ext = { "name": "fc config", "namespace": "fcconfig", "entity_id": "8844", "disabled": False, "conf": { "arp_per_prefix_router_failure": args["enable"] } } r = cgx.post.element_extensions(element["site_id"], element["id"], ext) if not r: jd_detailed(r) raise ValueError("cant create fcconfig extenstion") else: # set the new value fcconfig["conf"]["arp_per_prefix_router_failure"] = args["enable"] # update the rules log.info("-- updating fcconfig entry") r = cgx.put.element_extensions(element["site_id"], element["id"], fcconfig["id"], fcconfig) if not r: jd_detailed(r) raise ValueError("cant update fcconfig extension")
def get_events(cgx_session, numhours, starttime, endtime, event_codes, sitelist): if numhours == RANGE: start_time_iso = starttime.isoformat() + "Z" end_time_iso = endtime.isoformat() + "Z" else: current_time = datetime.datetime.utcnow().replace(second=0, microsecond=0) start_time = current_time - datetime.timedelta(hours= numhours) start_time_iso = start_time.isoformat() + "Z" end_time_iso = None eventlist = [] # # Get matching set of events. # events_query_payload = { "limit": { "count": 100, "sort_on": "time", "sort_order": "descending" }, "query": { "code": event_codes, "site": sitelist }, "severity": [], "start_time":start_time_iso, "end_time":end_time_iso } more_events=True while more_events: print ("INFO: Getting {0} starting from {1} using query {2}".format(event_codes, start_time_iso, json.dumps(events_query_payload))) resp = cgx_session.post.events_query(data=events_query_payload) if resp.cgx_status: eventlist += resp.cgx_content.get("items", None) offset = resp.cgx_content['_offset'] print ("\tTotal events: {0}. Events Retrieved: {1}. Events Pending: {2}".format(resp.cgx_content['total_count'],resp.cgx_content['included_count'], (resp.cgx_content['total_count']-resp.cgx_content['included_count']) )) if offset: events_query_payload['start_time'] = start_time_iso events_query_payload['_offset'] = offset more_events = True else: more_events = False else: print ("ERR: Failed to get events: {}".format(resp.cgx_content)) print(cloudgenix.jd_detailed(resp)) more_events = False return [] #print "\t{0}:{1} returned".format(datetime.datetime.utcnow(), len(eventlist)) return eventlist
def createdicts(cgx_session): # Network Stack resp = cgx_session.get.networkpolicysetstacks() if resp.cgx_status: nwstacklist = resp.cgx_content.get("items",None) for nwstack in nwstacklist: nwstackid_nwstackname_dict[nwstack['id']] = nwstack['name'] else: print("ERR: Could not query Network Policy Stack") cloudgenix.jd_detailed(resp) # QoS Stack resp = cgx_session.get.prioritypolicysetstacks() if resp.cgx_status: qosstacklist = resp.cgx_content.get("items", None) for qosstack in qosstacklist: qosstackid_qosstackname_dict[qosstack['id']] = qosstack['name'] else: print("ERR: Could not query Priority Policy Stack") cloudgenix.jd_detailed(resp) # Policy (v1) resp = cgx_session.get.policysets() if resp.cgx_status: pollist = resp.cgx_content.get("items", None) for pol in pollist: polid_polname_dict[pol['id']] = pol['name'] else: print("ERR: Could not query for Policy Sets (v1)") cloudgenix.jd_detailed(resp) # Security Set resp = cgx_session.get.securitypolicysets() if resp.cgx_status: secpollist = resp.cgx_content.get("items", None) for secpol in secpollist: secpolid_secpolname_dict[secpol['id']] = secpol['name'] else: print("ERR: Could not query for Security Policy Sets") cloudgenix.jd_detailed(resp) return
def updateSIPalg(cgx, args, sites): """ change SIP alg accoring to the args input """ # for every elemnt, check if it should be changed and if it should do the required change for element in cgx.get.elements().cgx_content["items"]: # if element ID isn't in the sites list, its a hub and we can ignore it if not element["site_id"] in sites: continue # check if the element should be changed if args["scope_all"]: # first check if extension exist log.info("{element} at {site} is being configured".format( element=element["name"], site=sites[element["site_id"]])) alg = None for extension in cgx.get.element_extensions( element["site_id"], element["id"]).cgx_content["items"]: if extension["namespace"] == "algconfig": alg = extension log.info("-- already have algconfig") break # if alg do not exists create on if not alg: log.info("-- creating algconfig name space") ext = { "name": "alg", "namespace": "algconfig", "entity_id": None, "disabled": False, "conf": { "rules": [] } } r = cgx.post.element_extensions(element["site_id"], element["id"], ext) if not r: jd_detailed(r) raise ValueError("cant create algconfig extenstion") alg = r.cgx_content # if rules is None then create a list if not alg["conf"]["rules"]: alg["conf"]["rules"] = [] # find SIP alg rule rule_found = False for i in range(len(alg["conf"]["rules"])): #if found set the enable if alg["conf"]["rules"][i]["alg"] == "SIP": log.info("-- SIP alg found. Updating") rule_found = True alg["conf"]["rules"][i]["enabled"] = args["enable_alg"] break # if SIP alg not found append it to the rules if not rule_found: log.info("-- SIP alg not found. adding sip rule") alg["conf"]["rules"].append({ "alg": "SIP", "enabled": args["enable_alg"] }) # update the rules log.info("-- updating alg entry") r = cgx.put.element_extensions(element["site_id"], element["id"], alg["id"], alg) if not r: jd_detailed(r) raise ValueError("cant update alg extension")
def createnewrule(cgx_session, TYPE, SRC_POLICY_SET, SRC_POLICY_RULE, DST_POLICY_SET, DST_POLICY_RULE): if TYPE == "NW": if SRC_POLICY_SET in nwset_name_id_dict.keys(): nwpid = nwset_name_id_dict[SRC_POLICY_SET] rulesidname = nwpolicyid_rulenameiddict_dict[nwpid] rulesnameid = nwpolicyid_rulenameiddict_dict[nwpid] if SRC_POLICY_RULE in rulesnameid.keys(): print("INFO: Rule {} found in Network Policy Set {}".format( SRC_POLICY_RULE, SRC_POLICY_SET)) rid = rulesnameid[SRC_POLICY_RULE] resp = cgx_session.get.networkpolicyrules( networkpolicyset_id=nwpid, networkpolicyrule_id=rid) if resp.cgx_status: rule = resp.cgx_content if DST_POLICY_SET in nwset_name_id_dict.keys(): dstpolid = nwset_name_id_dict[DST_POLICY_SET] print("INFO: Destination Network Policy Set {} found". format(DST_POLICY_SET)) print("INFO: Creating rule {} in policy {}".format( DST_POLICY_RULE, DST_POLICY_SET)) nwrulepayload = { "name": DST_POLICY_RULE, "description": rule.get("description", None), "tags": rule.get("tags", None), "network_context_id": rule.get("network_context_id", None), "source_prefixes_id": rule.get("source_prefixes_id", None), "destination_prefixes_id": rule.get("destination_prefixes_id", None), "app_def_ids": rule.get("app_def_ids", None), "paths_allowed": rule.get("paths_allowed", None), "service_context": rule.get("service_context", None), "order_number": rule.get("order_number", None), "enabled": rule.get("enabled", None) } resp = cgx_session.post.networkpolicyrules( networkpolicyset_id=dstpolid, data=nwrulepayload) if resp.cgx_status: print( "SUCCESS: Rule {} created on Network Policy Set {}" .format(DST_POLICY_RULE, DST_POLICY_SET)) else: print("ERR: Could not create the rule") cloudgenix.jd_detailed(resp) else: print( "ERR: Invalid Destination {} Policy set name: {}". format(TYPE, DST_POLICY_SET)) print("Please select from the following:") for x in nwset_name_id_dict.keys(): print("\t{}".format(x)) else: print("ERR: Rule {} does not exist in Network Policy Set {}". format(SRC_POLICY_RULE, SRC_POLICY_SET)) print("Please select from the following rules:") for x in rulesnameid.keys(): print("\t{}".format(x)) else: print("ERR: Invalid Source {} Policy set name: {}".format( TYPE, SRC_POLICY_SET)) print("Please select from the following:") for x in nwset_name_id_dict.keys(): print("\t{}".format(x)) elif TYPE == "QOS": if SRC_POLICY_SET in qosset_name_id_dict.keys(): qospid = qosset_name_id_dict[SRC_POLICY_SET] rulesidname = qospolicyid_rulenameiddict_dict[qospid] rulesnameid = qospolicyid_rulenameiddict_dict[qospid] if SRC_POLICY_RULE in rulesnameid.keys(): print("INFO: Rule {} found in Priority Policy Set {}".format( SRC_POLICY_RULE, SRC_POLICY_SET)) rid = rulesnameid[SRC_POLICY_RULE] resp = cgx_session.get.prioritypolicyrules( prioritypolicyset_id=qospid, prioritypolicyrule_id=rid) if resp.cgx_status: rule = resp.cgx_content if DST_POLICY_SET in qosset_name_id_dict.keys(): dstpolid = qosset_name_id_dict[DST_POLICY_SET] print("INFO: Destination Priority Policy Set {} found". format(DST_POLICY_SET)) print("INFO: Creating rule {} in policy {}".format( DST_POLICY_RULE, DST_POLICY_SET)) qosrulepayload = { "name": DST_POLICY_RULE, "description": rule.get("description", None), "tags": rule.get("tags", None), "network_context_id": rule.get("network_context_id", None), "source_prefixes_id": rule.get("source_prefixes_id", None), "destination_prefixes_id": rule.get("destination_prefixes_id", None), "app_def_ids": rule.get("app_def_ids", None), "priority_number": rule.get("priority_number", None), "dscp": rule.get("dscp", None), "order_number": rule.get("order_number", None), "enabled": rule.get("enabled", None) } resp = cgx_session.post.prioritypolicyrules( prioritypolicyset_id=dstpolid, data=qosrulepayload) if resp.cgx_status: print( "SUCCESS: Rule {} created on Priority Policy Set {}" .format(DST_POLICY_RULE, DST_POLICY_SET)) else: print("ERR: Could not create the rule") cloudgenix.jd_detailed(resp) else: print( "ERR: Invalid Destination {} Policy set name: {}". format(TYPE, DST_POLICY_SET)) print("Please select from the following:") for x in qosset_name_id_dict.keys(): print("\t{}".format(x)) else: print("ERR: Rule {} does not exist in Priority Policy Set {}". format(SRC_POLICY_RULE, SRC_POLICY_SET)) print("Please select from the following rules:") for x in rulesnameid.keys(): print("\t{}".format(x)) else: print("ERR: Invalid Source {} Policy set name: {}".format( TYPE, SRC_POLICY_SET)) print("Please select from the following:") for x in qosset_name_id_dict.keys(): print("\t{}".format(x)) else: print( "ERR: Invalid Policy Type: {}. Please pick NW or QOS".format(TYPE)) return
#!/usr/bin ptpython3 import cgxinit import requests from cloudgenix import jd, jd_detailed if __name__ == "__main__": # parse commands and get CGX cgx, args = cgxinit.go() IPs = set() # get the json file for key, row in requests.get(args["url"]).json().items(): for IP in row['ip_ranges']: if "255/32" not in IP: IPs.add(IP) # get the list of existing prefixes in the prefix list for filter in cgx.get.globalprefixfilters().cgx_content['items']: if filter["name"] == args["prefix"]: filter["filters"][0]["ip_prefixes"] = list(IPs) res = cgx.put.globalprefixfilters(filter["id"], filter) if not res: jd_detailed(res) else: print(f"{args['prefix']} update successfuly")
def createdicts(cgx_session): print("INFO: Building Translation dicts") print("\tSites..") resp = cgx_session.get.sites() if resp.cgx_status: sitelist = resp.cgx_content.get("items", None) for site in sitelist: sid = site['id'] sname = site['name'] site_id_name_dict[sid] = sname site_name_id_dict[sname] = sid else: print("ERR: Could not get sites") print(cloudgenix.jd_detailed(resp)) print("\tElements..") resp = cgx_session.get.elements() if resp.cgx_status: elemlist = resp.cgx_content.get("items", None) for elem in elemlist: eid = elem['id'] ename = elem['name'] if ename is None: ename = elem['serial_number'] elem_id_name_dict[eid] = ename sid = elem['site_id'] if sid == "1": continue eid_sid_dict[eid] = sid print("\tInterfaces..") for eid in eid_sid_dict.keys(): sid = eid_sid_dict[eid] if sid == "1": continue resp = cgx_session.get.interfaces(site_id=sid, element_id=eid) if resp.cgx_status: intflist = resp.cgx_content.get("items",None) for intf in intflist: iid = intf['id'] iname = intf['name'] intf_id_name_dict[(sid,eid,iid)] = iname intf_name_id_dict[(sid,eid,iname)] = iid else: print("ERR: Could not query for interfaces") print(cloudgenix.jd_detailed(resp)) print("\tSite WAN Interfaces..") for sid in site_id_name_dict.keys(): resp = cgx_session.get.waninterfaces(site_id = sid) if resp.cgx_status: swilist = resp.cgx_content.get("items", None) for swi in swilist: swiid = swi['id'] swiname = swi['name'] swi_id_name_dict[(sid,swiid)] = swiname swi_name_id_dict[(sid,swiname)] = swiid else: print("ERR: Could not query for site wan interfaces") print(cloudgenix.jd_detailed(resp)) return
def configextention(cgx_session, site, element, interface, prefix, app, action): if site in sitename_siteid_dict.keys(): ssid = sitename_siteid_dict[site] else: print("ERR: Site {} does not exist".format(site)) cleanexit(cgx_session) if element in elemname_elemid_dict.keys(): eid = elemname_elemid_dict[element] sid = elemid_siteid_dict[eid] if ssid != sid: print("ERR: Element {} does not belong to site {}".format( element, site)) cleanexit(cgx_session) interfacenamelist = elemname_intfnamelist_dict[element] if interface in interfacenamelist: iid = intfname_intfid_dict[(sid, eid, interface)] resp = cgx_session.get.element_extensions(site_id=sid, element_id=eid) if resp.cgx_status: extensionlist = resp.cgx_content.get("items", None) entitynotfound = True for ext in extensionlist: if ext['entity_id'] == iid: entitynotfound = False config = ext.get("conf", None) rules = config.get("rules", None) print("INFO: Configuration rules {} found on {}:{}:{}". format(rules, siteid_sitename_dict[sid], elemid_elemname_dict[eid], interface)) rules.append({ "app": app, "action": action, "prefix": prefix }) config['rules'] = rules ext['conf'] = config resp = cgx_session.put.element_extensions( site_id=sid, element_id=eid, extension_id=ext['id'], data=ext) if resp.cgx_status: print("INFO: Configuration {} edited on {}:{}:{}". format(rules, siteid_sitename_dict[sid], elemid_elemname_dict[eid], interface)) cleanexit(cgx_session) else: print( "ERR: Could not update configuration to {} on {}:{}:{}" .format(rules, siteid_sitename_dict[sid], elemid_elemname_dict[eid], interface)) cloudgenix.jd_detailed(resp) cleanexit(cgx_session) if entitynotfound: postpayload = { "name": "allowssh", "namespace": "devicemanagement/interface", "entity_id": iid, "disabled": False, "conf": { "rules": [{ "prefix": prefix, "app": app, "action": action }] } } rules = postpayload["conf"]["rules"] resp = cgx_session.post.element_extensions( site_id=sid, element_id=eid, data=postpayload) if resp.cgx_status: print( "INFO: Added configuration {} to {}:{}:{}".format( rules, siteid_sitename_dict[sid], elemid_elemname_dict[eid], interface)) else: print( "ERR: Could not update configuration to {} on {}:{}:{}" .format(rules, siteid_sitename_dict[sid], elemid_elemname_dict[eid], interface)) cloudgenix.jd_detailed(resp) else: print("ERR: Interface {} does not exist on element {}".format( interface, element)) cleanexit(cgx_session) else: print("ERR: Element {} not found.".format(element)) cleanexit(cgx_session) return
def go(): ############################################################################ # Begin Script, parse arguments. ############################################################################ # Parse arguments parser = argparse.ArgumentParser(description="{0}.".format(SCRIPT_NAME)) # Allow Controller modification and debug level sets. controller_group = parser.add_argument_group('API', 'These options change how this program connects to the API.') controller_group.add_argument("--controller", "-C", help="Controller URI, ex. " "C-Prod: https://api.elcapitan.cloudgenix.com", default="https://api.elcapitan.cloudgenix.com") login_group = parser.add_argument_group('Login', 'These options allow skipping of interactive login') login_group.add_argument("--email", "-E", help="Use this email as User Name instead of prompting", default=None) login_group.add_argument("--pass", "-P", help="Use this Password instead of prompting", default=None) args = vars(parser.parse_args()) ############################################################################ # Instantiate API & Login ############################################################################ cgx_session = cloudgenix.API(controller=args["controller"], ssl_verify=False) print("{0} v{1} ({2})\n".format(SCRIPT_NAME, SDK_VERSION, cgx_session.controller)) # login logic. Use cmdline if set, use AUTH_TOKEN next, finally user/pass from config file, then prompt. # figure out user if args["email"]: user_email = args["email"] elif CLOUDGENIX_USER: user_email = CLOUDGENIX_USER else: user_email = None # figure out password if args["pass"]: user_password = args["pass"] elif CLOUDGENIX_PASSWORD: user_password = CLOUDGENIX_PASSWORD else: user_password = None # check for token if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["pass"]: cgx_session.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if cgx_session.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit() else: while cgx_session.tenant_id is None: cgx_session.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not cgx_session.tenant_id: user_email = None user_password = None ############################################################################ # Get Operators ############################################################################ roles_id_name = {} resp = cgx_session.get.roles() if resp.cgx_status: rolelist = resp.cgx_content.get("items", None) for role in rolelist: roles_id_name[role['id']] = role['name'] else: print("ERR: Could not retrieve roles") cloudgenix.jd_detailed(resp) userlist = pd.DataFrame() print("INFO: Retrieving operators") resp = cgx_session.get.tenant_operators() if resp.cgx_status: operators = resp.cgx_content.get("items", None) for op in operators: first_name = "" last_name = "" email = "" rolestr = "" crolestr = "" if "first_name" in op.keys(): first_name = op.get("first_name", None) if "last_name" in op.keys(): last_name = op.get("last_name", None) if "email" in op.keys(): email = op.get("email", None) if "roles" in op.keys(): roles = op.get("roles", None) for role in roles: rolestr = rolestr + "{},".format(role['name']) if "custom_roles" in op.keys(): customroles = op.get("custom_roles", None) for crole in customroles: cid = crole['id'] if cid in roles_id_name.keys(): cname = roles_id_name[cid] else: cname = cid crolestr = crolestr + "{},".format(cname) userlist = userlist.append({"First Name": first_name, "Last Name": last_name, "Email": email, "Roles": rolestr[:-1], "Custom Roles": crolestr[:-1]}, ignore_index=True) ############################################################################ # Store file ############################################################################ curtime_str = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S') filename = "{}/operators_{}.csv".format(os.getcwd(), curtime_str) print("INFO: Operators retrieved.. Saving to file {}".format(filename)) userlist.to_csv(filename,index=False) else: print("ERR: Could not query operators") cloudgenix.jd_detailed(resp) ############################################################################ # Logout to clear session. ############################################################################ cgx_session.get.logout() print("INFO: Logging Out") sys.exit()
def go(): ############################################################################ # Begin Script, parse arguments. ############################################################################ # Parse arguments parser = argparse.ArgumentParser(description="{0}.".format(SCRIPT_NAME)) # Allow Controller modification and debug level sets. controller_group = parser.add_argument_group('API', 'These options change how this program connects to the API.') controller_group.add_argument("--controller", "-C", help="Controller URI, ex. " "C-Prod: https://api.elcapitan.cloudgenix.com", default="https://api.elcapitan.cloudgenix.com") login_group = parser.add_argument_group('Login', 'These options allow skipping of interactive login') login_group.add_argument("--email", "-E", help="Use this email as User Name instead of prompting", default=None) login_group.add_argument("--pass", "-P", help="Use this Password instead of prompting", default=None) # Commandline for entering Site info site_group = parser.add_argument_group('Device Specific information', 'Provide the site and element name where ALG needs to be disabled') site_group.add_argument("--sitename", "-SN", help="Name of the Site", default=None) site_group.add_argument("--elemname", "-EN", help="Name of the Element", default=None) site_group.add_argument("--action", "-A", help="Action for ALG configuration. Select ENABLE or DISABLE", default=None) args = vars(parser.parse_args()) ############################################################################ # Extract Command Line Arguments ############################################################################ sitename = args['sitename'] elemname = args['elemname'] action = args['action'] if (sitename is None) or (elemname is None): print("ERR: Please provide both Site and Element names") sys.exit() if action not in ["ENABLE", "DISABLE"]: print("ERR: Incorrect action: {}. Please select ENABLE or DISABLE".format(action)) sys.exit() ############################################################################ # Instantiate API & Login ############################################################################ cgx_session = cloudgenix.API(controller=args["controller"], ssl_verify=False) print("{0} v{1} ({2})\n".format(SCRIPT_NAME, SDK_VERSION, cgx_session.controller)) # login logic. Use cmdline if set, use AUTH_TOKEN next, finally user/pass from config file, then prompt. # figure out user if args["email"]: user_email = args["email"] elif CLOUDGENIX_USER: user_email = CLOUDGENIX_USER else: user_email = None # figure out password if args["pass"]: user_password = args["pass"] elif CLOUDGENIX_PASSWORD: user_password = CLOUDGENIX_PASSWORD else: user_password = None # check for token if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["pass"]: cgx_session.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if cgx_session.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit() else: while cgx_session.tenant_id is None: cgx_session.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not cgx_session.tenant_id: user_email = None user_password = None ############################################################################ # Validate Site & Element Name and Config SIP ALG ############################################################################ createdicts(cgx_session) if sitename in sitename_siteid_dict.keys(): sid = sitename_siteid_dict[sitename] if elemname in elemname_sitename_dict.keys(): sname = elemname_sitename_dict[elemname] if sname == sitename: eid = elemname_elemid_dict[elemname] print("INFO: Element {} found attached to site {}".format(elemname, sitename)) resp = cgx_session.get.element_extensions(site_id=sid, element_id=eid) if resp.cgx_status: extensions = resp.cgx_content.get("items",None) extfound = False for ext in extensions: if ext['namespace'] == "algconfig": print("INFO: ALG Config on {}:{}".format(sitename,elemname)) extfound = True conf = { "rules":[ { "alg": "SIP", "enabled": actionxlate[action] } ] } ext["conf"] = conf resp = cgx_session.put.element_extensions(site_id=sid, element_id=eid, extension_id=ext['id'],data=ext) if resp.cgx_status: print("INFO: SIP ALG {}D on {}:{}".format(action,sitename,elemname)) else: print("ERR: Could not edit ALG config on {}:{}\n{}".format(sitename,elemname,cloudgenix.jd_detailed(resp))) if not extfound: print("INFO: No ALG Config on {}:{}".format(sitename,elemname)) data = { "name" : "alg", "namespace":"algconfig", "entity_id": None, "conf":{ "rules":[ { "alg": "SIP", "enabled": actionxlate[action] } ] }, "disabled":False, } print("Using element extensions API to configure: {}".format(data)) resp = cgx_session.post.element_extensions(site_id=sid, element_id=eid, data=data) if resp.cgx_status: print("INFO: SIP ALG {}D on {}:{}".format(action,sitename, elemname)) else: print("ERR: Could not {} SIP ALG.\n {}".format(action, cloudgenix.jd_detailed(resp))) else: print("ERR: Element {} is not attached to site {}. Please reenter site name and element name".format(elemname,sitename)) else: print("ERR: Element {} not found. Please reenter element name".format(elemname)) else: print("ERR: Site {} not found. Please reenter site name".format(sitename)) ############################################################################ # Logout to clear session. ############################################################################ cgx_session.get.logout() print("INFO: Logging Out") sys.exit()
template = { "name": "REPLACE", "description": None, "tags": None, "ipv4_config": { "prefixes": ["REPLACE"], "dhcp_relay": None, "dhcp_server": None, "default_routers": None }, "scope": "global", "network_context_id": None } # add one prefix at a time for prefix in ip_list: if prefix in existing: print(f"{prefix} already exists") else: # add prefix to cgx template['ipv4_config']['prefixes'] = [prefix] template['name'] = "p-" + prefix res = cgx.post.lannetworks(site_id, template) if not res: print(f"ERROR: Couldn't add {prefix}") cloudgenix.jd_detailed(res) sys.exit() else: print(f"Added {prefix} to site")
def go(): ############################################################################ # Begin Script, start login / argument handling. ############################################################################ # Parse arguments parser = argparse.ArgumentParser(description="{0}.".format(SCRIPT_NAME)) # Allow Controller modification and debug level sets. controller_group = parser.add_argument_group('API', 'These options change how this program connects to the API.') controller_group.add_argument("--controller", "-C", help="Controller URI, ex. " "C-Prod: https://api.cloudgenix.com", default=None) controller_group.add_argument("--insecure", "-I", help="Disable SSL certificate and hostname verification", dest='verify', action='store_false', default=True) login_group = parser.add_argument_group('Login', 'These options allow skipping of interactive login') login_group.add_argument("--email", "-E", help="Use this email as User Name instead of prompting", default=None) login_group.add_argument("--pass", "-PW", help="Use this Password instead of prompting", default=None) debug_group = parser.add_argument_group('Debug', 'These options enable debugging output') debug_group.add_argument("--debug", "-D", help="Verbose Debug info, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) ############################################################################ # Instantiate API ############################################################################ cgx_session = cloudgenix.API(controller=args["controller"], ssl_verify=args["verify"]) cgx_session.set_debug(args["debug"]) ############################################################################ # Draw Interactive login banner, run interactive login including args above. ############################################################################ print("{0} v{1} ({2})\n".format(SCRIPT_NAME, SDK_VERSION, cgx_session.controller)) # login logic. Use cmdline if set, use AUTH_TOKEN next, finally user/pass from config file, then prompt. # figure out user if args["email"]: user_email = args["email"] elif CLOUDGENIX_USER: user_email = CLOUDGENIX_USER else: user_email = None # figure out password if args["pass"]: user_password = args["pass"] elif CLOUDGENIX_PASSWORD: user_password = CLOUDGENIX_PASSWORD else: user_password = None # check for token if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["pass"]: cgx_session.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if cgx_session.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit() else: while cgx_session.tenant_id is None: cgx_session.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not cgx_session.tenant_id: user_email = None user_password = None ############################################################################ # Iterate through tenant_ids and get machines, elements and sites ############################################################################ curtime_str = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S') tenantname = cgx_session.tenant_name tenantname = tenantname.replace(" ","") tenantname = tenantname.replace("/","") filename = "{}/{}_inventory_{}.csv".format(os.getcwd(),tenantname,curtime_str) with open(filename, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=HEADER) writer.writeheader() hwids = [] machines = {} resp = cgx_session.get.machines() if resp.cgx_status: machinelist = resp.cgx_content.get("items", None) print("\tMachines: {}".format(len(machinelist))) for machine in machinelist: if machine['machine_state'] in ["claimed"]: em_element_id = machine["em_element_id"] else: em_element_id = "n/a" machines[machine["sl_no"]] = {"em_element_id": em_element_id, "model_name": machine["model_name"], "software_version": machine["image_version"], "ship_state": machine["ship_state"]} hwids.append(machine["sl_no"]) else: print("ERR: Failed to retrieve machines") cloudgenix.jd_detailed(resp) elements = {} elemid_siteid_dict = {} resp = cgx_session.get.elements() if resp.cgx_status: elemlist = resp.cgx_content.get("items", None) print("\tElements: {}".format(len(elemlist))) for elem in elemlist: elements[elem['serial_number']] = {"site_id": elem["site_id"], "software_version": elem["software_version"], "name": elem["name"], "role": elem["role"], "state": elem["state"]} elemid_siteid_dict[elem["id"]] = elem["site_id"] else: print("ERR: Failed to retrieve elements") cloudgenix.jd_detailed(resp) sites = {} resp = cgx_session.get.sites() if resp.cgx_status: sitelist = resp.cgx_content.get("items", None) print("\tSites: {}".format(len(sitelist))) for site in sitelist: sites[site["id"]] = {"name": site["name"], "admin_state": site["admin_state"], "address": site["address"], "location": site["location"]} else: print("ERR: Failed to retrieve sites") cloudgenix.jd_detailed(resp) # Extract data from dicts for CSV hwidslist = list(dict.fromkeys(hwids)) for item in hwidslist: site_name = "Unbound" element_name = "Unclaimed" element_role = "n/a" site_state = "n/a" element_state = "n/a" street = "n/a" city = "n/a" state = "n/a" country = "n/a" post_code = "n/a" longitude = "n/a" latitude = "n/a" model_type = None model_name = None curmachine = machines[item] ship_state = curmachine["ship_state"] software_version = curmachine["software_version"] model_name = curmachine["model_name"] if "v" in model_name: model_type = "Virtual" else: model_type = "Physical" if item in elements.keys(): curelement = elements[item] software_version = curelement["software_version"] element_name = curelement["name"] element_state = curelement["state"] element_role = curelement["role"] site_id = curelement["site_id"] if site_id != "1": cursite = sites[site_id] site_name = cursite["name"] site_state = cursite["admin_state"] address = cursite["address"] if address: street = "{} {}".format(address.get("street",None),address.get("street2",None)) city = address.get("city") state = address.get("state") country = address.get("country") post_code = address.get("post_code") location = cursite["location"] longitude = location["longitude"] latitude = location["latitude"] writer.writerow({ "serial_number": item, "model_name":model_name, "model_type":model_type, "software_version": software_version, "site_name": site_name, "element_name": element_name, "element_role": element_role, "site_state": site_state, "element_state": element_state, "street": street, "city": city, "state": state, "country": country, "post_code": post_code, "longitude": longitude, "latitude": latitude}) ############################################################# # Logout ############################################################# print("INFO: Logging Out") cgx_session.get.logout() sys.exit()
def createcustomapps(yamldata, cgx_session): appconfig = yamldata.get("apps", None) for app in appconfig.keys(): config = appconfig[app] iprules = config.get("ip_rules", None) if iprules is not None: for i, rule in enumerate(iprules): dstfilter = rule.get("dest_filters", None) if dstfilter is not None: for dj, df in enumerate(dstfilter): if df in global_pfname_id_dict.keys(): pfid = global_pfname_id_dict[df] config["ip_rules"][i]["dest_filters"][dj] = pfid yamlreplace[df] = pfid else: print("ERR: IP Rule Destination Prefix Filter {} not found. Please reenter the Prefix Filter for {}".format(df, app)) cleanexit(cgx_session) srcfilter = rule.get("src_filters", None) if srcfilter is not None: for sj, sf in enumerate(srcfilter): if sf in global_pfname_id_dict.keys(): pfid = global_pfname_id_dict[sf] config["ip_rules"][i]["src_filters"][sj] = pfid yamlreplace[sf] = pfid else: print("ERR: IP Rule Source Prefix Filter {} not found. Please reenter the Prefix Filter for {}".format(sf, app)) cleanexit(cgx_session) tcprules = config.get("tcp_rules", None) if tcprules is not None: for i, rule in enumerate(tcprules): client_filters = rule.get("client_filters", None) if client_filters is not None: for clj, clf in enumerate(client_filters): if clf in global_pfname_id_dict.keys(): pfid = global_pfname_id_dict[clf] config["tcp_rules"][i]["client_filters"][clj] = pfid yamlreplace[clf] = pfid else: print("ERR: TCP Client Prefix Filter {} not found. Please reenter the Prefix Filter for {}".format(clf, app)) cleanexit(cgx_session) server_filters = rule.get("server_filters", None) if server_filters is not None: for srj, srf in enumerate(server_filters): if srf in global_pfname_id_dict.keys(): pfid = global_pfname_id_dict[srf] config["tcp_rules"][i]["server_filters"][srj] = pfid yamlreplace[srf] = pfid else: print("ERR: TCP Server Prefix Filter {} not found. Please reenter the Prefix Filter for {}".format(srf, app)) cleanexit(cgx_session) udprules = config.get("udp_rules", None) if udprules is not None: for i, rule in enumerate(udprules): udp_filters = rule.get("udp_filters", None) if udp_filters is not None: for uj, uf in enumerate(udp_filters): if uf in global_pfname_id_dict.keys(): pfid = global_pfname_id_dict[uf] config["udp_rules"][i]["udp_filters"][uj] = pfid yamlreplace[uf] = pfid else: print("ERR: UDP Prefix Filter {} not found. Please reenter the Prefix Filter for {}".format(uf, app)) cleanexit(cgx_session) resp = cgx_session.post.appdefs(data=config, api_version="v2.3") if resp.cgx_status: print("SUCCESS: Custom App {} created".format(app)) else: print("ERR: Could not create Custom App {}".format(app)) cloudgenix.jd_detailed(resp) return
def go(): ############################################################################ # Begin Script, parse arguments. ############################################################################ # Parse arguments parser = argparse.ArgumentParser(description="{0}.".format(SCRIPT_NAME)) # Allow Controller modification and debug level sets. controller_group = parser.add_argument_group( 'API', 'These options change how this program connects to the API.') controller_group.add_argument( "--controller", "-C", help="Controller URI, ex. " "C-Prod: https://api.elcapitan.cloudgenix.com", default="https://api.elcapitan.cloudgenix.com") login_group = parser.add_argument_group( 'Login', 'These options allow skipping of interactive login') login_group.add_argument( "--email", "-E", help="Use this email as User Name instead of prompting", default=None) login_group.add_argument("--pass", "-P", help="Use this Password instead of prompting", default=None) # Commandline for entering Auth Token info auth_group = parser.add_argument_group( 'Auth Token Specific information', 'Information shared here will be used to create an auth token') auth_group.add_argument( "--roles", "-R", help= "Roles. Allowed values: super, viewonly, secadmin, nwadmin, iamadmin. Multiple roles should be comma separated", default=None) auth_group.add_argument( "--expirationdate", "-ED", help="Expiration Date in format YYYY-MM-DDTHH:MM:SSZ", default=None) args = vars(parser.parse_args()) ############################################################################ # Parse Args ############################################################################ roles = args["roles"] role_ds = [] if roles: if "," in roles: tmp = roles.split(",") for role in tmp: if role not in ROLES: print( "ERR: Invalid role. Please choose from: super,viewonly,secadmin,nwadmin or iamadmin" ) sys.exit() else: mappedrole = rolemap[role] role_ds.append({"name": mappedrole}) else: if roles in ROLES: mappedrole = rolemap[roles] role_ds.append({"name": mappedrole}) else: print( "ERR: Invalid role. Please choose from: super,viewonly,secadmin,nwadmin or iamadmin" ) sys.exit() expirationdate = args["expirationdate"] timestamp = None if expirationdate: if "." in expirationdate: utc_dt = datetime.datetime.strptime(expirationdate, "%Y-%m-%dT%H:%M:%S.%fZ") else: utc_dt = datetime.datetime.strptime(expirationdate, "%Y-%m-%dT%H:%M:%SZ") # Convert UTC datetime to seconds since the Epoch timestamp = (utc_dt - datetime.datetime(1970, 1, 1)).total_seconds() * 1000 ############################################################################ # Instantiate API & Login ############################################################################ cgx_session = cloudgenix.API(controller=args["controller"], ssl_verify=False) print("{0} v{1} ({2})\n".format(SCRIPT_NAME, SDK_VERSION, cgx_session.controller)) # login logic. Use cmdline if set, use AUTH_TOKEN next, finally user/pass from config file, then prompt. # figure out user if args["email"]: user_email = args["email"] elif CLOUDGENIX_USER: user_email = CLOUDGENIX_USER else: user_email = None # figure out password if args["pass"]: user_password = args["pass"] elif CLOUDGENIX_PASSWORD: user_password = CLOUDGENIX_PASSWORD else: user_password = None # check for token if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["pass"]: cgx_session.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if cgx_session.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit() else: while cgx_session.tenant_id is None: cgx_session.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not cgx_session.tenant_id: user_email = None user_password = None ############################################################################ # Create Auth Token ############################################################################ authdata = {"roles": role_ds, "expires_utc_ms": timestamp} operator_id = cgx_session.operator_id print("INFO: Creating AUTH Token for operator {} using data {}".format( operator_id, authdata)) resp = cgx_session.post.authtokens(operator_id=operator_id, data=authdata) if resp.cgx_status: print("Auth creation successful!") authtoken = resp.cgx_content.get("x_auth_token", None) print(authtoken) else: print("ERR: Could not create auth token") cloudgenix.jd_detailed(resp) ############################################################################ # Logout to clear session. ############################################################################ cgx_session.get.logout() print("INFO: Logging Out") sys.exit()