Created
August 11, 2025 17:33
-
-
Save ntwrkguru/2acf93202e81fbd91630839633dc00d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Simple utility to generate an API key from a username/password | |
| for a Panos device. | |
| This module provides a class to generate and manage API keys for | |
| Palo Alto Networks devices using username and password. | |
| Dependencies: | |
| - requests | |
| - xmltodict | |
| - urllib3 | |
| Returns: | |
| api_key (str): The generated API key. | |
| """ | |
| import sys | |
| import logging | |
| import requests | |
| import xmltodict | |
| from urllib3 import exceptions, disable_warnings | |
| disable_warnings(exceptions.InsecureRequestWarning) | |
| # Configure logger | |
| logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler(sys.stdout)]) | |
| logger = logging.getLogger(__name__) | |
| class ApiKey: | |
| """ | |
| Generates an API key for a Palo Alto Networks device. | |
| Attributes: | |
| hostname (str): The hostname or IP address of the device. | |
| user (str): The username for authentication. | |
| password (str): The password for authentication. | |
| api_key (str): The generated API key. | |
| """ | |
| def __init__(self, hostname: str, user: str, password: str): | |
| self.hostname = hostname | |
| self.user = user | |
| self.password = password | |
| self.api_key = self.get_key() | |
| def get_key(self) -> str: | |
| """ | |
| Generates a Panos API key. | |
| Sends a request to the device to generate an API key using | |
| the provided username and password. | |
| Returns: | |
| str: The API key. | |
| Raises: | |
| Exception: If the API key generation fails. | |
| """ | |
| endpoint = f"https://{self.hostname}/api" | |
| params = { | |
| 'type': 'keygen', | |
| 'user': self.user, | |
| 'password': self.password | |
| } | |
| logger.info("Attempting to obtain an API key for %s", self.hostname) | |
| try: | |
| response = requests.get(endpoint, params=params, verify=False, timeout=60) | |
| response.raise_for_status() | |
| key = xmltodict.parse(response.text)['response']['result'].get('key') | |
| if key: | |
| logger.info("API key generated successfully") | |
| return key | |
| else: | |
| logger.error("Unable to obtain API Key for %s", self.hostname) | |
| exit(1) | |
| except requests.exceptions.RequestException as e: | |
| logger.error("Request failed: %s", e) | |
| exit(1) | |
| def print_key(self) -> None: | |
| """ | |
| Prints the derived API key. | |
| """ | |
| logger.info("API key: %s", self.api_key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment