logging.basicConfig(level=logging.INFO) clilogger = logging.getLogger() clilogger.setLevel(logging.INFO) elif DEBUG_LEVEL >= 2: logging.basicConfig(level=logging.DEBUG) clilogger = logging.getLogger() clilogger.setLevel(logging.DEBUG) else: logging.basicConfig(level=logging.WARNING) clilogger = logging.getLogger() clilogger.setLevel(logging.WARNING) # ok. try to login. if CLOUDGENIX_SSL_VERIFY is None and CLOUDGENIX_CONTROLLER is None: # Normal login sdk = cloudgenix.API() elif CLOUDGENIX_SSL_VERIFY is None: # custom controller sdk = cloudgenix.API(controller=CLOUDGENIX_CONTROLLER) elif CLOUDGENIX_CONTROLLER is None: # custom SSL Verification setting. sdk = cloudgenix.API(ssl_verify=CLOUDGENIX_SSL_VERIFY) else: # custom everything. sdk = cloudgenix.API(controller=CLOUDGENIX_CONTROLLER, ssl_verify=CLOUDGENIX_SSL_VERIFY) # actual api token use token_login = sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) # if login fails, sdk.tenant_id will be None.
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()
def servicelinks(sdk=None, idname_obj=None, controller="https://api.elcapitan.cloudgenix.com", ssl_verify=True, prisma_all_endpoints=False): prisma_name2ip = {} prisma_status = False if sdk is None: # need to instantiate sdk = cloudgenix.API(controller=controller, ssl_verify=ssl_verify) if not sdk.tenant_id: # need to login. if AUTH_TOKEN is None: sdk.interactive.login() else: sdk.interactive.use_token(AUTH_TOKEN) # Check Prisma API key if specified if PRISMA_API_KEY is not None: gpcs = GPCloudServiceOperations(PRISMA_API_KEY) print("Checking Prisma API Key.. ", end="", flush=True) prisma_status, prisma_name2ip, _, message = gpcs.remote_gw_addr_dicts() if not prisma_status: print("ERROR, message: {0}.".format(message), flush=True) sys.exit(1) else: print("Success." if message is None else "{0}.".format(message), flush=True) if sdk.tenant_id is None: print( "ERROR: CloudGenix API Login failed, please check credentials or AUTH_TOKEN." ) sys.exit(1) else: print("Logged into CloudGenix Tenant {0}.".format(sdk.tenant_name), flush=True) # gen id_name maps if idname_obj is None: id2n_obj = cloudgenix_idname.CloudGenixIDName(sdk) else: id2n_obj = idname_obj id2n_obj.update_sites_cache() id2n = id2n_obj.generate_sites_map() id2n_obj.update_elements_cache() id2n.update(id2n_obj.generate_elements_map()) element_id2site = id2n_obj.generate_elements_map(key_val='id', value_val='site_id') element_id2connected = id2n_obj.generate_elements_map( key_val='id', value_val='connected') # cloudgenix.jd(element_id2connected) id2n_obj.update_interfaces_cache() id2n.update(id2n_obj.generate_interfaces_map()) prisma_servicelinks = [] for interface in id2n_obj.interfaces_cache: tags = interface.get('tags', []) if isinstance(tags, list) and 'AUTO-PRISMA_MANAGED' in tags: prisma_servicelinks.append(interface) servicelink_status_list = [] for sl in prisma_servicelinks: description = sl.get('description', '') prisma_rno_list = remotenet_re.findall( description if description is not None else "") if len(prisma_rno_list) >= 1: prisma_rno = ";".join(prisma_rno_list) else: prisma_rno = "Unknown" element_id = sl.get('element_id') site_id = element_id2site.get(element_id, "Could not get site") element_connected = element_id2connected.get(element_id, False) interface_id = sl.get('id') parent_if_id = sl.get('parent') admin_state = sl.get('admin_up') # check for endpoint ip config sl_config = sl.get('service_link_config', {}) if sl_config is not None: peer_config = sl_config.get('peer', {}) else: peer_config = {} if peer_config is not None: conf_ip_list = peer_config.get('ip_addresses', []) else: conf_ip_list = [] if len(conf_ip_list) == 0: conf_ip = "No IP" else: conf_ip = ";".join(conf_ip_list) resp = sdk.get.interfaces_status(site_id, element_id, interface_id) if not element_connected: # if element is not connected, status is stale. operational_state = "Unknown_Offline" extended_state = "Unknown_Offline" elif resp.cgx_status: operational_state = resp.cgx_content.get("operational_state") extended_state = resp.cgx_content.get("extended_state") else: operational_state = "Unknown" extended_state = "Unknown" site_name = id2n.get(site_id, site_id) element_name = id2n.get(element_id, element_id) interface_name = id2n.get(interface_id, interface_id) parent_if_name = id2n.get(parent_if_id, parent_if_id) if not prisma_status: servicelink_status_list.append({ "Site": site_name, "Element": element_name, "Interface": interface_name, "Element Online": "Online" if element_connected else "Offline", "Admin State": str(admin_state), "Operational State": operational_state, "Extended State": extended_state, "Prisma Remote On-boarding": prisma_rno, "Parent Interface": parent_if_name, "Configured Endpoint": conf_ip }) else: # in prisma endpoint IP mode. check if we want all tunnels or just admin down ones. if prisma_all_endpoints or admin_state is False: servicelink_status_list.append({ "Site": site_name, "Element": element_name, "Interface": interface_name, "Element Online": "Online" if element_connected else "Offline", "Admin State": str(admin_state), "Operational State": operational_state, "Extended State": extended_state, "Prisma Remote On-boarding": prisma_rno, "Parent Interface": parent_if_name, "Configured Endpoint": conf_ip, "Prisma API Endpoint IP": prisma_name2ip.get(prisma_rno) }) return servicelink_status_list
def go(): """ Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site() :return: No return """ # Parse arguments parser = argparse.ArgumentParser(description="{0} ({1})".format( GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION)) #### # # Add custom cmdline argparse arguments here # #### custom_group = parser.add_argument_group('custom_args', 'Circuit matching arguments') custom_group.add_argument("--cost", help="Cost to set the Wan Interfaces to (0-255)", required=True, type=int) custom_group.add_argument( "--category", help="Circuit Category (waninterface label) name to match for change.", required=True, type=text_type) custom_group.add_argument( "--simulate", help="Simulate changes (don't actually make any changes.)", action='store_true', default=False) custom_group.add_argument( '--output', type=text_type, default=None, help= "Output to filename. If not specified, will print output on STDOUT.") #### # # End custom cmdline arguments # #### # Standard CloudGenix script switches. 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. https://api.elcapitan.cloudgenix.com", default=None) 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 cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument( "--password", "-PW", help="Use this Password instead of cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--insecure", "-I", help="Do not verify SSL certificate", action='store_true', default=False) login_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) debug_group = parser.add_argument_group( 'Debug', 'These options enable debugging output') debug_group.add_argument("--sdkdebug", "-D", help="Enable SDK Debug output, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) sdk_debuglevel = args["sdkdebug"] # Build SDK Constructor if args['controller'] and args['insecure']: sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False) elif args['controller']: sdk = cloudgenix.API(controller=args['controller']) elif args['insecure']: sdk = cloudgenix.API(ssl_verify=False) else: sdk = cloudgenix.API() # check for region ignore if args['ignore_region']: sdk.ignore_region = True # SDK debug, default = 0 # 0 = logger handlers removed, critical only # 1 = logger info messages # 2 = logger debug messages. if sdk_debuglevel == 1: # CG SDK info sdk.set_debug(1) elif sdk_debuglevel >= 2: # CG SDK debug sdk.set_debug(2) # 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["password"]: user_password = args["password"] 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["password"]: sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if sdk.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit(1) else: while sdk.tenant_id is None: sdk.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not sdk.tenant_id: user_email = None user_password = None #### # # Do your custom work here, or call custom functions. # #### result = update_costs(sdk, args['cost'], args['category'], args['simulate'], args['output'])
def go(): """ Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site() :return: No return """ # Parse arguments parser = argparse.ArgumentParser(description="{0} ({1})".format( GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION)) #### # # Add custom cmdline argparse arguments here # #### custom_group = parser.add_argument_group('custom_args', 'Tag Options') custom_group.add_argument("--remove", help="Remove all Serial Tags.", default=False, action="store_true") #### # # End custom cmdline arguments # #### # Standard CloudGenix script switches. 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. https://api.elcapitan.cloudgenix.com", default=None) 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 cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument( "--password", "-PW", help="Use this Password instead of cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--insecure", "-I", help="Do not verify SSL certificate", action='store_true', default=False) login_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) debug_group = parser.add_argument_group( 'Debug', 'These options enable debugging output') debug_group.add_argument("--sdkdebug", "-D", help="Enable SDK Debug output, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) sdk_debuglevel = args["sdkdebug"] # Build SDK Constructor if args['controller'] and args['insecure']: sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False) elif args['controller']: sdk = cloudgenix.API(controller=args['controller']) elif args['insecure']: sdk = cloudgenix.API(ssl_verify=False) else: sdk = cloudgenix.API() # check for region ignore if args['ignore_region']: sdk.ignore_region = True # SDK debug, default = 0 # 0 = logger handlers removed, critical only # 1 = logger info messages # 2 = logger debug messages. if sdk_debuglevel == 1: # CG SDK info sdk.set_debug(1) elif sdk_debuglevel >= 2: # CG SDK debug sdk.set_debug(2) # 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["password"]: user_password = args["password"] 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["password"]: sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if sdk.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit(1) else: while sdk.tenant_id is None: sdk.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not sdk.tenant_id: user_email = None user_password = None #### # # Do your custom work here, or call custom functions. # #### remove = args['remove'] if not remove: print( "Checking all Elements for '#serial' hashtag on Controller with correct serial..." ) else: print("Removing all '#serial' hashtags on Controller ports.") elements_resp = sdk.get.elements() if elements_resp.cgx_status: elements_cache = elements_resp.cgx_content.get('items', []) else: print("ERROR: Unable to read 'elements': {0}".format( cloudgenix.jdout_detailed(elements_resp))) sys.exit() for element in elements_cache: element_id = element.get('id') element_displayname = element.get('name', element_id) print("Checking '{0}'... ".format(element_displayname), end="") element_id = element.get('id') site = element.get("site_id") serial_no = element.get("serial_number") if not serial_no: print("Error getting Serial Number.") continue if not site or site == "1": print("Not assigned to Site, skipping.") continue interfaces_resp = sdk.get.interfaces(site, element_id) if interfaces_resp.cgx_status: interfaces_cache = interfaces_resp.cgx_content.get('items', []) else: print("Unable to read 'interfaces'. Skipping.") continue selected_interface = {} for interface in interfaces_cache: if interface.get('name') in ['controller', 'controller 1']: selected_interface = interface continue if not selected_interface: print( "Could not find Controller/Controller 1 interface. Skipping.") continue selected_interface_id = selected_interface.get('id') selected_interface_name = selected_interface.get('name') serial_hashtag = "serial:{0}".format(serial_no) interface_hashtags = extract_tags(selected_interface) if remove: candidtate_interface_config = remove_tags(selected_interface) interface_edit_resp = sdk.put.interfaces( site, element_id, selected_interface_id, candidtate_interface_config) if interface_edit_resp.cgx_status: print("Cleaned Serial Hashtags from {0}.".format( selected_interface_name)) else: print("Failed Clean Serial Hashtags: {0}".format( cloudgenix.jdout_detailed(interface_edit_resp))) else: # add/check if serial_hashtag in interface_hashtags: print("Serial Hashtag Present.") continue # tag not present, add. candidtate_interface_config = put_tags([serial_hashtag], selected_interface) interface_edit_resp = sdk.put.interfaces( site, element_id, selected_interface_id, candidtate_interface_config) if interface_edit_resp.cgx_status: print("Added Serial Hashtag to {0}.".format( selected_interface_name)) else: print("Failed to add Serial Hashtag: {0}".format( cloudgenix.jdout_detailed(interface_edit_resp)))
def go(): """ Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site() :return: No return """ # Parse arguments parser = argparse.ArgumentParser(description="{0} ({1})".format( GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION)) #### # # Add custom cmdline argparse arguments here # #### custom_group = parser.add_argument_group('parser_args', 'Parsing / Output Arguments') custom_group.add_argument("--output", "-O", help="Output File (default is './tagname.txt'", default=None, type=str) custom_group.add_argument("--tag", "-T", help="Tag to search for.", required=True) #### # # End custom cmdline arguments # #### # Standard CloudGenix script switches. 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. https://api.elcapitan.cloudgenix.com", default=None) 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 cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument( "--password", "-PW", help="Use this Password instead of cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--insecure", "-I", help="Do not verify SSL certificate", action='store_true', default=False) login_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) debug_group = parser.add_argument_group( 'Debug', 'These options enable debugging output') debug_group.add_argument("--sdkdebug", "-D", help="Enable SDK Debug output, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) sdk_debuglevel = args["sdkdebug"] # Build SDK Constructor if args['controller'] and args['insecure']: sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False) elif args['controller']: sdk = cloudgenix.API(controller=args['controller']) elif args['insecure']: sdk = cloudgenix.API(ssl_verify=False) else: sdk = cloudgenix.API() # check for region ignore if args['ignore_region']: sdk.ignore_region = True # SDK debug, default = 0 # 0 = logger handlers removed, critical only # 1 = logger info messages # 2 = logger debug messages. if sdk_debuglevel == 1: # CG SDK info sdk.set_debug(1) elif sdk_debuglevel >= 2: # CG SDK debug sdk.set_debug(2) # 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["password"]: user_password = args["password"] 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["password"]: sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if sdk.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit(1) else: while sdk.tenant_id is None: sdk.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not sdk.tenant_id: user_email = None user_password = None #### # # Do your custom work here, or call custom functions. # #### # sites sites_resp = sdk.get.sites() sites_cache, _ = extract_items(sites_resp, 'sites') # elements elements_resp = sdk.get.elements() elements_cache, _ = extract_items(elements_resp, 'elements') # name to ID maps # sites name sites_id2n = build_lookup_dict(sites_cache, key_val='id', value_val='name') # element name elements_id2n = build_lookup_dict(elements_cache, key_val='id', value_val='name') ip_output = [] # enumerate all sites print("Searching {0} Sites, please wait...".format(len(sites_cache))) for site in sites_cache: site_id = site.get('id') # get the items with the tag. ip_output.extend( site_items_with_tag(sdk, site_id, args['tag'], sites_id2n)) # enumerate all elements print("Searching {0} Elements, please wait...".format(len(elements_cache))) for element in elements_cache: # check if bound to site, if not - skip. element_id = element.get('id') site_id = element.get('site_id') if not site_id: print("Element {0} not bound to a site. Skipping.".format( elements_id2n.get(element_id, element_id))) continue # get the items with the tag. ip_output.extend( element_items_with_tag(sdk, site_id, element_id, args['tag'], sites_id2n, elements_id2n)) if not ip_output: # no results, exit throw_error( "No Interfaces or Static routes with tag '{0}' found. Exiting without creating file." "".format(args['tag'])) sys.exit(1) else: if not args['output']: # no specified file, use tag.txt filename = "./{0}.txt".format(args['tag']) else: filename = args['output'] print("Writing {0} found entries to {1}".format(len(ip_output), filename)) with open(filename, 'w') as outputfile: outputfile.write("\n".join(ip_output))
vpn_group.add_argument("--load-wn-list-a", "-WA", help="JSON file containing Wan Network List A", default=False) vpn_group.add_argument("--load-wn-list-b", "-WB", help="JSON file containing Wan Network List B", default=False) args = vars(parser.parse_args()) ############################################################################ # Instantiate API ############################################################################ cgx_session = cloudgenix.API(controller=args["controller"], ssl_verify=args["verify"]) # set debug 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, SCRIPT_VERSION, cgx_session.controller)) # interactive or cmd-line specified initial login mytoken = None if mytoken: print("Found token. Using it to log in.") cgx_session.interactive.use_token(mytoken)
# just one argument, it hopefully is the config file. config_file = sys.argv[1] # Try open config file, get list of site names, element names try: with open(config_file, 'r') as datafile: loaded_config = yaml.safe_load(datafile) except IOError as e: ci_print("ERROR: Could not open file {0}: {1}".format(config_file, e), color="red") sys.exit(1) # let user know it worked. ci_print(" Loaded Config File {0}.".format(config_file)) # create a site name-> ID dict and element name->ID dict. sdk = cloudgenix.API() sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) region = sdk.controller_region sites_n2id = sdk.build_lookup_dict(sdk.extract_items(sdk.get.sites())) elements_n2id = sdk.build_lookup_dict(sdk.extract_items(sdk.get.elements())) sites_dict = {} config_sites, sites_api_version = config_lower_version_get(loaded_config, "sites", sdk.get.sites) for site, config_site_cnf in config_sites.items(): # get the list of element names elements_list = [] config_elements, elements_api_version = config_lower_version_get(config_site_cnf, "elements", sdk.get.elements) for element, config_element_cnf in config_elements.items(): elements_list.append(element) # update the sites dict with the site/element(s) sites_dict[site] = elements_list
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 go(): """ Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site() :return: No return """ # Parse arguments parser = argparse.ArgumentParser(description="{0} ({1})".format(GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION)) #### # # Add custom cmdline argparse arguments here # #### custom_group = parser.add_argument_group('custom_args', 'Do ACL Options') custom_group.add_argument("--input", help="ACL file to Apply to controller", required=True) custom_group.add_argument("--archive", help="File name to save previous ACL to", default=None) custom_group.add_argument("--no-client-login", help="Don't prompt for client login if ESP/MSP. " "Act on ACL on the ESP/MSP.", default=False, action='store_true') #### # # End custom cmdline arguments # #### # Standard CloudGenix script switches. 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. https://api.elcapitan.cloudgenix.com", default=None) 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 cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--password", "-PW", help="Use this Password instead of cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--insecure", "-I", help="Do not verify SSL certificate", action='store_true', default=False) login_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) debug_group = parser.add_argument_group('Debug', 'These options enable debugging output') debug_group.add_argument("--sdkdebug", "-D", help="Enable SDK Debug output, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) sdk_debuglevel = args["sdkdebug"] # Build SDK Constructor if args['controller'] and args['insecure']: sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False) elif args['controller']: sdk = cloudgenix.API(controller=args['controller']) elif args['insecure']: sdk = cloudgenix.API(ssl_verify=False) else: sdk = cloudgenix.API() # check for region ignore if args['ignore_region']: sdk.ignore_region = True # SDK debug, default = 0 # 0 = logger handlers removed, critical only # 1 = logger info messages # 2 = logger debug messages. if sdk_debuglevel == 1: # CG SDK info sdk.set_debug(1) elif sdk_debuglevel >= 2: # CG SDK debug sdk.set_debug(2) # 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["password"]: user_password = args["password"] elif CLOUDGENIX_PASSWORD: user_password = CLOUDGENIX_PASSWORD else: user_password = None # client login no_client_login = args['no_client_login'] # check for token if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["password"]: sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if sdk.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit(1) else: while sdk.tenant_id is None: sdk.interactive.login(user_email, user_password, client_login=False if no_client_login else True) # clear after one failed login, force relogin. if not sdk.tenant_id: user_email = None user_password = None #### # # Do your custom work here, or call custom functions. # #### output_filename = args['archive'] input_filename = args['input'] # open output to "fail fast" if file doesn't work. if output_filename is not None: with open(output_filename, "w") as new_config_json: pass # open input file. with open(input_filename, "r") as config_json: input_json = json.load(config_json) # is there a list object at the root of the input file? if not isinstance(input_json, list): # ok, if not list - is it in DICT format? if isinstance(input_json, dict): # check for optimized ACL optimized_ipv4_list = input_json.get("optimized_ipv4_list") if optimized_ipv4_list is None or not isinstance(optimized_ipv4_list, list): print("ERROR: ACL json is not in correct format (expected list, got '{0}'.)".format(type(input_json))) exit(1) else: # got optimized list, set. input_json = optimized_ipv4_list else: print("ERROR: ACL json is not in correct format (expected list, got '{0}'.)".format(type(input_json))) exit(1) sanitized_ipv4_list = [] for entry in input_json: if isinstance(entry, dict): ipv4 = entry.get('ipv4') if ipv4 and isinstance(ipv4, text_type): # got ipv4 candidate. add in correct ipv4 list format. sanitized_ipv4_list.append({ "ipv4": ipv4 }) else: print("WARNING: read ipv4 invalid format: type: {0} value: '{1}'. Skipping.." "".format(type(ipv4), ipv4)) else: print("WARNING: read list entry invalid format: type: {0} value: '{1}'. Skipping.." "".format(type(entry), entry)) # do the ACL change. old_ipv4_list = do_acl(sdk, sanitized_ipv4_list) if output_filename is not None: with open(output_filename, "w") as old_config_json: json.dump(old_ipv4_list, old_config_json, indent=4) return
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. https://api.elcapitan.cloudgenix.com", default=None) controller_group.add_argument( "--insecure", "-I", help="Disable SSL certificate and hostname verification", dest='verify', action='store_false', default=True) controller_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) 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) output_group = parser.add_argument_group( 'Output', 'These options change how the output is generated.') output_group.add_argument( "--output", help="Output file name (default is auto-generated from name/date/time)", type=str, default=None) args = vars(parser.parse_args()) ############################################################################ # Instantiate API ############################################################################ sdk = cloudgenix.API(controller=args["controller"], ssl_verify=args["verify"]) # set debug sdk.set_debug(args["debug"]) # set ignore region sdk.ignore_region = args["ignore_region"] ############################################################################ # Draw Interactive login banner, run interactive login including args above. ############################################################################ print("{0} v{1} ({2})\n".format(SCRIPT_NAME, SCRIPT_VERSION, sdk.controller)) # interactive or cmd-line specified initial login while sdk.tenant_name is None: sdk.interactive.login(args["email"], args["pass"]) ############################################################################ # End Login handling, begin script.. ############################################################################ generate(sdk, specify_filename=args["output"])
def setup_cloudgenix_connection(module=None, auth_token=None, controller=None, tenant_id=None, ssl_verify=None, ignore_region=None, display=None): if module is not None: # Check module args, if not present fall back to args or env vars. auth_token_mod = module.params.get('auth_token') controller_mod = module.params.get('controller') tenant_id_mod = module.params.get('tenant_id') ssl_verify_mod = module.params.get('ssl_verify') ignore_region_mod = module.params.get('ignore_region') if auth_token_mod: auth_token = auth_token_mod if controller_mod: controller = controller_mod if tenant_id_mod: tenant_id = tenant_id_mod if ssl_verify_mod: ssl_verify = ssl_verify_mod if ignore_region_mod: ignore_region = ignore_region_mod if not auth_token: if 'X_AUTH_TOKEN' in os.environ: auth_token = os.environ['X_AUTH_TOKEN'] if not controller: # can recreate controller if REGION if 'REGION' in os.environ: if 'ENV' in os.environ: controller = "https://api-" + string_types(os.environ.get('ENV')) + "." + \ string_types(os.environ.get('REGION')) + ".cloudgenix.com" else: controller = "https://api." + string_types( os.environ.get('REGION')) + ".cloudgenix.com" else: # use default API endpoint if all else fails. controller = "https://api.elcapitan.cloudgenix.com" # instantiate the SDK object cgx_session = cloudgenix.API(controller=controller, ssl_verify=ssl_verify) cgx_session.ignore_region = ignore_region cgx_session.add_headers({'X-Auth-Token': auth_token}) if not tenant_id: if 'TENANT_ID' in os.environ: tenant_id = os.environ['TENANT_ID'] else: # we need to get this from the API. If we have the auth_token, we're good. if auth_token: profile_response = cgx_session.get.profile() if profile_response.cgx_status: tenant_id = profile_response.cgx_content.get( 'tenant_id', tenant_id) else: # if we can log, please do. if display: display.vvvv( 'cloudgenix_util\n' '\tAUTH_TOKEN / GET Profile failed: {0}'.format( profile_response.cgx_content)) tenant_id = None cgx_session.tenant_id = tenant_id return auth_token, controller, tenant_id, cgx_session
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 app_group = parser.add_argument_group('Custom Application specific information', 'Information shared here will be used to create custom applications') app_group.add_argument("--configfile", "-f", help="YAML file containing application details", 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 filename = args["configfile"] if filename is None: print("ERR: Please provide the path to the YAML config file") cleanexit(cgx_session) ############################################################################ # Read YAML Contents # Build Translation Dicts # Create Custom Apps ############################################################################ if os.path.exists(filename): with open(filename) as yamlfile: yamldata = yaml.load(yamlfile, Loader=yaml.FullLoader) createdicts(cgx_session) createcustomapps(yamldata, cgx_session) else: print("ERR: Invalid config file. File {} not found".format(filename)) cleanexit(cgx_session) ############################################################################ # Logout to clear session. ############################################################################ print("INFO: Logging Out") cleanexit(cgx_session)
def __init__(self): """ init - use the cgx object that was created by the calling main """ self.cgx = cloudgenix.API() self.out = ""
def servicelinks(sdk=None, idname_obj=None, controller="https://api.elcapitan.cloudgenix.com", ssl_verify=True, output_csv=False): if sdk is None: # need to instantiate sdk = cloudgenix.API(controller=controller, ssl_verify=ssl_verify) if not sdk.tenant_id: # need to login. if AUTH_TOKEN is None: sdk.interactive.login() else: sdk.interactive.use_token(AUTH_TOKEN) # gen id_name maps if idname_obj is None: id2n_obj = cloudgenix_idname.CloudGenixIDName(sdk) else: id2n_obj = idname_obj id2n_obj.update_sites_cache() id2n = id2n_obj.generate_sites_map() id2n_obj.update_elements_cache() id2n.update(id2n_obj.generate_elements_map()) element_id2site = id2n_obj.generate_elements_map(key_val='id', value_val='site_id') element_id2connected = id2n_obj.generate_elements_map( key_val='id', value_val='connected') # cloudgenix.jd(element_id2connected) id2n_obj.update_interfaces_cache() id2n.update(id2n_obj.generate_interfaces_map()) prisma_servicelinks = [] for interface in id2n_obj.interfaces_cache: tags = interface.get('tags', []) if isinstance(tags, list) and 'AUTO-PRISMA_MANAGED' in tags: prisma_servicelinks.append(interface) servicelink_status_list = [] for sl in prisma_servicelinks: description = sl.get('description', '') prisma_rno_list = remotenet_re.findall( description if description is not None else "") if len(prisma_rno_list) >= 1: prisma_rno = ";".join(prisma_rno_list) else: prisma_rno = "Unknown" element_id = sl.get('element_id') site_id = element_id2site.get(element_id, "Could not get site") element_connected = element_id2connected.get(element_id, False) interface_id = sl.get('id') parent_if_id = sl.get('parent') admin_state = sl.get('admin_up') resp = sdk.get.interfaces_status(site_id, element_id, interface_id) if not element_connected: # if element is not connected, status is stale. operational_state = "Unknown_Offline" extended_state = "Unknown_Offline" elif resp.cgx_status: operational_state = resp.cgx_content.get("operational_state") extended_state = resp.cgx_content.get("extended_state") else: operational_state = "Unknown" extended_state = "Unknown" site_name = id2n.get(site_id, site_id) element_name = id2n.get(element_id, element_id) interface_name = id2n.get(interface_id, interface_id) parent_if_name = id2n.get(parent_if_id, parent_if_id) servicelink_status_list.append({ "Site": site_name, "Element": element_name, "Interface": interface_name, "Element Online": "Online" if element_connected else "Offline", "Admin State": str(admin_state), "Operational State": operational_state, "Extended State": extended_state, "Prisma Remote On-boarding": prisma_rno, "Parent Interface": parent_if_name }) return servicelink_status_list
def go(): """ Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site() :return: No return """ # Parse arguments parser = argparse.ArgumentParser(description="{0} ({1})".format(GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION)) #### # # Add custom cmdline argparse arguments here # #### custom_group = parser.add_argument_group('custom_args', 'Pull ACL Options') custom_group.add_argument("--output", help="File name to save output to", required=True) custom_group.add_argument("--no-client-login", help="Don't prompt for client login if ESP/MSP. " "Act on ACL on the ESP/MSP.", default=False, action='store_true') #### # # End custom cmdline arguments # #### # Standard CloudGenix script switches. 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. https://api.elcapitan.cloudgenix.com", default=None) 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 cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--password", "-PW", help="Use this Password instead of cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--insecure", "-I", help="Do not verify SSL certificate", action='store_true', default=False) login_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) debug_group = parser.add_argument_group('Debug', 'These options enable debugging output') debug_group.add_argument("--sdkdebug", "-D", help="Enable SDK Debug output, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) sdk_debuglevel = args["sdkdebug"] # Build SDK Constructor if args['controller'] and args['insecure']: sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False) elif args['controller']: sdk = cloudgenix.API(controller=args['controller']) elif args['insecure']: sdk = cloudgenix.API(ssl_verify=False) else: sdk = cloudgenix.API() # check for region ignore if args['ignore_region']: sdk.ignore_region = True # SDK debug, default = 0 # 0 = logger handlers removed, critical only # 1 = logger info messages # 2 = logger debug messages. if sdk_debuglevel == 1: # CG SDK info sdk.set_debug(1) elif sdk_debuglevel >= 2: # CG SDK debug sdk.set_debug(2) # 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["password"]: user_password = args["password"] elif CLOUDGENIX_PASSWORD: user_password = CLOUDGENIX_PASSWORD else: user_password = None # client login no_client_login = args['no_client_login'] # check for token if CLOUDGENIX_AUTH_TOKEN and not args["email"] and not args["password"]: sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if sdk.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit(1) else: while sdk.tenant_id is None: sdk.interactive.login(user_email, user_password, client_login=False if no_client_login else True) # clear after one failed login, force relogin. if not sdk.tenant_id: user_email = None user_password = None #### # # Do your custom work here, or call custom functions. # #### output_filename = args['output'] ipv4_list = pull_acl(sdk, False) config_json = open(output_filename, "w") try: json.dump(ipv4_list, config_json, indent=4) finally: config_json.close()
logging.basicConfig( level=logging.DEBUG, format="%(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s") logger.setLevel(logging.DEBUG) else: # Remove all handlers for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) # set logging level to default logger.setLevel(logging.WARNING) ############################################################################ # Instantiate API ############################################################################ sdk = cloudgenix.API(controller=args["controller"], ssl_verify=args["verify"]) # set debug sdk.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, sdk.controller)) # interactive or cmd-line specified initial login while sdk.tenant_name is None: sdk.interactive.login(args["email"], args["pass"])
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()
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 config_group = parser.add_argument_group( 'SSH Config Specific information', 'IP prefix and interface information to enable SSH') config_group.add_argument("--site", "-SN", help="Name of the Element", default=None) config_group.add_argument("--element", "-EN", help="Name of the Element", default=None) config_group.add_argument("--interface", "-IN", help="Interface where you want to enable SSH", default=None) config_group.add_argument( "--application", "-AP", help= "Application you want to add controls to. Accepted values: BGP, DHCP, PING, SNMP, SSH, TRACEROUTE, SpokeHASync", default=None) config_group.add_argument("--ipprefix", "-IP", help="IP Prefix", default=None) config_group.add_argument( "--action", "-AC", help="Action for config. Accepted values: allow or deny", default=None) config_group.add_argument( "--filename", "-f", help= "CSV file containing configuration information. CSV header should match: site,element,interface,ipprefix,app,action", default=None) args = vars(parser.parse_args()) ############################################################################ # Parse CLI parameters ############################################################################ CONFIGTYPE = None filename = args['filename'] if filename: if not os.path.isfile(filename): print( "ERR: File {} does not exist. Please enter the accurate file". format(filename)) sys.exit() else: CONFIGTYPE = "FILE" else: app = args['application'] if app not in [ "BGP", "DHCP", "PING", "SNMP", "SSH", "TRACEROUTE", "SpokeHASync" ]: print( "ERR: Invalid application: {}. Please choose one: BGP, DHCP, PING, SNMP, SSH, TRACEROUTE or SpokeHASync" .format(app)) sys.exit() action = args['action'] if action not in ["ALLOW", "DENY"]: print( "ERR: Invalid action: {}. Please choose: ALLOW or DENY".format( action)) sys.exit() site = args['site'] element = args['element'] interface = args['interface'] prefix = args['ipprefix'] CONFIGTYPE = "CLI" ############################################################################ # 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 ############################################################################ # Build Translation Dictionaries ############################################################################ buildtranslationdicts(cgx_session) ############################################################################ # Configure SSH Extension ############################################################################ if CONFIGTYPE == "CLI": configextention(cgx_session=cgx_session, site=site, element=element, interface=interface, prefix=prefix, app=app, action=action) else: configdata = pd.read_csv(filename) columns = list(configdata.columns) if set(columns) == set(CSV_HEADER): for i, row in configdata.iterrows(): print("INFO: Configuring row {} from CSV".format(i + 1)) configextention(cgx_session=cgx_session, site=row['site'], element=row['element'], interface=str(row['interface']), prefix=row['prefix'], app=row['app'], action=row['action']) else: print( "ERR: CSV header not in expected format. Please make sure the headers are {}" .format(CSV_HEADER)) cleanexit(cgx_session) ############################################################################ # Logout to clear session. ############################################################################ cleanexit(cgx_session)
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 Event Filters site_group = parser.add_argument_group('Filters for events', 'The following attributes will be used to query events') site_group.add_argument("--eventcodes", "-EC", help="List event codes you want to query for", default=None) site_group.add_argument("--sitename", "-S", help="Name of the Site you want events filtered for. For multiple sites, separate names by using a comma.", default=None) site_group.add_argument("--hour", "-H", help="Number of hours from now you need the events queried for. Or use the keyword RANGE to provide a time range", default=None) site_group.add_argument("--starttime", "-ST", help="Start time in format YYYY-MM-DDTHH:MM:SSZ", default=None) site_group.add_argument("--endtime", "-ET", help="End time in format YYYY-MM-DDTHH:MM:SSZ", default=None) args = vars(parser.parse_args()) ############################################################################ # Check if YAML config files was provided via CLI ############################################################################ eventcodes = args['eventcodes'] numhours = args['hour'] sitename = args['sitename'] starttime = args['starttime'] endtime = args['endtime'] stime = None etime = None if eventcodes is None: print("WARN: No event codes listed. All events will be returned.") if numhours is None: print("ERR: Invalid number of hours.") sys.exit() if numhours == RANGE: if starttime is None or endtime is None: print("ERR: For time range, please provide both starttime and endtime in format YYYY-MM-DDTHH:MM:SSZ") sys.exit() else: if "." in starttime: stime = datetime.datetime.strptime(starttime, "%Y-%m-%dT%H:%M:%S.%fZ") else: stime = datetime.datetime.strptime(starttime, "%Y-%m-%dT%H:%M:%SZ") if "." in endtime: etime = datetime.datetime.strptime(endtime, "%Y-%m-%dT%H:%M:%S.%fZ") else: etime = datetime.datetime.strptime(endtime, "%Y-%m-%dT%H:%M:%SZ") else: numhours = int(numhours) if numhours <= 0: print("ERR: Invalid number of hours.") sys.exit() if sitename is None: print("INFO: No site filter configured. All events will be returned") ############################################################################ # 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 ############################################################################ # Build Site translation dict ############################################################################ createdicts(cgx_session) sitelist = [] if sitename is not None: sitename = sitename.replace(", ",",") sites = sitename.split(",") for site in sites: if site in site_name_id_dict.keys(): sitelist.append(site_name_id_dict[site]) continue else: print("ERR: Site {} does not exist on the tenant. Please re-enter site name(s)".format(site)) sys.exit() ############################################################################ # Get Events ############################################################################ event_codes = [] if eventcodes: eventcodes = eventcodes.replace(" ","") event_codes = eventcodes.split(",") events = get_events(cgx_session, numhours, stime, etime, event_codes, sitelist) ############################################################################ # Write to CSV ############################################################################ # get time now. curtime_str = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S') # create file-system friendly tenant str. tenant_str = "".join(x for x in cgx_session.tenant_name if x.isalnum()).lower() # Set filenames csvfile = os.path.join('./', '%s_events_%s.csv' %(tenant_str, curtime_str)) with open(csvfile, 'w') as csv_file: csv_file.write('Element,Serial Number,Site\n') csv_file.flush() csvdata = pd.DataFrame(columns=["time","time_ms","time_sms","code","id","severity","type","correlation_id","site","element","entity_ref","entity_ref text","info","info text","cleared","acknowledged","acknowledgement_info"]) print("INFO: Creating pandas dict") firstbar = len(events) + 1 barcount = 1 # could be a long query - start a progress bar. pbar = ProgressBar(widgets=[Percentage(), Bar(), ETA()], max_value=firstbar).start() for event in events: cleared = "n/a" correlation_id = "n/a" acknowledged = "n/a" acknowledgement_info = "n/a" site = "Unassigned" if "." in event['time']: date = datetime.datetime.strptime(event['time'], "%Y-%m-%dT%H:%M:%S.%fZ") else: date = datetime.datetime.strptime(event['time'], "%Y-%m-%dT%H:%M:%SZ") time_ms = date.replace(microsecond=0) time_ms = time_ms.isoformat() + "Z" time_sms = date.replace(second=0, microsecond=0) time_sms = time_sms.isoformat() + "Z" entity_ref = get_entity(cgx_session, event) info = get_info(cgx_session, event) if event['element_id'] in elem_id_name_dict.keys(): elemname = elem_id_name_dict[event['element_id']] else: elemname = event['element_id'] if event['element_id'] in eid_sid_dict.keys(): sid = eid_sid_dict[event['element_id']] site = site_id_name_dict[sid] else: print("INFO: Element not attached to site. {}".format(event)) site = "Unassigned" if event['type'] == "alarm": cleared = event['cleared'] correlation_id = event['correlation_id'] acknowledged = event['acknowledged'] acknowledgement_info = event['acknowledgement_info'] csvdata = csvdata.append({"time":event['time'], "time_ms":time_ms, "time_sms":time_sms, "code":event['code'], "id":event['id'], "severity":event['severity'], "type":event['type'], "correlation_id":correlation_id, "site":site, "element":elemname, "entity_ref":event['entity_ref'], "entity_ref text":entity_ref, "info":event['info'], "info text":info, "cleared":cleared, "acknowledged":acknowledged, "acknowledgement_info":acknowledgement_info},ignore_index=True) barcount += 1 pbar.update(barcount) # finish after iteration. pbar.finish() print("INFO: Writing events to file {}".format(csvfile)) csvdata.to_csv(csvfile, index=False) ############################################################################ # Logout and exit script ############################################################################ print("INFO: Logging out.") cgx_session.get.logout() return
#!/usr/bin/env python import json import cloudgenix # Import ID -> Name for CloudGenix import cloudgenix_idname # Create CloudGenix API constructor cgx_sess = cloudgenix.API() # Call CloudGenix API login cgx_sess.interactive.login() # Generate ID -> Name Dict idname_dict = cloudgenix_idname.generate_id_name_map(cgx_sess) # Dump whole ID -> Name dict to console. print(json.dumps(idname_dict, indent=4)) # Cleanup and logout cgx_sess.interactive.logout()
def go(): """ Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site() :return: No return """ # Parse arguments parser = argparse.ArgumentParser(description="{0} ({1})".format(GLOBAL_MY_SCRIPT_NAME, GLOBAL_MY_SCRIPT_VERSION)) #### # # Add custom cmdline argparse arguments here # #### custom_group = parser.add_argument_group('custom_args', 'Per Prefix ARP') custom_group.add_argument("--enable", help="enable Per Prefix ARP", default=False, action="store_true") custom_group.add_argument("--disable", help="disable Sub Optimal Re-eval", default=True, action="store_false") custom_group.add_argument("--all", help="apply to all IONs", default=None, action="store_true") custom_group.add_argument("--list", help="list Sub Optimal Config on all IONs", default=None, action="store_true") custom_group.add_argument("--site_file", help="site list file. Each site name on a different line", default=None, type=argparse.FileType('r')) #### # # End custom cmdline arguments # #### # Standard CloudGenix script switches. 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. https://api.elcapitan.cloudgenix.com", default=None) 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 cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--password", "-PW", help="Use this Password instead of cloudgenix_settings.py " "or prompting", default=None) login_group.add_argument("--insecure", "-I", help="Do not verify SSL certificate", action='store_true', default=False) login_group.add_argument("--noregion", "-NR", help="Ignore Region-based redirection.", dest='ignore_region', action='store_true', default=False) debug_group = parser.add_argument_group('Debug', 'These options enable debugging output') debug_group.add_argument("--sdkdebug", "-D", help="Enable SDK Debug output, levels 0-2", type=int, default=0) args = vars(parser.parse_args()) sdk_debuglevel = args["sdkdebug"] # Build SDK Constructor if args['controller'] and args['insecure']: sdk = cloudgenix.API(controller=args['controller'], ssl_verify=False) elif args['controller']: sdk = cloudgenix.API(controller=args['controller']) elif args['insecure']: sdk = cloudgenix.API(ssl_verify=False) else: sdk = cloudgenix.API() # check for region ignore if args['ignore_region']: sdk.ignore_region = True # SDK debug, default = 0 # 0 = logger handlers removed, critical only # 1 = logger info messages # 2 = logger debug messages. if sdk_debuglevel == 1: # CG SDK info sdk.set_debug(1) elif sdk_debuglevel >= 2: # CG SDK debug sdk.set_debug(2) # 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["password"]: user_password = args["password"] 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["password"]: sdk.interactive.use_token(CLOUDGENIX_AUTH_TOKEN) if sdk.tenant_id is None: print("AUTH_TOKEN login failure, please check token.") sys.exit(1) else: while sdk.tenant_id is None: sdk.interactive.login(user_email, user_password) # clear after one failed login, force relogin. if not sdk.tenant_id: user_email = None user_password = None #### # # Do your custom work here, or call custom functions. # #### return sdk,args
def run_module(): # define the available arguments/parameters that a user can pass to # the module module_args = dict( email=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), controller=dict(type='str', required=False), ssl_verify=dict(type='bool', required=False, default=True), ignore_region=dict(type='bool', required=False, default=False), ) # seed the result dict in the object # we primarily care about changed and state # change is if this module effectively modified the target # state will include any data that you want your module to pass back # for consumption, for example, in a subsequent task result = dict(changed=False, auth_token='', tenant_id='', controller='', region='', meta='') # the AnsibleModule object will be our abstraction working with Ansible # this includes instantiation, a couple of common attr would be the # args/params passed to the execution, as well as if the module # supports check mode module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) # check for Cloudgenix SDK (Required) if not HAS_CLOUDGENIX: module.fail_json( msg= 'The "cloudgenix" python module is required by this Ansible module.' ) # if the user is working with this module in only check mode we do not # want to make any changes to the environment, just return the current # state with no modifications if module.check_mode: return result # setup CloudGenix API session cgx_session = cloudgenix.API(controller=module.params['controller'], ssl_verify=module.params['ssl_verify']) cgx_session.ignore_region = module.params['ignore_region'] # issue login request login_response = cgx_session.post.login({ "email": module.params['email'], "password": module.params['password'] }) # check for login failure if not login_response.cgx_status: # if login fails, fail module result['meta'] = login_response.cgx_content module.fail_json(msg='login failure', **result) auth_token = login_response.cgx_content.get('x_auth_token') # Check for no AUTH_TOKEN, this means a SAML or MSP/ESP user, which is not supported in this version. if not auth_token: result['meta'] = login_response.cgx_content module.fail_json( msg='The "email" specified was a SAML2.0 user or ESP/MSP user. ' 'These are not yet supported via the CloudGenix Ansible module', **result) # login success, mark changed True, as session is established even if somethin below fails. result['changed'] = True # token in the original login (not saml) means region parsing has not been done. # do now, and recheck if cookie needs set. auth_region = cgx_session.parse_region(login_response) cgx_session.update_region_to_controller(auth_region) cgx_session.reparse_login_cookie_after_region_update(login_response) # everything but tenant_id, update result result['auth_token'] = auth_token result['region'] = cgx_session.controller_region result['controller'] = cgx_session.controller # get tenant id profile_response = cgx_session.get.profile() if not profile_response.cgx_status: # profile get failure, fail module result['meta'] = profile_response.cgx_content module.fail_json(msg='GET profile failure', **result) cgx_session.tenant_id = profile_response.cgx_content.get('tenant_id') cgx_session.email = profile_response.cgx_content.get('email') if not cgx_session.tenant_id: # tenant ID not in profile, fail. result['meta'] = profile_response.cgx_content module.fail_json(msg='GET profile had no tenant_id value.', **result) result['tenant_id'] = cgx_session.tenant_id # in the event of a successful module execution, you will want to # simple AnsibleModule.exit_json(), passing the key/value results module.exit_json(**result) # avoid Pylint R1710 return result
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=None) 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 policy_group = parser.add_argument_group( 'Policy Set & Rule Specific Information', 'Name policy set, rule and policy type that needs to be cloned') policy_group.add_argument( "--type", "-T", help="Type of Policy Set. Allowed values: NW or QOS", default=None) policy_group.add_argument("--srcpolicy", "-SP", help="Source Policy Set Name", default=None) policy_group.add_argument( "--srcrule", "-SR", help="Source Policy Rule. This is the rule that will be cloned", default=None) policy_group.add_argument("--dstpolicy", "-DP", help="Destination Policy Set Name", default=None) policy_group.add_argument( "--dstrule", "-DR", help= "Destination Policy Rule. This new rule will be created in the destination policy set", 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 ############################################################################ # Parse Arguments ############################################################################ TYPE = args['type'] if TYPE not in ["NW", "QOS"]: print("ERR: Invalid policy type: {}. Please choose NW or QOS".format( TYPE)) cleanexit(cgx_session) SRC_POLICY_SET = args['srcpolicy'] SRC_POLICY_RULE = args['srcrule'] DST_POLICY_SET = args['dstpolicy'] DST_POLICY_RULE = args['dstrule'] if (SRC_POLICY_RULE == None) or (SRC_POLICY_SET == None) or ( DST_POLICY_RULE == None) or (DST_POLICY_SET == None): print( "ERR: Please provide both source and destination policy set and rule name" ) cleanexit(cgx_session) ############################################################################ # Build Translation Dicts ############################################################################ createrulemaps(cgx_session) ############################################################################ # Create Rule ############################################################################ createnewrule(cgx_session, TYPE, SRC_POLICY_SET, SRC_POLICY_RULE, DST_POLICY_SET, DST_POLICY_RULE) ############################################################################ # 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. https://cloudgenix.com:8443", 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()) if args['debug'] == 1: logging.basicConfig(level=logging.INFO, format="%(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s") logger.setLevel(logging.INFO) elif args['debug'] >= 2: logging.basicConfig(level=logging.DEBUG, format="%(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s") logger.setLevel(logging.DEBUG) else: # Remove all handlers for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) # set logging level to default logger.setLevel(logging.WARNING) ############################################################################ # Instantiate API ############################################################################ cgx_session = cloudgenix.API(controller=args["controller"], ssl_verify=args["verify"]) # set debug 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)) # interactive or cmd-line specified initial login while cgx_session.tenant_name is None: cgx_session.interactive.login(args["email"], args["pass"]) ############################################################################ # End Login handling, begin script.. ############################################################################ # get time now. curtime_str = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S') # create file-system friendly tenant str. tenant_str = "".join(x for x in cgx_session.tenant_name if x.isalnum()).lower() # Set filenames site_csv = os.path.join('./', '%s_site_info_%s.csv' % (tenant_str, curtime_str)) print("Creating %s for data output..." % (str(site_csv))) with open(site_csv, 'w') as csv_file: csv_file.write(CSVHEADER) csv_file.flush() # Create Translation Dicts createdicts(cgx_session) get_site_info(cgx_session, site_csv) # end of script, run logout to clear session. cgx_session.get.logout() print("Logging Out.")