Skip to main content
Version: v46

Automation with Python SDK

The Python Software Development Kit (SDK) is a RESTful client for programmatically using PrivX API.

You can use the PrivX Python SDK to automate tasks such as creating local users, managing roles, and retrieving connection metadata and audit trails. The SDK uses OAuth 2.0 to authenticate an API client to the PrivX REST API. The roles assigned to the API client determine which operations it can perform.

The SDK supports the functionalities available through PrivX REST API. Functionalities that require terminal access are not supported. Also, the SDK does not implement support for connection creation and playback. However, connection metadata and trails can be accessed through the SDK.

Installing Python SDK​

You can install the Python SDK directly from our GitHub repository. We recommend installing the SDK in a Python virtual environment. With the environment active, run:

pip install git+https://github.com/SSHcom/privx-sdk-for-python.git

Configuring API Client​

Create an API client and grant it the permissions required by your script. For the local user creation example below, the client needs the users-manage permission.

To configure the SDK with permissions for connecting to PrivX API:

  1. In the PrivX Web UI, go to Administration → Roles and click Add Role. Enter a name for the role, select the required permissions, and save the role.

  2. Go to Deployment → API Clients and click Add API Client. Assign the role you created to the API client and save the client.

  3. Copy the OAuth client ID and secret, the API client ID and secret, and the CA certificate from the API client details.

    3287

  4. Create a file named config.py for the examples below. Set HOSTNAME and HOSTPORT to the hostname and HTTPS port of your PrivX deployment. Replace the placeholders with the values from the API client details. For CA_CERT, paste the complete PEM certificate, including the BEGIN CERTIFICATE and END CERTIFICATE lines. For production scripts, load the credentials from environment variables or a secret file.

    HOSTNAME = "privx.example.com"
    HOSTPORT = 443

    OAUTH_CLIENT_ID = "privx-external"
    OAUTH_CLIENT_SECRET = "<oauth-client-secret>"

    API_CLIENT_ID = "<api-client-id>"
    API_CLIENT_SECRET = "<api-client-secret>"

    CA_CERT = """<complete-pem-certificate>"""

Checking Role Store Status​

Use api.get_role_store_status() to verify that your script can reach PrivX. This endpoint accepts unauthenticated requests and returns limited information before authentication.

  1. In the same directory as config.py, create a file named test_sdk.py:

    import json
    import config

    import privx_api

    api = privx_api.PrivXAPI(
    config.HOSTNAME,
    config.HOSTPORT,
    config.CA_CERT,
    config.OAUTH_CLIENT_ID,
    config.OAUTH_CLIENT_SECRET,
    )

    resp = api.get_role_store_status()

    print(resp.ok)
    print(json.dumps(resp.data, indent=3))
  2. Run the script. A successful request prints True, followed by get_role_store_status() details. If the service is running, the status field shows RUNNING. Example:

    True
    {
    "version": "99-0 (8aa5ade842f0a8d65d6f332b25d2d532cf72c8a6)",
    "api_version": "v1",
    "status": "RUNNING",
    "status_message": "OK",
    "app_id": "7ffcdea4-68c4-4bc4-4416-84f267627591",
    "server-mode": "",
    "start_time": "2021-07-27T11:36:59.614101032Z"
    }

Creating Local Users​

To create a local PrivX user, authenticate the API client before calling create_user().

The PrivXAPI class is the backbone of the SDK through which all interaction with PrivX are done. In the previous example we did not authenticate against PrivX before getting role-store service status. The service status endpoint does not require authentication and would output less information than usual.

Most interactions require authentication using api.authenticate. For example, when creating a PrivX local user:

  1. Add the following code to the end of test_sdk.py. It uses the api instance created above and prompts for the new user’s initial password.

    # skipping imports and initialization of PrivXAPI instance

    # authenticated as py-sdk-api client
    api.authenticate(config.API_CLIENT_ID, config.API_CLIENT_SECRET)

    # required data for user creation
    user = {
    "username": "test_user",
    "full_name": "TEST USER",
    "email": "test@user.com",
    "password": {"password": "1234567890"},
    "password_change_required": True,
    }

    # call the PrivX API endpoint in order to create a user
    resp = api.create_user(user)

    print(json.dumps(resp.data, indent=3))
  2. Run python test_sdk.py again and enter the initial password when prompted. If PrivX creates the user successfully, the response contains the new user’s ID:

    {
    "id": "f7568c03-d0e5-465d-44e7-92a159203f72"
    }
  3. In the PrivX Web UI, go to Administration → Users and verify that test_user was successfully added through Python SDK.

    3443

Additional Python SDK Examples​

For more SDK examples, including how to add roles (add-role.py), create secrets (create-secret.py), and import hosts (example-host-import-json.py), see the examples directory in the SDK repository.

Handling API Responses​

PrivX API mostly returns responses as JSON, however, Python SDK handles those responses a bit for convenience. There are two types of responses in the SDK: REST responses and Stream responses.

All Python SDK methods return an object of PrivXAPIResponse or PrivXStreamResponse, which has two properties ok type of bool and data type of Dict.

resp = api.create_user(user)

resp.ok // bool
resp.data // dict

Use response.ok to check whether an API request returned the expected HTTP status. How you read the response depends on whether the endpoint returns data or a file.

REST Responses​

REST responses are used for operations that do not return files.

For a REST response (PrivXAPIResponse), use response.data to read the result. If a request fails, check the response for error details.

For example, if you run the user creation script again with the same username, PrivX returns an error similar to the following:

response = api.create_user(user)

print(response.data)
"status": 400,
"details": {
"error_code": "BAD_REQUEST",
"details": [
{
"property": "username",
"error_code": "VALUE_DUPLICATE",
"error_message": "username exists"
\}
]
}
}

Stream Responses​

Stream response is used when PrivX returns a file.

For a file download (PrivXStreamResponse), use iter_content() to read the file in chunks. Accessing response.data on a stream response raises InternalAPIException.

For example, download_trail() returns a file-object response, which could be written to a file:

resp = api.download_trail(...)

with open("trail.txt", "w") as file:
for char in resp.iter_content(chunk_size):
file.write(char.decode("utf-8"))

Open the output file in binary mode to preserve the downloaded contents.

Error Handling​

All handled errors are currently represented with InternalAPIException:

from privx_api import InternalAPIException


resp = api.download_trail(...)
try:
parse_resp_data(resp.data)
except InternalAPIException:
logging.error("Response is file-based")
with open("trail.txt", "w") as file:
for char in resp.iter_content(chunk_size):
file.write(char.decode("utf-8"))