Python API Client for OpenCTI
pycti is the official Python API client for the OpenCTI platform, a free and open-source platform for threat intelligence. It provides an interface to interact with OpenCTI's GraphQL API, enabling users to programmatically manage and query cyber threat intelligence data. The library's versioning (e.g., 7.YYYYMMDD.P) closely mirrors the OpenCTI platform's releases, indicating a rapid development and release cadence.
Warnings
- breaking Major version updates of the OpenCTI platform (e.g., from v6 to v7) often involve significant changes to the underlying GraphQL API schema. Using a `pycti` client version intended for an older or newer platform version can lead to `KeyError`s or `AttributeError`s due to API method or data structure mismatches.
- gotcha The versioning scheme for `pycti` (e.g., 7.260409.0) is tied directly to the OpenCTI platform's version and release date (YYMMDD), rather than typical semantic versioning for an independent library. This can be confusing when trying to understand compatibility or client-side breaking changes.
- gotcha When fetching large datasets, OpenCTI's GraphQL API is paginated. Failing to implement proper pagination logic (using `first` and `after` arguments) will result in retrieving only the first default set of results, potentially missing most of the data.
Install
-
pip install pycti
Imports
- OpenCTIClient
from pycti import OpenCTIClient
Quickstart
import os
from pycti import OpenCTIClient
# Initialize the OpenCTI client using environment variables
# Ensure OPENCTI_URL and OPENCTI_TOKEN environment variables are set
opencti_url = os.environ.get("OPENCTI_URL", "https://localhost:8080")
opencti_token = os.environ.get("OPENCTI_TOKEN", "YOUR_OPENCTI_TOKEN")
if not opencti_token or opencti_token == "YOUR_OPENCTI_TOKEN":
print("Error: OPENCTI_TOKEN environment variable or direct token is not set.")
print("Please set OPENCTI_URL and OPENCTI_TOKEN or pass them directly.")
exit(1)
try:
# Connect to the OpenCTI platform
# log_level can be 'debug', 'info', 'warning', 'error'
client = OpenCTIClient(opencti_url, opencti_token, log_level="info")
print(f"Successfully connected to OpenCTI at {opencti_url}")
# Example: Fetch the first 5 indicators
print("Fetching first 5 indicators...")
indicators = client.indicator.list(first=5)
if indicators:
print(f"Found {len(indicators)} indicators:")
for indicator in indicators:
print(f"- ID: {indicator.get('id')}, Pattern: {indicator.get('pattern')}")
else:
print("No indicators found or unable to fetch any.")
except Exception as e:
print(f"An error occurred: {e}")
print("Please ensure the OpenCTI platform is running, accessible, and authentication credentials are correct.")