### Complete Script Example Source: https://context7.com/cloudgenix/sdk-python/llms.txt A full example demonstrating SDK usage patterns, including authentication, retrieving site and element information, and logging out. ```APIDOC ## Complete Script Example A full example demonstrating SDK usage patterns. ```python #!/usr/bin/env python """Complete CloudGenix SDK usage example.""" import cloudgenix from cloudgenix import jd import os import sys def main(): # Initialize SDK sdk = cloudgenix.API() sdk.set_debug(0) # Set to 1 or 2 for debugging # Authenticate - try AUTH_TOKEN first, then interactive auth_token = os.environ.get("CLOUDGENIX_AUTH_TOKEN") if auth_token: if not sdk.interactive.use_token(auth_token): print("Token authentication failed") sys.exit(1) else: if not sdk.interactive.login(): print("Interactive login failed") sys.exit(1) print(f"Logged in as {sdk.email} to tenant {sdk.tenant_name}") # Get all sites sites_resp = sdk.get.sites() if not sites_resp.cgx_status: print(f"Failed to get sites: {sites_resp.cgx_errors}") sdk.interactive.logout() sys.exit(1) sites = sdk.extract_items(sites_resp, error_label="sites") site_lookup = sdk.build_lookup_dict(sites, key_val='name', value_val='id') print(f"\nFound {len(sites)} sites:") for site in sites: print(f" - {site.get('name')} ({site.get('element_cluster_role')})") # Get WAN interfaces for each site site_id = site.get('id') wan_resp = sdk.get.waninterfaces(site_id=site_id) if wan_resp.cgx_status: wans = wan_resp.cgx_content.get('items', []) for wan in wans: print(f" WAN: {wan.get('name')} - {wan.get('link_bw_down')}kbps down") # Get all elements elements_resp = sdk.get.elements() if elements_resp.cgx_status: elements = sdk.extract_items(elements_resp, error_label="elements") print(f"\nFound {len(elements)} elements:") for elem in elements: print(f" - {elem.get('name')} ({elem.get('model_name')}) - State: {elem.get('state')}") # Logout sdk.interactive.logout() print("\nLogout successful") if __name__ == "__main__": main() ``` ``` -------------------------------- ### Python SDK Authentication Example Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/patch_api.m.html Demonstrates how to authenticate with the CloudGenix platform using the Python SDK. This is a prerequisite for most other operations. ```python from cloudgenix import CloudGenix # Replace with your CloudGenix site, username, and password cgx = CloudGenix(site='your_site', username='your_username', password='your_password') # Login to the CloudGenix platform login_response = cgx.login() if login_response: print("Successfully logged in to CloudGenix.") else: print("Failed to log in to CloudGenix.") ``` -------------------------------- ### Complete CloudGenix SDK Script Example Source: https://context7.com/cloudgenix/sdk-python/llms.txt This script demonstrates a comprehensive usage pattern of the CloudGenix SDK. It covers initialization, authentication (token-based and interactive), retrieving site and element information, and logging out. The script includes error handling for API calls and utility functions for data extraction and lookup. ```python #!/usr/bin/env python """Complete CloudGenix SDK usage example.""" import cloudgenix from cloudgenix import jd import os import sys def main(): # Initialize SDK sdk = cloudgenix.API() sdk.set_debug(0) # Set to 1 or 2 for debugging # Authenticate - try AUTH_TOKEN first, then interactive auth_token = os.environ.get("CLOUDGENIX_AUTH_TOKEN") if auth_token: if not sdk.interactive.use_token(auth_token): print("Token authentication failed") sys.exit(1) else: if not sdk.interactive.login(): print("Interactive login failed") sys.exit(1) print(f"Logged in as {sdk.email} to tenant {sdk.tenant_name}") # Get all sites sites_resp = sdk.get.sites() if not sites_resp.cgx_status: print(f"Failed to get sites: {sites_resp.cgx_errors}") sdk.interactive.logout() sys.exit(1) sites = sdk.extract_items(sites_resp, error_label="sites") site_lookup = sdk.build_lookup_dict(sites, key_val='name', value_val='id') print(f"\nFound {len(sites)} sites:") for site in sites: print(f" - {site.get('name')} ({site.get('element_cluster_role')})") # Get WAN interfaces for each site site_id = site.get('id') wan_resp = sdk.get.waninterfaces(site_id=site_id) if wan_resp.cgx_status: wans = wan_resp.cgx_content.get('items', []) for wan in wans: print(f" WAN: {wan.get('name')} - {wan.get('link_bw_down')}kbps down") # Get all elements elements_resp = sdk.get.elements() if elements_resp.cgx_status: elements = sdk.extract_items(elements_resp, error_label="elements") print(f"\nFound {len(elements)} elements:") for elem in elements: print(f" - {elem.get('name')} ({elem.get('model_name')}) - State: {elem.get('state')}") # Logout sdk.interactive.logout() print("\nLogout successful") if __name__ == "__main__": main() ``` -------------------------------- ### Create CloudGenix Site Source: https://context7.com/cloudgenix/sdk-python/llms.txt Provides an example of creating a new site in the CloudGenix platform using the SDK's POST method. It defines the necessary site data, including name, description, address, location, and policy information, and handles the response to confirm creation or report errors. ```python import cloudgenix sdk = cloudgenix.API() sdk.interactive.login() # Create a new branch site site_data = { "name": "Branch Office NYC", "description": "New York City branch location", "address": { "street": "123 Main Street", "city": "New York", "state": "NY", "post_code": "10001", "country": "United States" }, "location": { "latitude": 40.7128, "longitude": -74.0060 }, "element_cluster_role": "SPOKE", "admin_state": "active", "policy_set_id": None, "security_policyset_id": None, "network_policysetstack_id": None, "tags": ["production", "east-coast"] } response = sdk.post.sites(data=site_data) if response.cgx_status: new_site = response.cgx_content print(f"Created site: {new_site.get('name')} with ID: {new_site.get('id')}") else: print(f"Failed to create site: {response.cgx_errors}") ``` -------------------------------- ### Python: CloudGenix API Login and Get Sites Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html This snippet shows how to import the CloudGenix SDK, instantiate the API, log in interactively (handling SAML2.0 and MSP), and then retrieve and print a list of sites for the selected account. It requires the 'cloudgenix' SDK, 'requests', and potentially 'websockets' and 'urllib3' depending on the Python version. ```python from cloudgenix import API, jd sdk = API() sdk.interactive.login() jd(sdk.get.sites()) ``` -------------------------------- ### Get Policy Sets and Rules (Python) Source: https://context7.com/cloudgenix/sdk-python/llms.txt Fetches network policy sets and their associated rules. It allows retrieving all policy sets and then drilling down to get the rules for a specific policy set identified by its ID. Output includes policy set names, IDs, rule names, priorities, and allowed paths. ```python import cloudgenix sdk = cloudgenix.API() sdk.interactive.login() # Get all policy sets response = sdk.get.policysets() if response.cgx_status: policysets = response.cgx_content.get('items', []) for ps in policysets: print(f"Policy Set: {ps.get('name')} - ID: {ps.get('id')}") # Get policy rules for a specific policy set policyset_id = "15136303050290400" response = sdk.get.policyrules(policyset_id=policyset_id) if response.cgx_status: rules = response.cgx_content.get('items', []) for rule in rules: print(f"Rule: {rule.get('name')} - Priority: {rule.get('priority')}") print(f" App Def IDs: {rule.get('app_def_ids')}") print(f" Paths Allowed: {rule.get('paths_allowed')}") ``` -------------------------------- ### GET /tenant/configuration Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/patch_api.m.html Retrieves the configuration details for a tenant, including password policies and provider-specific data. ```APIDOC ## GET /tenant/configuration ### Description Retrieves the current tenant configuration, including security policies and provider metadata. ### Method GET ### Endpoint /tenant/configuration ### Parameters #### Query Parameters - **tenant_id** (string) - Required - The unique identifier for the tenant. ### Response #### Success Response (200) - **password_policy** (object) - Contains security settings like failed_login_attempts and password_aging_days. - **provider_data** (object) - Contains certificate information and provider-specific metadata. #### Response Example { "password_policy": { "enable_failed_login_attempts": true, "failed_login_attempts": 5 }, "provider_data": { "certificate": { "serial_number": "123456789" } } } ``` -------------------------------- ### Initialize CloudGenix API and Link Methods (Python) Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Initializes the CloudGenix API client, constructs a user agent string including the 'websockets' library version, and binds various API method classes (GET, POST, PUT, PATCH, DELETE, Interactive, WebSockets) to the client object. ```Python websocketlib_version = websockets.version.version if not websocketlib_name: websocketlib_name = 'websockets' if not websocketlib_version: websocketlib_version = 'UNKNOWN' ws_user_agent = 'python-{0}/{1} (CGX SDK v{2})'.format(websocketlib_name, websocketlib_version, self.version) self._websocket_headers = { 'Accept': 'application/json', 'User-Agent': text_type(ws_user_agent) } # Bind API method classes to this object subclasses = self._subclass_container() self.get = subclasses["get"]() """API object link to `cloudgenix.get_api.Get`""" self.post = subclasses["post"]() """API object link to `cloudgenix.post_api.Post`""" self.put = subclasses["put"]() """API object link to `cloudgenix.put_api.Put`""" self.patch = subclasses["patch"]() """API object link to `cloudgenix.patch_api.Patch`""" self.delete = subclasses["delete"]() """API object link to `cloudgenix.delete_api.Delete`""" self.interactive = subclasses["interactive"]() """API object link to `cloudgenix.interactive.Interactive`""" self.ws = subclasses["ws"]() """API object link to `cloudgenix.ws.WebSockets`""" return ``` -------------------------------- ### Logging Setup in Python SDK Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Configures logging for the CloudGenix SDK. It sets up a logger for the API using the module's name and a separate logger for websockets. This allows for debug printing via `cloudgenix.API.set_debug`. ```python import logging # Set logging to function name api_logger = logging.getLogger(__name__) # websocket logger is handled slightly differently, so we will have a seperate handle. ws_logger = logging.getLogger('websockets') ``` -------------------------------- ### Initialize and Fetch Sites using CloudGenix SDK Source: https://github.com/cloudgenix/sdk-python/blob/master/README.md This snippet demonstrates how to instantiate the CloudGenix API client, perform an interactive login, and retrieve a list of sites. It uses the built-in jd helper to pretty-print the JSON response. ```python from cloudgenix import API, jd # Instantiate the CloudGenix API constructor sdk = API() # Call CloudGenix API login using the Interactive helpers sdk.interactive.login() # Print a dump of the list of sites for your selected account jd(sdk.get.sites()) ``` -------------------------------- ### GET /view_headers Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Retrieves all current headers in the session. ```APIDOC ## GET /view_headers ### Description Returns a dictionary of all headers currently set in the session. ### Method GET ### Endpoint /view_headers ### Response #### Success Response (200) - **headers** (dict) - Current session headers. ``` -------------------------------- ### GET /view_rest_retry Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Retrieves the current retry configuration for the session. ```APIDOC ## GET /view_rest_retry ### Description Returns the current retry settings for the HTTP session. ### Method GET ### Endpoint /view_rest_retry ### Parameters #### Query Parameters - **url** (string) - Optional - The URL to check retry settings for. Defaults to 'https://'. ### Response #### Success Response (200) - **retries** (dict) - The retry configuration object. #### Response Example { "total": 3, "backoff_factor": 0.1 } ``` -------------------------------- ### Python SDK Initialization and Basic Usage Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/ws_api.m.html Demonstrates how to initialize the CloudGenix SDK and perform basic operations. This typically involves setting up authentication and making initial API calls. No external dependencies are strictly required beyond the SDK itself. ```python from cloudgenix import CloudGenix # Initialize the SDK with your CloudGenix controller details cgx = CloudGenix(controller_ip='your_controller_ip', token='your_auth_token') # Example: Get a list of sites sites = cgx.get_sites() print(f"Found {len(sites)} sites.") # Example: Get a specific site by name site_name = 'MySite' specific_site = next((site for site in sites if site.name == site_name), None) if specific_site: print(f"Details for site '{site_name}': {specific_site.to_dict()}") else: print(f"Site '{site_name}' not found.") ``` -------------------------------- ### GET /policysets Source: https://context7.com/cloudgenix/sdk-python/llms.txt Retrieve network policy sets and their associated rules. ```APIDOC ## GET /policysets ### Description Fetches all policy sets or specific rules within a policy set. ### Method GET ### Endpoint /policysets or /policyrules ### Parameters #### Query Parameters - **policyset_id** (string) - Required for rules - ID of the policy set to query ### Response #### Success Response (200) - **items** (array) - List of policy sets or rules #### Response Example { "items": [{"name": "Global_Policy", "id": "12345"}] } ``` -------------------------------- ### GET /appdefs Source: https://context7.com/cloudgenix/sdk-python/llms.txt Retrieve application definitions used for traffic classification. ```APIDOC ## GET /appdefs ### Description Retrieves a list of all application definitions or a specific definition by ID. ### Method GET ### Endpoint /appdefs/{appdef_id} ### Parameters #### Path Parameters - **appdef_id** (string) - Optional - Unique identifier for the application definition ### Response #### Success Response (200) - **items** (array) - List of application definitions #### Response Example { "items": [{"display_name": "Office365", "category": "SaaS"}] } ``` -------------------------------- ### GET /websocket/headers Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Retrieve the current list of headers configured for the WebSocket object. ```APIDOC ## GET /websocket/headers ### Description View current headers in the API() WebSocket object. ### Method GET ### Endpoint /websocket/headers ### Response #### Success Response (200) - **headers** (dict) - A dictionary where keys are header names and values are header values. #### Response Example { "Authorization": "Bearer token", "Content-Type": "application/json" } ``` -------------------------------- ### Initialize CloudGenix API Class Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html This snippet demonstrates how to instantiate the main API class. It sets up the controller URL, SSL verification settings, and update check preferences. ```python from cloudgenix import API # Initialize the API client # controller: URL of the CloudGenix controller # ssl_verify: Boolean or file path for SSL certificate verification # update_check: Enable or disable SDK update notifications cg_api = API(controller='https://api.elcapitan.cloudgenix.com', ssl_verify=True, update_check=True) ``` -------------------------------- ### GET /accounts/password-policy Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/patch_api.m.html Retrieves the current password security policy settings for the tenant. ```APIDOC ## GET /accounts/password-policy ### Description Fetches the configured password policy, including complexity requirements and account lockout settings. ### Method GET ### Endpoint /accounts/password-policy ### Parameters None ### Response #### Success Response (200) - **minimum_password_length** (integer) - Minimum required characters - **enable_two_numbers** (boolean) - Requirement for numeric characters - **failed_login_attempts** (integer) - Max allowed failed attempts #### Response Example { "minimum_password_length": 8, "enable_two_numbers": true, "failed_login_attempts": 5 } ``` -------------------------------- ### Initialize CloudGenix API Source: https://context7.com/cloudgenix/sdk-python/llms.txt Demonstrates how to initialize the CloudGenix API class with various configuration options, including default settings, custom controller URLs, SSL verification settings, and custom certificate paths. It also shows how to access the SDK version. ```python import cloudgenix # Basic initialization with defaults sdk = cloudgenix.API() # Custom controller URL and SSL verification disabled sdk = cloudgenix.API( controller="https://api.cloudgenix.com", ssl_verify=False, update_check=True # Check for SDK updates on instantiation ) # Using custom SSL certificate file sdk = cloudgenix.API(ssl_verify="/path/to/custom/ca-bundle.crt") # Access SDK version print(f"CloudGenix SDK Version: {sdk.version}") # Output: CloudGenix SDK Version: 6.6.2b1 ``` -------------------------------- ### GET /api/tenants/{tenant_id}/ws Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/ws_api.m.html Opens the default Tenant WebSocket for use in multiple functions. ```APIDOC ## GET /api/tenants/{tenant_id}/ws ### Description Opens the default Tenant WebSocket for use in multiple functions. ### Method GET ### Endpoint /{api_version}/api/tenants/{tenant_id}/ws ### Parameters #### Path Parameters - **tenant_id** (string) - Required - The unique identifier for the tenant. #### Query Parameters - **api_version** (string) - Optional - The API version to use (default v2.0). ### Response #### Success Response (200) - **websocket** (object) - Returns a websockets.client.Connect object. ``` -------------------------------- ### Initialize Tenant Profile and Session Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/interactive.m.html This snippet handles the post-authentication steps, including parsing the authentication region, updating controller settings, and retrieving the operator profile to finalize the session. ```python auth_token = response.cgx_content.get('x_auth_token') if auth_token: auth_region = self._parent_class.parse_region(response) self._parent_class.update_region_to_controller(auth_region) self._parent_class.reparse_login_cookie_after_region_update(response) if self.update_profile_vars() and self._parent_class.tenant_id: if self.tenant_update_vars(): if self._parent_class.is_esp and client_login: return self.client_login(client=client) self._parent_class._password = None self._parent_class.remove_header('Referer') return True ``` -------------------------------- ### GET /request_url Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Determines the appropriate URL to use for a request based on proxy settings and request schemes. ```APIDOC ## GET /request_url ### Description Calculates the URL to be used for the final request. If a proxy is involved, it returns the full URL; otherwise, it returns the path portion. ### Method GET ### Endpoint /request_url ### Parameters #### Query Parameters - **request** (PreparedRequest) - Required - The request being processed. - **proxies** (dict) - Required - Dictionary of proxy mappings. ### Response #### Success Response (200) - **url** (string) - The resolved URL string. #### Response Example { "url": "https://api.cloudgenix.com/v1/resource" } ``` -------------------------------- ### Python SDK: Create a Network Policy Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/patch_api.m.html Demonstrates how to create a new network policy using the CloudGenix Python SDK. This involves defining policy rules and parameters. ```python from cloudgenix import CloudGenix # Assuming cgx is an authenticated CloudGenix object # cgx = CloudGenix(site='your_site', username='your_username', password='your_password') # cgx.login() policy_data = { "name": "New_Network_Policy", "description": "Policy created via SDK", "rules": [ { "name": "Rule1", "source": {"any": True}, "destination": {"any": True}, "action": "allow", "priority": 100 } ] } created_policy = cgx.create_network_policy(policy_data) if created_policy: print(f"Successfully created network policy: {created_policy['name']} (ID: {created_policy['id']})") else: print("Failed to create network policy.") ``` -------------------------------- ### GET /extract_items Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Extracts a list of items from a CloudGenix API response object based on a specified key. ```APIDOC ## GET /extract_items ### Description Extracts a list of items from a CloudGenix extended requests.Response object. It allows for custom error labeling and specifying which HTTP status codes should be treated as silent successes. ### Method GET ### Parameters #### Request Body - **resp_object** (requests.Response) - Required - The response object to parse. - **error_label** (string) - Optional - Text to describe the operation in case of error. - **pass_code_list** (list) - Optional - List of HTTP codes to silently pass. - **items_key** (string) - Optional - The key to extract from the JSON response (default: 'items'). ### Response #### Success Response (200) - **items** (list) - A list of objects extracted from the response. ``` -------------------------------- ### Display Interactive Client Selection Menu Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/interactive.m.html The quick_menu method renders a CLI menu based on a provided list of tuples and a format string. It validates user input until a valid selection is made or the user quits, returning the selected tuple and a success status. ```python @staticmethod def quick_menu(banner, list_line_format, choice_list): api_logger.info('quick_menu function:') invalid = True menu_int = -1 while invalid: print(banner) for item_index, item_value in enumerate(choice_list): print(list_line_format.format(item_index + 1, *item_value)) menu_choice = compat_input("\nChoose a Number or (Q)uit: ") if str(menu_choice).lower() in ['q']: print("Canceling Menu..") return False, None try: menu_int = int(menu_choice) sanity = True except ValueError: print("ERROR: ", menu_choice) sanity = False if sanity and 1 <= menu_int <= len(choice_list): invalid = False else: print("Invalid input, needs to be between 1 and {0}.\n".format(len(choice_list))) return True, choice_list[int(menu_int) - 1] ``` -------------------------------- ### GET /operator Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/patch_api.m.html Retrieves the operator configuration details including account settings, roles, and security policies. ```APIDOC ## GET /operator ### Description Retrieves the full configuration object for an operator, including personal information, security settings, and associated tenant details. ### Method GET ### Endpoint /operator ### Parameters #### Path Parameters None #### Query Parameters None ### Request Body N/A ### Request Example {} ### Response #### Success Response (200) - **name** (string) - Name of the operator - **pan_account_id** (string) - Palo Alto Networks account ID - **operator** (object) - Detailed operator profile containing addresses, roles, and settings #### Response Example { "name": "Example Operator", "pan_account_id": "12345", "operator": { "email": "user@example.com", "first_name": "John", "last_name": "Doe" } } ``` -------------------------------- ### GET /api/tenants/{tenant_id}/elements/{element_id}/ws/toolkitsessions Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/ws_api.m.html Opens a Toolkit Session WebSocket for a specific element. ```APIDOC ## GET /api/tenants/{tenant_id}/elements/{element_id}/ws/toolkitsessions ### Description Open a Toolkit Session WebSocket for a specific element. ### Method GET ### Endpoint /{api_version}/api/tenants/{tenant_id}/elements/{element_id}/ws/toolkitsessions ### Parameters #### Path Parameters - **tenant_id** (string) - Required - The unique identifier for the tenant. - **element_id** (string) - Required - The unique identifier for the element. #### Query Parameters - **api_version** (string) - Optional - The API version to use (default v2.0). - **cols** (integer) - Optional - Number of columns for terminal (default 207). - **rows** (integer) - Optional - Number of rows for terminal (default 53). ### Response #### Success Response (200) - **websocket** (object) - Returns a websockets.client.Connect object. ``` -------------------------------- ### Initialize CloudGenix API Constructor Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html The __init__ method initializes the API session, configures SSL verification, sets up REST retry parameters, and updates the User-Agent header for API requests. ```python def __init__(self, controller=controller, ssl_verify=verify, update_check=True): self.version = version self.update_info_url = update_info_url if controller and isinstance(controller, (binary_type, text_type)): self.controller = controller.lower() self.controller_orig = controller.lower() self._session = requests.Session() if isinstance(ssl_verify, (binary_type, text_type, bool)): self.ssl_verify(ssl_verify, update_adapter=False) self.modify_rest_retry(update_adapter=False) self.update_session_adapter() if isinstance(update_check, bool): self.update_check = update_check if update_check: self.notify_for_new_version() user_agent = self._session.headers.get('User-Agent') if user_agent: user_agent += ' (CGX SDK v{0})'.format(self.version) else: user_agent = 'python-requests/UNKNOWN (CGX SDK v{0})'.format(self.version) self._session.headers.update({ 'Accept': 'application/json', 'User-Agent': text_type(user_agent) }) ``` -------------------------------- ### Display Interactive CLI Menu Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/interactive.m.html The quick_menu function renders a formatted list of options to the console and prompts the user for selection. It handles input validation, allows for cancellation via 'Q', and returns the selected item tuple. ```python @staticmethod def quick_menu(banner, list_line_format, choice_list): api_logger.info('quick_menu function:') invalid = True menu_int = -1 while invalid: print(banner) for item_index, item_value in enumerate(choice_list): print(list_line_format.format(item_index + 1, *item_value)) menu_choice = compat_input("\nChoose a Number or (Q)uit: ") if str(menu_choice).lower() in ['q']: print("Canceling Menu..") return False, None try: menu_int = int(menu_choice) sanity = True except ValueError: print("ERROR: ", menu_choice) sanity = False if sanity and 1 <= menu_int <= len(choice_list): invalid = False else: print("Invalid input, needs to be between 1 and {0}.\n".format(len(choice_list))) return True, choice_list[int(menu_int) - 1] ``` -------------------------------- ### Get WAN Interfaces API Source: https://context7.com/cloudgenix/sdk-python/llms.txt Retrieves WAN (Wide Area Network) interface configurations for a specified site. ```APIDOC ## Get WAN Interfaces ### Description Retrieve WAN interface configurations for a site. ### Method GET ### Endpoint /api/v1/sites/{site_id}/waninterfaces ### Parameters #### Path Parameters - **site_id** (string) - Required - The unique identifier of the site. ### Request Example ```python import cloudgenix sdk = cloudgenix.API() sdk.interactive.login() site_id = "15136303050290012" # Get all WAN interfaces for a site response = sdk.get.waninterfaces(site_id=site_id) if response.cgx_status: wan_interfaces = response.cgx_content.get('items', []) for wan in wan_interfaces: print(f"WAN Interface: {wan.get('name')}") print(f" Type: {wan.get('type')}") print(f" Link BW Down: {wan.get('link_bw_down')} kbps") print(f" Link BW Up: {wan.get('link_bw_up')} kbps") print(f" Label: {wan.get('label_id')}") ``` ### Response #### Success Response (200) - **items** (array) - A list of WAN interface objects. - **name** (string) - The name of the WAN interface. - **type** (string) - The type of WAN interface (e.g., 'VDSL', 'Ethernet'). - **link_bw_down** (integer) - The download bandwidth in kbps. - **link_bw_up** (integer) - The upload bandwidth in kbps. - **label_id** (string) - The label identifier for the WAN interface. #### Response Example ```json { "items": [ { "name": "WAN-1", "type": "Ethernet", "link_bw_down": 100000, "link_bw_up": 100000, "label_id": "WAN-Primary" } ], "total_count": 1 } ``` ``` -------------------------------- ### Configuring CloudGenix Network Policies (Python) Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/ws_api.m.html This code demonstrates how to create or update network policies using the CloudGenix SDK. It involves defining policy objects with specific rules and applying them to the network. This requires a good understanding of CloudGenix policy structures. Errors may occur if the policy definition is invalid. ```python from cloudgenix import CloudGenix, NetworkPolicy # Assuming cgx is already initialized # cgx = CloudGenix(controller_ip='your_controller_ip', token='your_auth_token') # Define a new network policy new_policy = NetworkPolicy( name='New_App_Policy', description='Policy for a new critical application', priority=10, rules=[ { 'name': 'Allow_Critical_App', 'app_list': ['CriticalApp1', 'CriticalApp2'], 'action': 'allow', 'source': 'any', 'destination': 'any' } ] ) # Create the policy on the CloudGenix controller # try: # created_policy = cgx.create_network_policy(new_policy) # print(f"Successfully created policy: {created_policy.name} (ID: {created_policy.id})") # except Exception as e: # print(f"Error creating policy: {e}") # Note: Uncomment the creation part to actually create the policy. ``` -------------------------------- ### proxy_headers() - Get Proxy Headers Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Returns a dictionary of headers to add to requests sent through a proxy. This is for internal use or subclassing. ```APIDOC ## proxy_headers() ### Description Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code and is only exposed for use when subclassing the `HTTPAdapter`. ### Method `proxy_headers(proxy)` ### Endpoint N/A (Instance Method) ### Parameters - **proxy** (string) - The URL of the proxy being used for this request. ### Request Example ```python headers = http_adapter.proxy_headers('http://myproxy.com:8080') ``` ### Response - **headers** (dict) - A dictionary of headers to be sent to the proxy. #### Success Response (200) - **headers** (dict) - The dictionary of proxy headers. #### Response Example ```json { "Proxy-Authorization": "Basic ..." } ``` ``` -------------------------------- ### API Initialization Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Initializes the CloudGenix API client, setting up the session, controller URL, and SSL verification settings. ```APIDOC ## Initialization of CloudGenix API ### Description Creates the API constructor object to manage connections to the CloudGenix controller. This object handles session state, authentication tokens, and REST request configurations. ### Method Constructor ### Parameters #### Path Parameters - **controller** (string) - Optional - The base URL of the CloudGenix controller. Defaults to 'https://api.elcapitan.cloudgenix.com'. - **ssl_verify** (bool/string) - Optional - Determines if SSL verification should be performed. Can be a boolean or a file path to a CA bundle. - **update_check** (bool) - Optional - Whether to notify the user if a newer version of the SDK is available. ### Request Example ```python from cloudgenix import API # Initialize the API client cg = API(controller='https://api.elcapitan.cloudgenix.com', ssl_verify=True) ``` ### Response #### Success Response (Object) - **_session** (requests.Session) - The underlying session object used for all API calls. - **tenant_id** (int) - The numeric ID of the tenant, populated after login. - **operator_id** (string) - The ID of the current authenticated operator. ``` -------------------------------- ### Python: Select and Login to Cloudgenix Client Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/interactive.m.html This function allows a user to select a specific client from a list of detected ESP/MSP clients and then logs into that selected client. It handles the display of client options, user selection, and the subsequent API calls to authenticate with the chosen client. It also manages potential region changes and updates necessary session information. ```python def client_login(self, client=None): """ If logged into an ESP/MSP, now login to a client. **Parameters**: - **client**: Optional. ESP/MSP managed Client Canonical Name, Client Name, or Client ID (matched in this order) **Returns**: Boolean Success. """ api_logger.info('client_login function:') if self._parent_class.token_session is True: # AUTH_TOKENs are not allowed to do client login/logout. print("Static AUTH_TOKENs are not allowed to perform client login/logout operations.") return False # sanity check if ESP if self._parent_class.is_esp: # ESP/MSP! Pass any client info through to client choice. choose_status, chosen_client_id, chosen_client_region = self.client_choice(client=client) if choose_status: # attempt to login as client clogin_resp = self._parent_class.post.clients_login(chosen_client_id, {}) if clogin_resp.cgx_status: # see if we need to change regions. redirect_region = clogin_resp.cgx_content.get('redirect_region') redirect_x_auth_token = clogin_resp.cgx_content.get('redirect_x_auth_token') redirect_urlpath = clogin_resp.cgx_content.get('redirect_urlpath') if redirect_region is not None and redirect_x_auth_token is not None: api_logger.debug('CLIENT REGION SWITCH: %s -> %s', self._parent_class.controller_region, redirect_region) # Need to change regions. self._parent_class.update_region_to_controller(redirect_region) # Now set a temporary X-Auth-Token header, overwriting previous if there. # if using a static AUTH_TOKEN, client login will switch to dynamic via # Cookies. self._parent_class.add_headers({'X-Auth-Token': redirect_x_auth_token}) # login successful, update profile # Profile call will set new login cookies if switching regions. c_profile = self.update_profile_vars() if redirect_region is not None and redirect_x_auth_token is not None: # if region switch, we need to clear the X-Auth-Token header, as it was a temporary value # and now we are using cookies for ephemeral AUTH_TOKENs. self._parent_class.remove_header('X-Auth-Token') # Update tenant info. t_profile = self.tenant_update_vars() if c_profile and t_profile: # successful full client login. self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return True else: if t_profile: print("ESP Client Tenant detail retrieval failed. ESP may no longer be valid.") # clear password out of memory self._parent_class.email = None self._parent_class._password = None # remove referer header prior to continuing. self._parent_class.remove_header('Referer') return False else: print("ESP Client Login failed. ESP session active.") # clear password out of memory self._parent_class.email = None ``` -------------------------------- ### GET /users/{id} Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/patch_api.m.html Retrieves the detailed profile information for a specific user, including account status, roles, and security settings. ```APIDOC ## GET /users/{id} ### Description Retrieves the full profile of a user, including linked accounts, phone numbers, and security configurations. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Request Example GET /users/user-12345 ### Response #### Success Response (200) - **email** (string) - User email address - **first_name** (string) - User first name - **last_name** (string) - User last name - **roles** (array) - List of assigned roles - **is_locked** (boolean) - Indicates if the account is locked #### Response Example { "id": "user-12345", "email": "user@example.com", "first_name": "John", "last_name": "Doe", "is_locked": false } ``` -------------------------------- ### Constructor Initialization Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Initializes the CloudGenix API constructor object, setting up the controller URL, SSL verification settings, and session headers. ```APIDOC ## Constructor __init__ ### Description Initializes the API constructor object, creates the requests session, and binds API method classes (GET, POST, PUT, PATCH, DELETE, Interactive, WebSockets). ### Parameters #### Arguments - **controller** (string) - Optional - Initial Controller URL String (default: https://api.elcapitan.cloudgenix.com) - **ssl_verify** (bool/string) - Optional - Should SSL be verified for this system. Can be a file path or boolean. - **update_check** (bool) - Optional - Enable/Disable SDK update check and new release notifications. ### Request Example ```python from cloudgenix import API cgx = API(controller='https://api.example.com', ssl_verify=True, update_check=True) ``` ``` -------------------------------- ### Get Interfaces API Source: https://context7.com/cloudgenix/sdk-python/llms.txt Retrieves a list of network interfaces for a specific element within a given site, or details for a particular interface. ```APIDOC ## Get Interfaces ### Description Retrieve interfaces for a specific element at a site. ### Method GET ### Endpoint /api/v1/sites/{site_id}/elements/{element_id}/interfaces /api/v1/sites/{site_id}/elements/{element_id}/interfaces/{interface_id} ### Parameters #### Path Parameters - **site_id** (string) - Required - The unique identifier of the site. - **element_id** (string) - Required - The unique identifier of the element. - **interface_id** (string) - Optional - The unique identifier of the interface to retrieve. ### Request Example ```python import cloudgenix sdk = cloudgenix.API() sdk.interactive.login() site_id = "15136303050290012" element_id = "15136303050290050" # Get all interfaces for an element response = sdk.get.interfaces(site_id=site_id, element_id=element_id) if response.cgx_status: interfaces = response.cgx_content.get('items', []) for iface in interfaces: print(f"Interface: {iface.get('name')} - Type: {iface.get('type')} - Admin State: {iface.get('admin_up')}") if iface.get('ipv4_config'): print(f" IPv4: {iface['ipv4_config'].get('static_config', {}).get('address')}") # Get a specific interface interface_id = "15136303050290100" response = sdk.get.interfaces(site_id=site_id, element_id=element_id, interface_id=interface_id) if response.cgx_status: iface = response.cgx_content print(f"Interface Details: {iface.get('name')}") ``` ### Response #### Success Response (200) - **items** (array) - A list of interface objects. - **name** (string) - The name of the interface. - **type** (string) - The type of the interface (e.g., 'LAN', 'WAN'). - **admin_up** (boolean) - Indicates if the interface is administratively up. - **ipv4_config** (object) - IPv4 configuration details. - **static_config** (object) - Static IPv4 configuration. - **address** (string) - The static IPv4 address. #### Response Example ```json { "items": [ { "name": "eth0", "type": "LAN", "admin_up": true, "ipv4_config": { "static_config": { "address": "192.168.1.1/24" } } } ], "total_count": 1 } ``` ``` -------------------------------- ### TlsHttpAdapter Class Initialization Source: https://github.com/cloudgenix/sdk-python/blob/master/docs/index.html Initializes a custom HTTP adapter with a specific SSL context for secure communication. ```APIDOC ## Class: TlsHttpAdapter ### Description A patched Requests HTTP Transport adapter that allows specification of a specific SSL Context. This enables fine-grained control over SSL Ciphers, Options, and CA specifications. ### Constructor `TlsHttpAdapter(ssl_context=None, **kwargs)` ### Parameters - **ssl_context** (ssl.SSLContext) - Optional - A custom SSL context object. If None, a default context is created using the SDK's CA bundle and default ciphers. - **kwargs** (dict) - Optional - Additional arguments passed to the base HTTPAdapter. ### Methods - **init_poolmanager(*args, **kwargs)**: Overrides the base method to inject the custom ssl_context into the pool manager. - **proxy_manager_for(*args, **kwargs)**: Overrides the base method to inject the custom ssl_context into the proxy manager. ### Usage Example ```python import ssl from cloudgenix import TlsHttpAdapter ctx = ssl.create_default_context() adapter = TlsHttpAdapter(ssl_context=ctx) ``` ``` -------------------------------- ### Get Elements (Devices) API Source: https://context7.com/cloudgenix/sdk-python/llms.txt Retrieves a list of all network elements (devices) in the network or details for a specific element using its ID. ```APIDOC ## Get Elements (Devices) ### Description Retrieve all elements or a specific element by ID. ### Method GET ### Endpoint /api/v1/elements /api/v1/elements/{element_id} ### Parameters #### Path Parameters - **element_id** (string) - Optional - The unique identifier of the element to retrieve. #### Query Parameters - **site_id** (string) - Optional - Filters elements by the site they belong to. ### Request Example ```python import cloudgenix sdk = cloudgenix.API() sdk.interactive.login() # Get all elements response = sdk.get.elements() if response.cgx_status: elements = response.cgx_content.get('items', []) for element in elements: print(f"Element: {element.get('name')} - Model: {element.get('model_name')} - State: {element.get('state')}") # Get a specific element element_id = "15136303050290050" response = sdk.get.elements(element_id=element_id) if response.cgx_status: element = response.cgx_content print(f"Element: {element.get('name')}") print(f"Serial: {element.get('serial_number')}") print(f"Software Version: {element.get('software_version')}") print(f"Site ID: {element.get('site_id')}") ``` ### Response #### Success Response (200) - **items** (array) - A list of element objects. - **name** (string) - The name of the element. - **model_name** (string) - The model of the element. - **state** (string) - The current operational state of the element. - **serial_number** (string) - The serial number of the element. - **software_version** (string) - The software version running on the element. - **site_id** (string) - The ID of the site the element is associated with. #### Response Example ```json { "items": [ { "name": "Router-1", "model_name": "CloudGenix-CGX1000", "state": "Up", "serial_number": "CGX12345", "software_version": "6.5.0", "site_id": "15136303050290012" } ], "total_count": 1 } ``` ``` -------------------------------- ### Open WebSocket Toolkit Sessions Source: https://context7.com/cloudgenix/sdk-python/llms.txt Establishes asynchronous WebSocket connections for real-time toolkit sessions or default tenant event streaming. ```python async with sdk.ws.toolkit_session(element_id="15136303050290050", cols=207, rows=53) as websocket: await websocket.send('show version\n') response = await websocket.recv() async with sdk.ws.default() as websocket: async for message in websocket: print(f"Received: {message}") ```