### Example: Run with OneAPI Client and Interactive Prompts Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/alerts/README.md This example shows the command to run the script using the default OneAPI client. The script then guides the user through interactive prompts for alert type, time filter, and alert ID. ```bash # Run with OneAPI client (default) python zdx_alerts_management.py # The script will prompt for: # 1. Alert type (a/b/c/d) # 2. Time filter (if applicable) # 3. Alert ID (for options c and d) ``` -------------------------------- ### Install v2.x Beta Release Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Use this command to install the v2.x beta release of the SDK. Pre-releases must be explicitly requested. ```bash pip install --pre --upgrade "zscaler-sdk-python>=2.0.0b1" ``` -------------------------------- ### List Locations (Legacy Client Examples) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/administration/README.md Examples for listing locations using the legacy client, including basic listing. ```bash # List all locations using legacy client python zdx_management.py -l --use-legacy-client ``` -------------------------------- ### Install SDK in Development Mode (Basic) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/tests/integration/zaiguard/README.md Basic installation of the SDK in development mode, which is often required for running tests and development. ```bash pip install -e . ``` -------------------------------- ### Get User by ID (Example) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zia/user_management.md An example demonstrating how to fetch a user group by its ID. Note: The example code seems to be for fetching a group, not a user, despite the function name. ```python >>> user, _, error = client.zia.user_management.get_group(updated_group.id) ... if error: ... print(f"Error fetching group by ID: {error}") ... return ... print(f"Fetched group by ID: {fetched_group.as_dict()}") ``` -------------------------------- ### Install SDK in Development Mode Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/tests/integration/zaiguard/README.md Install the SDK with development dependencies to resolve potential import errors. ```bash pip install -e ".[dev]" ``` -------------------------------- ### List Departments (Legacy Client Examples) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/administration/README.md Examples for listing departments using the legacy client, including basic listing and filtering by time. ```bash # List all departments using legacy client python zdx_management.py -d --use-legacy-client ``` ```bash # List departments from the past 5 hours using legacy client python zdx_management.py -d -s 5 --use-legacy-client ``` -------------------------------- ### List Locations (OneAPI Examples) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/administration/README.md Examples for listing locations using the OneAPI client, including basic listing and verbose output. ```bash # List all locations python zdx_management.py -l ``` -------------------------------- ### Example: Run with Legacy Client and Interactive Prompts Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/alerts/README.md This example demonstrates how to invoke the script using the legacy client. Similar to the OneAPI client, it will present interactive prompts for user input. ```bash # Run with legacy client python zdx_alerts_management.py --use-legacy-client # Same interactive prompts as OneAPI client ``` -------------------------------- ### List Departments (OneAPI Examples) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/administration/README.md Collection of examples demonstrating listing departments with the OneAPI client, including filtering by time and enabling verbose output. ```bash # List all departments python zdx_management.py -d ``` ```bash # List departments from the past 3 hours python zdx_management.py -d -s 3 ``` ```bash # List locations with verbose output python zdx_management.py -l -v ``` -------------------------------- ### Example Command for OneAPI Client Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/application/app_metrics/README.md This bash command shows how to run the ZDX application metrics script using the default OneAPI client. The script will then guide you through interactive prompts for filtering data. ```bash # Run with OneAPI client (default) python zdx_app_metrics.py # The script will prompt for: # 1. Application ID # 2. Hours to look back (optional) # 3. Metric name (optional) # 4. Location ID (optional) # 5. Department ID (optional) # 6. Geolocation ID (optional) ``` -------------------------------- ### Run SaaS Security Example Script Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zins/saas_security/README.md Execute the Python example script after setting the required environment variables. This script demonstrates how to query CASB data. ```bash # Run the example python saas_security_example.py ``` -------------------------------- ### Run Firewall Analytics Example Script Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zins/firewall/README.md Execute the main Python script to run the firewall analytics examples after setting the required environment variables. ```bash # Run the example python firewall_example.py ``` -------------------------------- ### Install Zscaler SDK Python Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/_sources/index.rst.txt Install the latest version of the Zscaler SDK Python from PyPI using pip. ```console $ pip install zscaler-sdk-python ``` -------------------------------- ### Install zscaler-sdk-python v2.x Beta Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/UPGRADE_GUIDE.md Use this command to install the latest v2.x beta release. Ensure you use the --pre flag or specify a beta version to opt into pre-releases. ```bash pip install --pre --upgrade "zscaler-sdk-python>=2.0.0b1" ``` -------------------------------- ### v1.x Legacy ZIA Authentication Example Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/UPGRADE_GUIDE.md This is a legacy example from v1.x that uses per-product credentials and will no longer work in v2.x. It demonstrates authentication for ZIA users. ```python from zscaler.oneapi_client import LegacyZIAClient config = { "username": "...", "password": "...", "api_key": "...", "cloud": "zscalertwo", } with LegacyZIAClient(config) as client: users, _, _ = client.user_management.list_users() ``` -------------------------------- ### Example Private Key in PEM Format Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md This is an example of a private key in PEM format, used for authentication with the Zscaler SDK. Note that this is not a production key. ```text -----BEGIN PRIVATE KEY----- # Example private key (not a real key) MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCv3krdYg3z7h0H 60QoePJMghllQxsfPxp3mgFfYEaIbF88Z8dvPZEfhAtP19/Mv62ASjwgqzQzKHRV -----END PRIVATE KEY----- ``` -------------------------------- ### Full Pagination Example with Error Handling Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/index.md A comprehensive example demonstrating how to fetch all paginated results, including error handling for initial fetches and subsequent page requests. It also shows how to catch StopIteration when no more data is available. ```python def main(): with ZscalerClient(config) as client: query_parameters = {} groups, resp, err = client.zia.user_management.list_groups(query_parameters) if err: print(f"Error: {err}") return print(f"Processing {len(groups)} groups:") for group in groups: print(group) while resp.has_next(): next_page, err = resp.next() if err: print(f"Error fetching next page: {err}") break for group in next_page: print(group) try: resp.next() # Will raise StopIteration if no more data except StopIteration: print("✅ No more groups to retrieve.") if __name__ == "__main__": main() ``` -------------------------------- ### v2.x OneAPI Authentication Example Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/UPGRADE_GUIDE.md This example demonstrates the OneAPI authentication method required for v2.x, which works across all supported Zscaler products. It shows the configuration for OneAPI client initialization. ```python from zscaler import ZscalerClient config = { "clientId": "...", "clientSecret": "...", # or "privateKey": "..." for JWT auth "vanityDomain": "...", "cloud": "production", # optional; defaults to production } client = ZscalerClient(config) ``` -------------------------------- ### LegacyZTBClient Usage Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Example of how to initialize and use the LegacyZTBClient to interact with ZTB resources. ```APIDOC ## LegacyZTBClient Initialization and Usage ### Description Demonstrates initializing the `LegacyZTBClient` with configuration options and making calls to ZTB resources like alarms and devices. ### Configuration Options - **api_key** (string) - Required - Your ZTB API key. - **cloud** (string) - Required if `override_url` is not provided - The cloud subdomain (e.g., `zscalerbd-api`). - **override_url** (string) - Optional - Full base URL override (e.g., `https://zscalerbd-api.goairgap.com`). If set, `cloud` is ignored. - **partner_id** (string) - Optional - Partner ID for the `x-partner-id` header. - **timeout** (integer) - Optional - Request timeout in seconds (default: 240). - **max_retries** (integer) - Optional - Max retry attempts for specific errors (default: 5). ### Client Initialization Example ```python from zscaler.oneapi_client import LegacyZTBClient config = { "api_key": "{yourZTBAPIKey}", "cloud": "zscalerbd-api", # or use override_url "logging": {"enabled": False, "verbose": False}, } with LegacyZTBClient(config) as client: # API calls go here pass ``` ### Resource Interaction Examples #### List Alarms - **Method**: `client.ztb.alarms.list_alarms()` - **Description**: Retrieves a list of alarms. - **Returns**: `alarms`, `response`, `error` #### List Active Devices - **Method**: `client.ztb.devices.list_active_devices(query_params)` - **Description**: Retrieves a list of active devices with optional pagination. - **Parameters**: - **query_params** (dict) - Optional - Query parameters such as `page` and `limit`. - **page** (integer) - Optional - Page number for pagination. - **limit** (integer) - Optional - Number of items per page. - **Returns**: `devices`, `response`, `error` ``` -------------------------------- ### Initialize and Use LegacyZTBClient Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/guides/ztb.md Demonstrates how to initialize the LegacyZTBClient with configuration and access ZTB resources like alarms and devices. Includes basic error handling and iteration over results. ```python from zscaler.oneapi_client import LegacyZTBClient config = { "api_key": "{yourZTBAPIKey}", "cloud": "zscalerbd-api", "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZTBClient(config) as client: alarms, response, error = client.ztb.alarms.list_alarms() if error: print(f"Error: {error}") return devices, _, err = client.ztb.devices.list_active_devices( query_params={"page": 1, "limit": 25} ) if not err: for d in devices: print(d.hostname) if __name__ == "__main__": main() ``` -------------------------------- ### Quick ZIA Example Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/_sources/index.rst.txt Initialize the ZIA client helper and list users. Ensure you have your ZIA API key, cloud name, username, and password. ```python from zscaler import ZIAClientHelper from pprint import pprint zia = ZIAClientHelper(api_key='ZIA_API_KEY', cloud='ZIA_CLOUD', username='ZIA_USERNAME', password='ZIA_PASSWORD') for user in zia.users.list_users(): pprint(user) ``` -------------------------------- ### Get Firewall Traffic by Action Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zins/firewall.md Retrieves Zero Trust Firewall traffic data aggregated by action. Specify start and end times, an optional limit, filtering, and ordering. ```python entries, _, err = client.zins.firewall.get_traffic_by_action( start_time=start_time, end_time=end_time, limit=10 ) ``` -------------------------------- ### Get Firewall Traffic by Location with Filtering Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zins/firewall.md Retrieves Zero Trust Firewall traffic data aggregated by location, with the ability to filter by location name. Requires specifying start and end times. ```python from zscaler.zins.models.inputs import ( FirewallEntriesFilterBy, StringFilter, FirewallEntryOrderBy ) from zscaler.zins.models.enums import SortOrder # With filtering filter_by = FirewallEntriesFilterBy( name=StringFilter(eq="Location1") ) entries, _, err = client.zins.firewall.get_traffic_by_location( start_time=start_time, end_time=end_time, limit=10, filter_by=filter_by ) ``` -------------------------------- ### Quick ZPA Example Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/_sources/index.rst.txt Initialize the ZPA client helper and list application segments. You will need your ZPA client ID, client secret, and customer ID. ```python from zscaler import ZPAClientHelper from pprint import pprint zpa = ZPAClientHelper(client_id='ZPA_CLIENT_ID', client_secret='ZPA_CLIENT_SECRET', customer_id='ZPA_CUSTOMER_ID') for app_segment in zpa.app_segments.list_segments(): pprint(app_segment) ``` -------------------------------- ### Get Cybersecurity Incidents by Location Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zins/cyber_security.md Fetch cybersecurity incidents, grouped by location or another specified dimension. Requires start and end times in epoch milliseconds. The default grouping is by location ID. ```python entries, _, err = client.zins.cyber_security.get_incidents_by_location( start_time=start_time, end_time=end_time, categorize_by="LOCATION_ID", limit=10 ) ``` -------------------------------- ### Get Cybersecurity Incidents by Category Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zins/cyber_security.md Retrieve cybersecurity incidents, grouped by a specified category. Ensure start and end times are provided in epoch milliseconds. The default categorization is by threat category ID. ```python entries, _, err = client.zins.cyber_security.get_incidents( start_time=start_time, end_time=end_time, categorize_by=["THREAT_CATEGORY_ID"], limit=10 ) ``` -------------------------------- ### Initialize and Use Legacy ZTB Client Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Demonstrates how to initialize the LegacyZTBClient with configuration and use it to list alarms and active devices. Ensure the correct API key and cloud subdomain are provided. The client automatically handles re-authentication on 401 errors and retries on rate limiting or server errors. ```python from zscaler.oneapi_client import LegacyZTBClient config = { "api_key": "{yourZTBAPIKey}", "cloud": "zscalerbd-api", # or use override_url for full URL "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZTBClient(config) as client: alarms, response, error = client.ztb.alarms.list_alarms() if error: print(f"Error listing alarms: {error}") return print(f"Alarms: {alarms}") devices, _, err = client.ztb.devices.list_active_devices( query_params={"page": 1, "limit": 25} ) if not err: for d in devices: print(d.hostname) if __name__ == "__main__": main() ``` -------------------------------- ### Get Visibility Chart Data Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/ztb/logs.md Retrieves data for a visibility chart using specified query parameters. Ensure the 'query_type' is provided. The example iterates through the returned data and prints the type and ID of each item. ```python chart_data, _, err = client.ztb.logs.get_visibility_chart( query_params={"query_type": "sites"} ) if err: print(f"Error: {err}") return for item in chart_data.data: print(item.type, item.id) ``` -------------------------------- ### Get CASB Application Report with Filtering Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zins/saas_security.md Retrieves CASB application report data with specific filtering applied. This example demonstrates how to filter the report by application name using the StringFilter and CasbEntriesFilterBy models. ```python # With filtering from zscaler.zins.models.inputs import CasbEntriesFilterBy, StringFilter filter_by = CasbEntriesFilterBy(name=StringFilter(eq="AppName")) entries, _, err = client.zins.saas_security.get_casb_app_report( start_time=start_time, end_time=end_time, filter_by=filter_by ) ``` -------------------------------- ### Get Firewall Traffic by Location with Ordering Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zins/firewall.md Retrieves Zero Trust Firewall traffic data aggregated by location, with the ability to order the results by a specified field (e.g., 'total') in descending order. Requires specifying start and end times. ```python from zscaler.zins.models.inputs import ( FirewallEntriesFilterBy, StringFilter, FirewallEntryOrderBy ) from zscaler.zins.models.enums import SortOrder # With ordering order_by = [FirewallEntryOrderBy(field_name="total", order=SortOrder.DESC)] entries, _, err = client.zins.firewall.get_traffic_by_location( start_time=start_time, end_time=end_time, order_by=order_by ) ``` -------------------------------- ### Initialize Legacy ZTW Client with Configuration Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Initialize the `LegacyZTWClient` for organizations not yet migrated to Zidentity. Provide credentials via a configuration dictionary. Environment variables can also be used. ```python import random from zscaler.oneapi_client import LegacyZTWClient config = { "username": '{yourUsername}', "password": '{yourPassword}', "api_key": '{yourApiKey}', "cloud": '{yourCloud}', "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZTWClient(config) as client: fetched_prov_url, response, error = client.ZTW.provisioning_url.list_provisioning_url() if error: print(f"Error fetching prov url by ID: {error}") return print(f"Fetched prov url by ID: {fetched_prov_url.as_dict()}") if __name__ == "__main__": main() ``` -------------------------------- ### Install Zscaler Python SDK Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/index.md Use this command to install the Zscaler Python SDK in your project. ```sh pip install zscaler-sdk-python ``` -------------------------------- ### Install Test Dependencies Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/tests/unit/README.md Install pytest and pytest-cov for running tests and generating coverage reports. ```bash pip install pytest pytest-cov ``` -------------------------------- ### Example Command for Legacy Client Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/application/app_metrics/README.md This bash command demonstrates running the ZDX application metrics script with the legacy client. It requires the `--use-legacy-client` flag and will present the same interactive prompts as the OneAPI client. ```bash # Run with legacy client python zdx_app_metrics.py --use-legacy-client # Same interactive prompts as OneAPI client ``` -------------------------------- ### Initialize ZscalerClient and Submit File Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/index.md Instantiate the ZscalerClient with authentication configuration and submit a file for sandbox analysis. Ensure the 'sandboxToken' and 'sandboxCloud' are correctly set. The client can be configured using a dictionary or environment variables. ```python from zscaler import ZscalerClient import os config = { "sandboxToken": '{yourSandboxToken}', "sandboxCloud": '{yourSandboxCloud}', "logging": {"enabled": False, "verbose": False}, } def main(): script_dir = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(script_dir, "test-pe-file.exe") force_analysis = True with ZscalerClient(config) as client: submit, _, err = client.zia.sandbox.submit_file(file_path=file_path, force=force_analysis) if err: print(f"Error submitting file: {err}") else: print("File submitted successfully!") print(f"Response: {submit}") if __name__ == "__main__": main() ``` -------------------------------- ### Example Web Traffic by Location Output Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zins/web_traffic/README.md This is an example of the expected output format for web traffic data grouped by location. ```text ============================================================ Web Traffic by Location ============================================================ Headquarters: 150000 transactions Branch Office A: 85000 transactions Branch Office B: 42000 transactions ... ``` -------------------------------- ### Initialize Legacy ZIA Client and Add Label Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/index.md Demonstrates how to initialize the LegacyZIAClient with configuration including username, password, API key, and cloud. It then shows how to add a new rule label using the client. Ensure you replace placeholder values with your actual credentials. The client is used within a context manager for proper resource handling. ```python import random from zscaler.oneapi_client import LegacyZIAClient config = { "username": '{yourUsername}', "password": '{yourPassword}', "api_key": '{yourApiKey}', "cloud": '{yourCloud}', "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZIAClient(config) as client: added_label, response, error = client.zia.rule_labels.add_label( name=f"NewLabel_{random.randint(1000, 10000)}", description=f"NewLabel_{random.randint(1000, 10000)}", ) if err: print(f"Error adding label: {err}") return print(f"Label added successfully: {added_label.as_dict()}") if __name__ == "__main__": main() ``` -------------------------------- ### Initialize LegacyZWAClient for ZWA Authentication Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/index.md Demonstrates how to initialize the LegacyZWAClient with ZWA credentials (key_id, key_secret, cloud) and use it to fetch DLP incident transactions. Ensure you provide valid credentials or configure environment variables. ```python import random from zscaler.oneapi_client import LegacyZWAClient config = { "key_id": '{yourKeyId}', "key_secret": '{yourKeySecret}', "cloud": '{yourCloud}', "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZWAClient(config) as client: transactions, _, err = client.zwa.dlp_incidents.get_incident_transactions('SVDP-17410643229970491392') if err: print(f"Error listing transactions: {err}") return for incident in transactions: print(incident.as_dict()) if __name__ == "__main__": main() ``` -------------------------------- ### Initialize ZTW Legacy Client Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/index.md Initializes the ZTW Legacy Client with configuration details. Use this for ZTW provisioning URL operations. ```python import random from zscaler.oneapi_client import LegacyZTWClient config = { "username": '{yourUsername}', "password": '{yourPassword}', "api_key": '{yourApiKey}', "cloud": '{yourCloud}', "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZTWClient(config) as client: fetched_prov_url, response, error = client.ztw.provisioning_url.list_provisioning_url() if error: print(f"Error fetching prov url by ID: {error}") return print(f"Fetched prov url by ID: {fetched_prov_url.as_dict()}") if __name__ == "__main__": main() ``` -------------------------------- ### Get IP GRE Tunnel Information Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zia/gre_tunnel.md Retrieves information for IP addresses with GRE tunnel details. Use this to get a list of tunnels. ```python tunnels_list, _, err = client.zia.gre_tunnel.get_ip_gre_tunnel_info() if err: print(f”Error listing tunnels: {err}”) return for tunnel in tunnels_list: print(tunnel.as_dict()) ``` -------------------------------- ### Run Shadow IT Example Script Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zins/shadow_it/README.md Execute the Python script that utilizes the Zscaler SDK to query Shadow IT discovered applications and dashboard summaries. ```bash # Run the example python shadow_it_example.py ``` -------------------------------- ### List All Configured Departments Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zdx/admin.md Prints all configured departments. Ensure the client object is initialized. ```python dept_list, _, err = client.zdx.admin.list_departments() if err: print(f"Error listing department: {err}") return print(f"Total department found: {len(dept_list)}") for dept in dept_list: print(dept.as_dict()) ``` -------------------------------- ### Quick ZPA Client Initialization Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.rst Initializes the ZPA client helper with client ID, client secret, customer ID, and cloud information. Use this for quick integration with ZPA services. ```python from zscaler import ZPAClientHelper from pprint import pprint zpa = ZPAClientHelper(client_id='ZPA_CLIENT_ID', client_secret='ZPA_CLIENT_SECRET', customer_id='ZPA_CUSTOMER_ID', cloud='ZPA_CLOUD') for app_segment in zpa.app_segments.list_segments(): pprint(app_segment) ``` -------------------------------- ### List App Connector Provisioning Keys Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/zs/zpa/provisioning.html Iterates through and prints all configured App Connector provisioning keys. ```python for key in zpa.provisioning.list_provisioning_keys(key_type="connector"): print(key) ``` -------------------------------- ### Get Malware Settings Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zia/malware_protection_policy.md Retrieves the general malware protection policy configuration details. Use this to get a comprehensive overview of malware protection settings. ```python settings, _, err = client.zia.malware_protection_policy.get_malware_settings() if err: print(f"Error fetching malware settings: {err}") return print("Current malware settings fetched successfully.") print(settings) ``` -------------------------------- ### Basic Pagination Example Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Demonstrates how to retrieve paginated results using the SDK's `has_next()` and `next()` methods. It fetches groups with a page size of 100 and extends the results list until all pages are retrieved or an error occurs. ```python query_parameters = {'page_size': 100} groups, resp, err = client.zia.user_management.list_groups(query_parameters) while resp.has_next(): more_groups, resp, err = resp.next() # Unpack all 3 return values if err: break if more_groups: groups.extend(more_groups) ``` -------------------------------- ### Initialize Legacy ZCC Client and List Devices Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Shows how to initialize the LegacyZCCClient with API key, secret key, and cloud configuration to list devices. This client is used for ZCC legacy authentication. ```python import random from zscaler.oneapi_client import LegacyZCCClient config = { "api_key": '{yourApiKey}', "secret_key": '{yourSecreKey}', "cloud": '{yourCloud}', "logging": {"enabled": False, "verbose": False}, } with LegacyZCCClient(config) as client: for group in client.zcc.devices.list_devices(): print(group) if __name__ == "__main__": main() ``` -------------------------------- ### Get Agent Connection Status Statistics Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zms/agents.md Retrieve aggregated statistics for agent connection statuses. Use this to get an overview of agent connectivity for a given customer. ```python result, _, err = client.zms.agents.get_agent_connection_status_statistics( customer_id="123456789" ) if err: print(err) print(result.get("totalCount")) ``` -------------------------------- ### Get Cloud Sandbox Report (Full) Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/zs/zia/sandbox.html Retrieves a full report for a file analyzed by Cloud Sandbox. Specify 'full' for 'report_details' to get comprehensive analysis. ```python >>> zia.sandbox.get_report('8350dED6D39DF158E51D6CFBE36FB012', 'full') ``` -------------------------------- ### Example Legacy Client Execution Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/application/app_score/README.md This bash command shows how to execute the script using the legacy ZDX client. It requires the `--use-legacy-client` flag and will prompt for the same inputs as the OneAPI client. ```bash # Run with legacy client python zdx_app_score.py --use-legacy-client # Same interactive prompts as OneAPI client ``` -------------------------------- ### Initialize Legacy ZPA Client and Add Segment Group Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.md Demonstrates how to initialize the LegacyZPAClient with configuration details and add a new segment group. Ensure all required configuration parameters are provided. ```python import random from zscaler.oneapi_client import LegacyZPAClient config = { "clientId": '{yourClientId}', "clientSecret": '{yourClientSecret}', "customerId": '{yourCustomerId}', "microtenantId": '{yourMicrotenantId}', "partnerId": "", # Optional parameter. When provided, automatically includes x-partner-id header in all requests "cloud": '{yourCloud}', "logging": {"enabled": False, "verbose": False}, } def main(): with LegacyZPAClient(config) as client: added_label, response, error = client.zpa.segment_groups.add_group( name=f"NewGroup_{random.randint(1000, 10000)}", description=f"NewGroup_{random.randint(1000, 10000)}", enabled=True ) if err: print(f"Error adding segment group: {err}") return print(f"Segment Group added successfully: {added_label.as_dict()}") if __name__ == "__main__": main() ``` -------------------------------- ### Get App Information Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/zs/zia/apptotal.html Retrieves information about an application from the AppTotal App Catalog. If the app is not found, it is submitted for analysis. A subsequent GET request is needed after analysis is complete. ```APIDOC ## get_app ### Description Searches the AppTotal App Catalog by app ID. If the app exists in the catalog, the app’s information is returned. If not, the app is submitted for analysis. After analysis is complete, a subsequent GET request is required to fetch the app’s information. ### Method `zia.apptotal.get_app(app_id, verbose=False)` ### Parameters #### Path Parameters - **app_id** (str) - Required - The app ID to search for. - **verbose** (bool) - Optional - Defaults to False. If True, returns verbose information. ### Request Example ```python zia.apptotal.get_app(app_id="12345", verbose=True) ``` ### Response #### Success Response (200) - **response** (Box) - The response object containing app information or analysis status. ``` -------------------------------- ### List Application Servers with Filtering Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zpa/servers.md Enumerates application servers with support for filtering by search terms, page number, and page size. The example demonstrates how to retrieve a paginated list and print server details. ```python >>> server_list, _, err = client.zpa.servers.list_servers( ... query_params={'search': 'Server01', 'page': '1', 'page_size': '100'}) ... if err: ... print(f"Error listing application servers: {err}") ... return ... print(f"Total application servers found: {len(server_list)}") ... for server in server_list: ... print(server.as_dict()) ``` -------------------------------- ### Update Timeout Rule Conditions Example Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zpa/policies.md Provides an example of the conditions format for updating a Timeout Policy rule using `update_timeout_rule_v2`. Note the structure for app and app_group conditions. ```python [("app", ["72058304855116918"]), ("app_group", ["72058304855114308"]) ("client_type", ["zpn_client_type_exporter", "zpn_client_type_zapp", "zpn_client_type_browser_isolation", "zpn_client_type_zapp_partner"]), ``` -------------------------------- ### Get PAC File by ID without Content Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zia/pac_files.md Fetches a specific PAC file by its ID, excluding its content. Use this to get metadata without the full PAC file. ```python >>> pac_files, _, error = client.zia.pac_files.get_pac_file('18805', query_params={'filter': 'pac_content'}) >>> if error: ... print(f"Error fetching PAC files by ID: {error}") ... return ... print(f"Total PAC file versions fetched: {len(pac_files)}") ... for version in pac_files: ... print(version.as_dict()) ``` -------------------------------- ### Quick ZIA Client Initialization Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/README.rst Initializes the ZIA client helper with username, password, API key, and cloud information. Use this for quick integration with ZIA services. ```python from zscaler import ZIAClientHelper from pprint import pprint zia = ZIAClientHelper(username='ZIA_USERNAME', password='ZIA_PASSWORD', api_key='ZIA_API_KEY', cloud='ZIA_CLOUD') for user in zia.users.list_users(): pprint(user) ``` -------------------------------- ### Get Count of Cloud-to-Cloud Incident Receivers Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zia/cloud_to_cloud_ir.md Retrieves the total number of Cloud-to-Cloud DLP Incident Receivers configured for your organization. This can be used to get a quick overview of existing configurations. ```python >>> count, _, error = client.zia.cloud_to_cloud_ir.list_c2c_count() >>> if error: ... print(f"Error fetching c2c receivers count: {error}") ... return ... print(f"Total c2c receivers found: {count}") ``` -------------------------------- ### Start ZDX Score Analysis Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zdx/troubleshooting.md Starts a ZDX Score analysis on a device for a specific application. Requires device ID, application ID, and time range (t0, t1). ```python start_analysis, response, error = client.zdx.troubleshooting.start_analysis( device_id='132559212', app_id='1', ) if error: print(f"Error starting analysis: {error}") return print(f"Analysis Started successfully: {start_analysis.as_dict()}") ``` -------------------------------- ### List Service Edge Provisioning Keys Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docs/zs/zpa/provisioning.html Iterates through and prints all configured Service Edge provisioning keys. ```python for key in zpa.provisioning.list_provisioning_keys(key_type="service_edge"): print(key) ``` -------------------------------- ### Running Unit Tests with Coverage Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/tests/unit/README.md Illustrates how to run the unit tests and generate a code coverage report using the `--coverage` flag. This helps identify which lines of code are not being executed by the tests. ```bash python tests/unit/run_rate_limiting_tests.py --coverage ``` -------------------------------- ### List All Application Servers Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zpa/application_server/README.md Use this command to list all application servers configured in ZPA. Ensure you have set up authentication via environment variables. ```shell python3 application_server_management.py -l ``` -------------------------------- ### Get End User Notification Settings Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zia/end_user_notification.md Retrieves the current End User Notification settings configured in the ZIA Admin Portal. This method makes a GET request to the ZIA Admin API. ```python settings, response, err = client.zia.end_user_notification.get_eun_settings() if not err: print(f"Notification Type: {settings['notification_type']}") print(f"Support Email: {settings['support_email']}") ``` -------------------------------- ### Add a New Client Setting Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/zpa/client_settings.md Use this method to create a new client setting. Ensure you provide the required name, enrollment certificate ID, and client certificate type. ```python added_client_setting, _, err = client.zpa.client_settings.add_client_setting( name='NewClientSetting', enrollment_cert_id='245675', client_certificate_type='ZAPP_CLIENT' ) ``` -------------------------------- ### Example OneAPI Client Execution Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/examples/zdx/application/app_score/README.md This bash command demonstrates running the script with the default OneAPI client. The script will then prompt for application and optional filtering details. ```bash # Run with OneAPI client (default) python zdx_app_score.py # The script will prompt for: # 1. Application ID # 2. Hours to look back (optional) # 3. Location ID (optional) # 4. Department ID (optional) # 5. Geolocation ID (optional) ``` -------------------------------- ### get_md5 Source: https://github.com/zscaler/zscaler-sdk-python/blob/master/docsrc/zs/ztb/site.md Get the Gateway MD5 hash. ```APIDOC ## get_md5 ### Description Get Gateway MD5. ### Method GET ### Endpoint /api/v2/Site/md5 ### Response #### Success Response (200) - **result string** (str) - The MD5 hash string. - **Response** (object) - The raw response object. - **error** (object) - Any error encountered during the request. ### Return Type tuple ```