4.2. Connection Handler

Easy all-in-one connection handler.

class axonius_api_client.connect.Connect(url, key, secret, log_console=False, log_file=False, log_file_rotate=False, certpath=None, certverify=False, certwarn=True, proxy=None, headers=None, cookies=None, credentials=False, timeout_connect=5, timeout_response=900, cert_client_key=None, cert_client_cert=None, cert_client_both=None, save_history=False, log_level='debug', log_request_attrs=None, log_response_attrs=None, log_request_body=False, log_response_body=False, log_logger=<Logger axonius_api_client (DEBUG)>, log_level_package='debug', log_level_endpoints='info', log_level_http='debug', log_level_auth='debug', log_level_api='debug', log_level_console='debug', log_level_file='debug', log_console_fmt='%(levelname)-8s [%(name)s] %(message)s', log_http_max=False, log_file_fmt='%(asctime)s %(levelname)-8s [%(name)s:%(module)s:%(funcName)s:%(pathname)s:%(lineno)d] %(message)s', log_file_name='axonius_api_client.log', log_file_path='/home/docs/checkouts/readthedocs.org/user_builds/axonius-api-client/checkouts/latest/docs', log_file_max_mb=5, log_file_max_files=5, log_hide_secrets=True, log_body_lines=100, wraperror=True, cf_token=None, cf_url=None, cf_path='cloudflared', cf_run=False, cf_run_login=True, cf_run_access=True, cf_env=False, cf_echo=True, cf_echo_verbose=False, cf_error=False, cf_error_login=True, cf_error_access=True, cf_timeout_access=60, cf_timeout_login=180, http=None, auth=None, auth_null=None, **kwargs)[source]

Bases: object

Easy all-in-one connection handler for using the API client.

Examples

>>> #!/usr/bin/env python
>>> # -*- coding: utf-8 -*-
>>> '''Base example for setting up the API client.'''
>>> import axonius_api_client as axonapi
>>>
>>> # get the URL, API key, API secret, & certwarn from the default ".env" file
>>> client_args = axonapi.get_env_connect()
>>>
>>> # OR override OS env vars with the values from a custom .env file
>>> # client_args = axonapi.get_env_connect(ax_env="/path/to/envfile", override=True)
>>>
>>> # create a client using the url, key, and secret from OS env
>>> client = axonapi.Connect(**client_args)
>>>
>>> j = client.jdump  # json dump helper
>>>
>>> client.start()  # connect to axonius
>>>
>>> # client.activity_logs                 # get audit logs
>>> # client.adapters                      # get adapters and update adapter settings
>>> # client.adapters.cnx                  # CRUD for adapter connections
>>> # client.dashboard                     # get/start/stop discovery cycles
>>> # client.dashboard_spaces              # CRUD for dashboard spaces
>>> # client.data_scopes                   # CRUD for data scopes
>>> # client.devices                       # get device assets
>>> # client.devices.fields                # get field schemas for device assets
>>> # client.devices.labels                # add/remove/get tags for device assets
>>> # client.devices.saved_queries         # CRUD for saved queries for device assets
>>> # client.enforcements                  # CRUD for enforcements
>>> # client.folders                       # CRUD for folders
>>> # client.folders.enforcements          # CRUD for enforcements folders
>>> # client.folders.queries               # CRUD for queries folders
>>> # client.instances                     # get instances and instance meta data
>>> # client.openapi                       # get openapi spec
>>> # client.meta                          # get product meta data
>>> # client.remote_support                # include_output/disable remote support settings
>>> # client.settings_global               # get/update global system settings
>>> # client.settings_gui                  # get/update gui system settings
>>> # client.settings_ip                   # get/update identity provider system settings
>>> # client.settings_lifecycle            # get/update lifecycle system settings
>>> # client.signup                        # initial signup, password resets
>>> # client.system_roles                  # CRUD for system roles
>>> # client.system_users                  # CRUD for system users
>>> # client.users                         # get user assets
>>> # client.users.fields                  # get field schemas for user assets
>>> # client.users.labels                  # add/remove/get tags for user assets
>>> # client.users.saved_queries           # CRUD for saved queries for user assets
>>> # client.vulnerabilities               # get vulnerability assets
>>> # client.vulnerabilities.fields        # get field schemas for vulnerability assets
>>> # client.vulnerabilities.labels        # add/remove/get tags for vulnerability assets
>>> # client.vulnerabilities.saved_queries # CRUD for saved queries for vulnerability assets
Parameters
TOOLS: types.ModuleType = <module 'axonius_api_client.tools' from '/home/docs/checkouts/readthedocs.org/user_builds/axonius-api-client/envs/latest/lib/python3.7/site-packages/axonius_api_client/tools.py'>

Tools module.

STARTED: bool = False

Flag to indicate if client has been started.

WRAPERROR: bool = True

Flag to indicate if client should wrap exceptions.

ARGS_API: dict = {}

Arguments to use when setting up models.

HANDLER_CON: typing.Optional[logging.StreamHandler] = None

Console logging handler.

HANDLER_FILE: typing.Optional[logging.handlers.RotatingFileHandler] = None

File logging handler.

API_ATTRS: typing.List[str] = ['activity_logs', 'adapters', 'dashboard', 'dashboard_spaces', 'data_scopes', 'devices', 'enforcements', 'folders', 'instances', 'meta', 'openapi', 'remote_support', 'settings_global', 'settings_gui', 'settings_ip', 'settings_lifecycle', 'signup', 'system_roles', 'system_users', 'users', 'vulnerabilities']

Attributes that are API Models.

API_LOG_LEVEL: typing.Union[int, str] = 'debug'

Log level for API Models.

REASON_RES: typing.List[typing.Pattern] = [re.compile('.*?object at.*?>: ([a-zA-Z0-9\\]\\[: ]+)'), re.compile('.*?] (.*) ')]

Patterns to look for in exceptions that we can pretty up for user display.

PKG_VERSION: str = '5.0.6'

Version of this package.

PY_VERSION: str = '3.7.9'

Version of Python that this package is running on.

ABOUT_CACHE: typing.Optional[dict] = None

Cached data from the /about endpoint.

HTTP_MAX: str = 'log_request_body = True\nlog_response_body = True\nlog_level_http = "debug"\nlog_level_package = "debug"\nlog_level_console = "debug"\nlog_level_file = "debug"\nlog_request_attrs = "all"\nlog_response_attrs = "all"\nlog_body_lines = 10000\n'

Override values used when log_http_max is True.

HTTP_MAX_CLI: str = 'log_request_body = True, log_response_body = True, log_level_http = "debug", log_level_package = "debug", log_level_console = "debug", log_level_file = "debug", log_request_attrs = "all", log_response_attrs = "all", log_body_lines = 10000'

CLI Help string for log_http_max.

__init__(url, key, secret, log_console=False, log_file=False, log_file_rotate=False, certpath=None, certverify=False, certwarn=True, proxy=None, headers=None, cookies=None, credentials=False, timeout_connect=5, timeout_response=900, cert_client_key=None, cert_client_cert=None, cert_client_both=None, save_history=False, log_level='debug', log_request_attrs=None, log_response_attrs=None, log_request_body=False, log_response_body=False, log_logger=<Logger axonius_api_client (DEBUG)>, log_level_package='debug', log_level_endpoints='info', log_level_http='debug', log_level_auth='debug', log_level_api='debug', log_level_console='debug', log_level_file='debug', log_console_fmt='%(levelname)-8s [%(name)s] %(message)s', log_http_max=False, log_file_fmt='%(asctime)s %(levelname)-8s [%(name)s:%(module)s:%(funcName)s:%(pathname)s:%(lineno)d] %(message)s', log_file_name='axonius_api_client.log', log_file_path='/home/docs/checkouts/readthedocs.org/user_builds/axonius-api-client/checkouts/latest/docs', log_file_max_mb=5, log_file_max_files=5, log_hide_secrets=True, log_body_lines=100, wraperror=True, cf_token=None, cf_url=None, cf_path='cloudflared', cf_run=False, cf_run_login=True, cf_run_access=True, cf_env=False, cf_echo=True, cf_echo_verbose=False, cf_error=False, cf_error_login=True, cf_error_access=True, cf_timeout_access=60, cf_timeout_login=180, http=None, auth=None, auth_null=None, **kwargs)[source]

Easy all-in-one connection handler.

Parameters
  • url (str) – URL, hostname, or IP address of Axonius instance

  • key (str) – API Key from account page in Axonius instance

  • secret (str) – API Secret from account page in Axonius instance

  • log_console (bool) – include_output logging to console

  • log_file (bool) – include_output logging to file

  • certpath (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – path to CA bundle file to use when verifying certs offered by url

  • certverify (bool) – raise exception if cert is self-signed or only if cert is invalid

  • certwarn (bool) – show insecure warning once or never show insecure warning

  • proxy (typing.Optional[str]) – proxy to use when making https requests to url

  • headers (typing.Union[dict, requests.structures.CaseInsensitiveDict, None]) – additional headers to supply with every request

  • cookies (typing.Union[dict, requests.cookies.RequestsCookieJar, None]) – additional cookies to supply with every request

  • credentials (bool) – treat key as username as secret as password

  • timeout_connect (typing.Union[int, float, None]) – seconds to wait for connections to open to url

  • timeout_response (typing.Union[int, float, None]) – seconds to wait for responses from url

  • cert_client_key (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – file with private key to offer to url

  • cert_client_cert (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – file with client cert to offer to url

  • cert_client_both (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – file with client cert and private key to offer to url

  • save_history (bool) – save history of responses to Http.HISTORY

  • log_level (typing.Union[str, int]) – log level to use for this object

  • log_request_attrs (typing.Union[str, typing.Iterable[str], None]) – list of request attributes to log

  • log_response_attrs (typing.Union[str, typing.Iterable[str], None]) – list of response attributes to log

  • log_request_body (bool) – log request body

  • log_response_body (bool) – log response body

  • log_logger (logging.Logger) – Logger for the entire package, where console and file output handlers will be attached to

  • log_level_package (typing.Union[str, int]) – log level to use for package root logger

  • log_level_endpoints (typing.Union[str, int]) – log level to use for endpoint loggers

  • log_level_http (typing.Union[str, int]) – log level to use for http loggers

  • log_level_auth (typing.Union[str, int]) – log level to use for auth loggers

  • log_level_api (typing.Union[str, int]) – log level to use for api loggers

  • log_level_console (typing.Union[str, int]) – log level to use for console loggers

  • log_level_file (typing.Union[str, int]) – log level to use for file loggers

  • log_console_fmt (str) – format string to use for console logging

  • log_file_fmt (str) – format string to use for file logging

  • log_file_name (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – name of file to log to

  • log_file_path (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – path to directory to log to

  • log_file_max_mb (int) – max size of log file in MB

  • log_file_max_files (int) – max number of log files to keep

  • log_file_rotate (bool) – rotate log file on startup

  • log_body_lines (int) – max length of request/response body to log

  • log_hide_secrets (bool) – hide secrets in logs

  • log_http_max (bool) – Shortcut to include_output ALL http logging warning: heavy log output

  • wraperror (bool) – wrap certain errors in a more user friendly format

  • cf_url (typing.Optional[str]) – URL to use in access token and access login commands, will fallback to url if not supplied

  • cf_token (typing.Optional[str]) – access token supplied by user, will be checked for validity if not empty

  • cf_env (bool) – if no token supplied, try to get token from OS env var CF_TOKEN

  • cf_run (bool) – if no token supplied or in OS env vars, try to get token from access token and access login commands

  • cf_run_access (bool) – if run is True, try to get token from access token,

  • cf_run_login (bool) – if run is True and no token returned from access token command, try to get token from access login command

  • cf_path (typing.Optional[typing.TypeVar(PathLike, pathlib.Path, str, bytes)]) – path to cloudflared binary to run, can be full path or path in OS env var $PATH

  • cf_timeout_access (typing.Optional[int]) – timeout for access token command in seconds

  • cf_timeout_login (typing.Optional[int]) – timeout for access login command in seconds

  • cf_error (bool) – raise error if an invalid token is found or no token can be found

  • cf_error_access (bool) – raise exc if access token command fails and login is False

  • cf_error_login (bool) – raise exc if access login command fails

  • cf_echo (bool) – echo commands and results to stderr

  • cf_echo_verbose (bool) – echo more to stderr

  • http (typing.Optional[axonius_api_client.http.Http]) – http object to use for this connection

  • auth (typing.Optional[axonius_api_client.auth.model.AuthModel]) – auth model to use for this connection

  • auth_null (typing.Optional[axonius_api_client.auth.model.AuthModel]) – null auth model to use for this connection

  • **kwargs (typing.Dict[str, typing.Any]) – unused

API_CACHE: typing.Dict[typing.Type[axonius_api_client.api.mixins.ModelMixins], axonius_api_client.api.mixins.ModelMixins] = None

Cache for API Models.

ARGS_ORIG: dict = {}

Original arguments supplied to the constructor.

LOG_LOGGER: logging.Logger = <Logger axonius_api_client (DEBUG)>

Logger for the entire package, where console and file output handlers will be attached to.

LOG: typing.Optional[logging.Logger] = None

Logger for this class.

LOG_HTTP_MAX: bool = False

very heavy log output*.

Type

Shortcut to include_output ALL http logging *warning

CREDENTIALS: bool = False

Flag to indicate if key & secret are actually username & password.

ARGS_HANDLER_CON: dict = {}

Arguments to use when setting up console logging.

ARGS_HANDLER_FILE: dict = {}

Arguments to use when setting up file logging.

HTTP: axonius_api_client.http.Http = None

HTTP client.

http: axonius_api_client.http.Http = None
AUTH: axonius_api_client.auth.model.AuthModel = None

Authentication handler.

auth: axonius_api_client.auth.model.AuthModel = None
AUTH_NULL: axonius_api_client.auth.model.AuthModel = None

Auth model for authenticating with no auth.

start()[source]

Connect to and authenticate with Axonius.

Return type

None

property activity_logs: ActivityLogs

Work with activity logs.

property adapters: Adapters

Work with adapters and adapter connections.

property dashboard: Dashboard

Work with discovery cycles.

property dashboard_spaces: DashboardSpaces

Work with dashboard spaces.

property data_scopes: DataScopes

Work with data scopes.

property devices: Devices

Work with device assets.

property enforcements: Enforcements

Work with Enforcement Center.

property folders: Folders

Work with folders for enforcements and queries.

property instances: Instances

Work with instances.

property openapi: OpenAPISpec

Work with the OpenAPI specification file.

property meta: Meta

Work with instance metadata.

property remote_support: RemoteSupport

Work with configuring remote support.

property settings_global: SettingsGlobal

Work with core system settings.

property settings_gui: SettingsGui

Work with gui system settings.

property settings_ip: SettingsIdentityProviders

Work with identity providers settings.

property settings_lifecycle: SettingsLifecycle

Work with lifecycle system settings.

property signup: Signup

Perform initial signup, password reset, and other unauthenticated endpoints.

property system_users: SystemUsers

Work with system users.

property system_roles: SystemRoles

Work with system roles.

property users: Users

Work with user assets.

property vulnerabilities: Vulnerabilities

Work with vulnerability assets.

set_wraperror(value=True)[source]

Set whether to wrap errors in a more user-friendly format.

Parameters

value (bool) –

Return type

None

static set_log_hide_secrets(value=True)[source]

Set whether to hide secrets in logs.

Parameters

value (bool) –

Return type

None

set_log_level_console(value='debug')[source]

Set the log level for this client’s console output.

Parameters

value (typing.Union[str, int]) –

Return type

None

set_log_level_file(value='debug')[source]

Set the log level for this client’s file output.

Parameters

value (typing.Union[str, int]) –

Return type

None

set_log_level_api(value='debug')[source]

Set the log level for this client’s api objects.

Parameters

value (typing.Union[str, int]) –

Return type

None

set_log_level_connect(value='debug')[source]

Set the log level for this client.

Parameters

value (typing.Union[str, int]) –

Return type

None

set_log_level_http(value='debug')[source]

Set the log level for this client’s http object.

Parameters

value (typing.Union[str, int]) –

Return type

None

set_log_level_auth(value='debug')[source]

Set the log level for this client’s auth objects.

Parameters

value (typing.Union[str, int]) –

Return type

None

set_log_level_package(value='debug')[source]

Set the log level for this client’s package.

Parameters

value (typing.Union[str, int]) –

Return type

None

static set_log_level_endpoints(value='info')[source]

Set the log level for this client’s endpoints.

Parameters

value (typing.Union[str, int]) –

Return type

None

control_log_console(enable=False)[source]

Add logging to console for this client.

Parameters

enable (bool) –

Return type

bool

control_log_file(enable=False, rotate=False)[source]

Add logging to file for this client.

Parameters
Return type

bool

rotate_log_files(value=False)[source]

Rollover log file.

Parameters

value (bool) –

Return type

None

property url: str

Get the URL of the current instance.

property api_keys: dict

Get the API keys for the current user.

property current_user: Optional[CurrentUser]

Get the current user (returns 404 for service accounts).

property about: dict

Cached data from the /about endpoint.

property version: str

Get the Axonius instance version.

property build_date: str

Get the Axonius instance build date.

property str_ax_version: str

Get the Axonius instance version & build date for use in str.

property str_ax_user: str

Get the Axonius instance user for use in str.

property ssl_days_left: Optional[int]

Get the number of days left until the SSL certificate expires.

property str_ax_cert: str

Get the Axonius instance SSL certificate for use in str.

property str_state: str

Get the connection state for use in str.

static jdump(obj, **kwargs)[source]

Print object as JSON.

Parameters

obj (typing.Any) –

Return type

None

__str__()[source]

Show object info.

Return type

str

__repr__()[source]

Show object info.

Return type

str

classmethod _get_exc_reason(exc)[source]

Trim exceptions down to a more user-friendly display.

Uses REASON_RES to do regex substitutions.

Parameters

exc (Exception) –

Return type

str

_check_binding(value)[source]

Check if an object is already bound to a different client.

Parameters

value (typing.Any) –

Return type

typing.Any

_init_http(http=None)[source]

Initialize the HTTP object.

Parameters

http (typing.Optional[axonius_api_client.http.Http]) –

Return type

axonius_api_client.http.Http

_init_auth(auth=None, log_level='debug')[source]

Initialize the Auth object.

Parameters
Return type

axonius_api_client.auth.model.AuthModel

_init_auth_null(auth_null=None, log_level='debug')[source]

Initialize the null Auth object.

Parameters
Return type

axonius_api_client.auth.model.AuthModel

_init()[source]

Custom init for this class.

_get_model(model, start=True, auth=None)[source]

Create or get an API model.

Parameters
Return type

typing.Any

Returns

model instance