OsqueryClient¶
Client for the Kibana Security Osquery API.
Osquery lets you query hosts like a database using SQL. Kibana’s Osquery Manager integration runs queries on Elastic Agents and stores the results in Elasticsearch. The API manages three resource types: packs (named sets of queries scheduled on agent policies), saved queries (reusable single queries), and live queries (one-off queries dispatched to a selection of agents).
Osquery resources are space-aware: a pack or saved query created in one space
is not visible from another space. Every method accepts an optional
space_id to target a specific space.
- class kibana._sync.client.osquery.OsqueryClient(client, default_space_id=None, validate_spaces=True)[source]¶
Bases:
NamespaceClientClient for the Kibana Security Osquery API.
Run live queries against Elastic Agents with Osquery Manager, and manage reusable saved queries and scheduled query packs. The Osquery integration must be added to an agent policy for queries to actually execute on hosts.
The API manages three resource types:
Packs (
/api/osquery/packs): named sets of queries scheduled to run at an interval on the agent policies the pack is assigned to.Saved queries (
/api/osquery/saved_queries): reusable single queries that can be run as live queries or included in packs.Live queries (
/api/osquery/live_queries): one-off queries dispatched to a selection of agents, with per-action results.
All Osquery resources are space-aware: every method accepts an optional
space_idto target a specific space (Nonetargets the default space or the space the client is scoped to).Example
>>> from kibana import Kibana >>> client = Kibana("http://localhost:5601", api_key="...") >>> >>> # Create a pack with one scheduled query >>> pack = client.osquery.create_pack( ... name="my_pack", ... queries={ ... "uptime": {"query": "select * from uptime;", "interval": 3600} ... }, ... ) >>> pack_id = pack.body["data"]["saved_object_id"] >>> >>> # Run a live query on all agents and fetch its results >>> live = client.osquery.create_live_query( ... query="select * from uptime;", agent_all=True ... ) >>> action_id = live.body["data"]["action_id"] >>> details = client.osquery.get_live_query(id=action_id)
Managing Packs
A pack groups queries and schedules them on the agent policies it is assigned to:
from kibana import Kibana client = Kibana("http://localhost:5601", api_key="your_api_key") # Create a pack with one scheduled query pack = client.osquery.create_pack( name="my_pack", description="Track host uptime", enabled=False, queries={ "uptime": {"query": "select * from uptime;", "interval": 3600} }, ) pack_id = pack.body["data"]["saved_object_id"] # List, fetch, update and delete packs packs = client.osquery.find_packs(page=1, page_size=20) details = client.osquery.get_pack(id=pack_id) # Note: the server treats updates as replacements — send every # field you want to keep. client.osquery.update_pack( id=pack_id, name="my_pack", description="Track host uptime (updated)", enabled=False, queries={ "uptime": {"query": "select * from uptime;", "interval": 600} }, ) client.osquery.delete_pack(id=pack_id)
Managing Saved Queries
Saved queries are reusable SQL queries that can be run as live queries or added to packs:
saved = client.osquery.create_saved_query( id="my_saved_query", query="select * from uptime;", interval="60", # the server requires a string, not an integer description="Host uptime", ecs_mapping={"host.uptime": {"field": "total_seconds"}}, ) saved_object_id = saved.body["data"]["saved_object_id"] queries = client.osquery.find_saved_queries(page_size=100) details = client.osquery.get_saved_query(id=saved_object_id) # Updates are replacements too; `new_id` (the saved query name) # is always required by the server. client.osquery.update_saved_query( id=saved_object_id, new_id="my_saved_query", query="select * from uptime;", interval="120", ) client.osquery.delete_saved_query(id=saved_object_id)
Running Live Queries
Live queries are dispatched to agents immediately. They require at least one enrolled Elastic Agent running the Osquery Manager integration:
live = client.osquery.create_live_query( query="select * from uptime;", agent_all=True, ecs_mapping={"host.uptime": {"field": "total_seconds"}}, ) live_query_id = live.body["data"]["action_id"] action_id = live.body["data"]["queries"][0]["action_id"] # Check the status and fetch per-query results details = client.osquery.get_live_query(id=live_query_id) results = client.osquery.get_live_query_results( id=live_query_id, action_id=action_id, page_size=100 ) # List past live queries history = client.osquery.find_live_queries(kuery="user_id:elastic")
- __init__(client, default_space_id=None, validate_spaces=True)[source]¶
Initialize the OsqueryClient.
- Parameters:
Example
>>> osquery_client = OsqueryClient(kibana_client)
- create_pack(*, name, queries, description=None, enabled=None, policy_ids=None, shards=None, space_id=None, validate_spaces=None)[source]¶
Create a query pack.
Creates an Osquery pack: a named set of queries that are scheduled to run on the agent policies the pack is assigned to.
- Parameters:
name (str) – The pack name.
queries (dict[str, Any]) – An object of queries keyed by query ID. Each value may contain
query(the SQL to run),interval(seconds between runs),platform,version,ecs_mapping,snapshotandremoved. Kibana requiresqueryandintervalfor each entry.description (str | None) – The pack description.
enabled (bool | None) – Enables the pack. Enabled packs run on the agent policies listed in
policy_ids.policy_ids (list[str] | None) – A list of agent policy IDs to schedule the pack on.
shards (dict[str, Any] | None) – An object with shard configuration for policies included in the pack. For each policy, set the shard configuration to a percentage (1-100) of target hosts.
space_id (str | None) – Optional space ID to create the pack in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the created pack, includingsaved_object_id(use it for get/update/delete),name,queries,enabledand audit metadata.- Raises:
BadRequestError – If required fields are missing or invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> pack = client.osquery.create_pack( ... name="my_pack", ... description="Track uptime", ... enabled=False, ... queries={ ... "uptime": { ... "query": "select * from uptime;", ... "interval": 3600, ... } ... }, ... ) >>> print(pack.body["data"]["saved_object_id"])
- find_packs(*, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get a list of all query packs.
- Parameters:
page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to list packs from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse containing
page,per_page,totaland adatalist of packs. Live Kibana 9.4.3 returns flattened pack objects (name,queries,saved_object_id, …), not theid/attributeswrapper shown in the OpenAPI example.- Raises:
BadRequestError – If a query parameter is invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> packs = client.osquery.find_packs(page=1, page_size=10) >>> for pack in packs.body["data"]: ... print(pack["saved_object_id"], pack["name"])
- get_pack(*, id, space_id=None, validate_spaces=None)[source]¶
Get the details of a query pack using the pack ID.
- Parameters:
- Returns:
name,description,enabled,queries,policy_ids,read_onlyand audit metadata.- Return type:
ObjectApiResponse whose
dataobject contains the pack- Raises:
NotFoundError – If the pack does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
Example
>>> pack = client.osquery.get_pack( ... id="3c42c847-eb30-4452-80e0-728584042334" ... ) >>> print(pack.body["data"]["name"])
- update_pack(*, id, name=None, description=None, enabled=None, policy_ids=None, queries=None, shards=None, space_id=None, validate_spaces=None)[source]¶
Update a query pack using the pack ID.
You cannot update a prebuilt pack. Note that the live Kibana server treats this as a replacement update: optional fields omitted from the request (for example
description) may be reset to their defaults, so pass every field you want to keep.- Parameters:
id (str) – The ID of the pack you want to update (the pack’s saved object ID).
name (str | None) – The pack name.
description (str | None) – The pack description.
enabled (bool | None) – Enables the pack.
policy_ids (list[str] | None) – A list of agent policy IDs to schedule the pack on.
queries (dict[str, Any] | None) – An object of queries keyed by query ID (same shape as in
create_pack()).shards (dict[str, Any] | None) – An object with shard configuration for policies included in the pack. For each policy, set the shard configuration to a percentage (1-100) of target hosts.
space_id (str | None) – Optional space ID the pack lives in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the updated pack. Live Kibana 9.4.3 returns the flattened pack (as increate_pack()) whenenabledis included in the request, and the raw saved object (attributeswrapper) otherwise.- Raises:
BadRequestError – If the request body is invalid or the pack is prebuilt.
NotFoundError – If the pack does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> client.osquery.update_pack( ... id="3c42c847-eb30-4452-80e0-728584042334", ... name="updated_pack_name", ... description="Still tracking uptime", ... queries={ ... "uptime": { ... "query": "select * from uptime;", ... "interval": 3600, ... } ... }, ... )
- delete_pack(*, id, space_id=None, validate_spaces=None)[source]¶
Delete a query pack using the pack ID.
- Parameters:
- Returns:
ObjectApiResponse with an empty object body on success.
- Raises:
NotFoundError – If the pack does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> client.osquery.delete_pack( ... id="3c42c847-eb30-4452-80e0-728584042334" ... )
- create_saved_query(*, id, query, interval, description=None, ecs_mapping=None, platform=None, removed=None, snapshot=None, version=None, space_id=None, validate_spaces=None)[source]¶
Create a saved query.
Creates a reusable Osquery saved query that can be run as a live query or added to packs.
- Parameters:
id (str) – The saved query identifier (its name, for example
"my_saved_query"). This is distinct from the saved object ID generated by Kibana.query (str) – The SQL query you want to run.
interval (str) – An interval, in seconds, on which to run the query, as a string (for example
"60"). The live server rejects integer values.description (str | None) – The saved query description.
ecs_mapping (dict[str, Any] | None) – Map osquery results columns or static values to Elastic Common Schema (ECS) fields, for example
{"host.uptime": {"field": "total_seconds"}}.platform (str | None) – Restricts the query to a specified platform. The default is all platforms. To specify multiple platforms, use commas, for example
"linux,darwin".removed (bool | None) – Indicates whether the query is removed.
snapshot (bool | None) – Indicates whether the query is a snapshot.
version (str | None) – Uses the Osquery versions greater than or equal to the specified version string.
space_id (str | None) – Optional space ID to create the saved query in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the created saved query, includingsaved_object_id(use it for get/update/delete) and audit metadata.- Raises:
BadRequestError – If required fields are missing or invalid.
ConflictError – If a saved query with the same
idexists.AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> saved = client.osquery.create_saved_query( ... id="my_saved_query", ... query="select * from uptime;", ... interval="60", ... description="Host uptime", ... ecs_mapping={"host.uptime": {"field": "total_seconds"}}, ... ) >>> print(saved.body["data"]["saved_object_id"])
- find_saved_queries(*, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get a list of all saved queries.
- Parameters:
page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to list saved queries from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse containing
page,per_page,totaland adatalist of saved queries. Live Kibana 9.4.3 returns flattened objects whereidis the saved query name andsaved_object_idis the saved object ID, not theid/attributeswrapper shown in the OpenAPI example.- Raises:
BadRequestError – If a query parameter is invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> queries = client.osquery.find_saved_queries(page_size=100) >>> for saved in queries.body["data"]: ... print(saved["saved_object_id"], saved["id"])
- get_saved_query(*, id, space_id=None, validate_spaces=None)[source]¶
Get the details of a saved query using the query ID.
- Parameters:
- Returns:
ObjectApiResponse whose
dataobject contains the saved query attributes (id,query,interval,ecs_mapping,prebuilt, …) and audit metadata.- Raises:
NotFoundError – If the saved query does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> saved = client.osquery.get_saved_query( ... id="3c42c847-eb30-4452-80e0-728584042334" ... ) >>> print(saved.body["data"]["query"])
- update_saved_query(*, id, new_id, query=None, description=None, interval=None, ecs_mapping=None, platform=None, removed=None, snapshot=None, version=None, space_id=None, validate_spaces=None)[source]¶
Update a saved query using the query ID.
You cannot update a prebuilt saved query. Note that the live Kibana server treats this as a replacement update: optional fields omitted from the request (for example
intervalordescription) may be reset or removed, so pass every field you want to keep. Also note that whileintervalmust be sent as a string, the server stores and returns it as an integer after an update.- Parameters:
id (str) – The ID of the saved query you want to update (the saved query’s saved object ID).
new_id (str) – The saved query identifier to set (the body
idfield). Required by the server; pass the existing identifier to keep it unchanged, or a different one to rename the saved query.query (str | None) – The SQL query you want to run.
description (str | None) – The saved query description.
interval (str | None) – An interval, in seconds, on which to run the query, as a string (for example
"60").ecs_mapping (dict[str, Any] | None) – Map osquery results columns or static values to Elastic Common Schema (ECS) fields.
platform (str | None) – Restricts the query to a specified platform, for example
"linux,darwin".removed (bool | None) – Indicates whether the query is removed.
snapshot (bool | None) – Indicates whether the query is a snapshot.
version (str | None) – Uses the Osquery versions greater than or equal to the specified version string.
space_id (str | None) – Optional space ID the saved query lives in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the updated saved query.- Raises:
BadRequestError – If the request body is invalid or the saved query is prebuilt.
NotFoundError – If the saved query does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> client.osquery.update_saved_query( ... id="3c42c847-eb30-4452-80e0-728584042334", ... new_id="my_saved_query", ... query="select * from uptime;", ... interval="120", ... )
- delete_saved_query(*, id, space_id=None, validate_spaces=None)[source]¶
Delete a saved query using the query ID.
- Parameters:
- Returns:
ObjectApiResponse with an empty object body on success.
- Raises:
NotFoundError – If the saved query does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> client.osquery.delete_saved_query( ... id="3c42c847-eb30-4452-80e0-728584042334" ... )
- create_live_query(*, query=None, queries=None, saved_query_id=None, pack_id=None, agent_all=None, agent_ids=None, agent_platforms=None, agent_policy_ids=None, alert_ids=None, case_ids=None, event_ids=None, ecs_mapping=None, metadata=None, space_id=None, validate_spaces=None)[source]¶
Create and run a live query.
Dispatches an Osquery query (or a pack of queries) to a selection of agents. Specify what to run via
query,queries,saved_query_idorpack_id, and select agents viaagent_all,agent_ids,agent_platformsoragent_policy_ids.Note: on a stack where no Elastic Agent has ever enrolled, the live server responds with a 500
index_not_found_exception(missing.fleet-agentsindex) instead of accepting the query.- Parameters:
query (str | None) – The SQL query you want to run.
queries (list[dict[str, Any]] | None) – An array of queries to run. Each entry may contain
id,query,platform,version,ecs_mapping,snapshotandremoved.saved_query_id (str | None) – The ID of a saved query to run.
pack_id (str | None) – The ID of the pack you want to run.
agent_all (bool | None) – When True, the query runs on all agents.
agent_ids (list[str] | None) – A list of agent IDs to run the query on.
agent_platforms (list[str] | None) – A list of agent platforms to run the query on.
agent_policy_ids (list[str] | None) – A list of agent policy IDs to run the query on.
alert_ids (list[str] | None) – A list of alert IDs associated with the live query.
case_ids (list[str] | None) – A list of case IDs associated with the live query.
event_ids (list[str] | None) – A list of event IDs associated with the live query.
ecs_mapping (dict[str, Any] | None) – Map osquery results columns or static values to Elastic Common Schema (ECS) fields.
metadata (dict[str, Any] | None) – Custom metadata object associated with the live query.
space_id (str | None) – Optional space ID to run the live query in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the queued live query:action_id,agents,expirationand aquerieslist with a per-queryaction_id(use it withget_live_query_results()).- Raises:
BadRequestError – If the request body is invalid (e.g. no query and no pack specified).
ApiError – If the query cannot be dispatched (e.g. no agents have ever enrolled on the stack).
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> live = client.osquery.create_live_query( ... query="select * from uptime;", ... agent_all=True, ... ecs_mapping={"host.uptime": {"field": "total_seconds"}}, ... ) >>> print(live.body["data"]["action_id"])
- find_live_queries(*, kuery=None, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get a list of all live queries.
- Parameters:
kuery (str | None) – The kuery to filter the results by, for example
"agent.id: 16d7caf5-efd2-4212-9b62-73dafc91fa13".page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to list live queries from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the raw search response with anitemslist of live query actions.- Raises:
BadRequestError – If a query parameter is invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> live_queries = client.osquery.find_live_queries(page_size=10) >>> print(live_queries.body["data"]["total"])
- get_live_query(*, id, space_id=None, validate_spaces=None)[source]¶
Get the details of a live query using the query ID.
Note: on the live Kibana 9.4.3 server, requesting an unknown live query ID returns a 500 error (“no elements in sequence”) rather than a 404.
- Parameters:
- Returns:
ObjectApiResponse whose
dataobject contains the live query details:action_id,agents,expiration,statusand per-query result counts.- Raises:
ApiError – If the live query does not exist (the server returns a 500 rather than a 404) or another API error occurs.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> details = client.osquery.get_live_query( ... id="3c42c847-eb30-4452-80e0-728584042334" ... ) >>> print(details.body["data"]["status"])
- get_live_query_results(*, id, action_id, kuery=None, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get the results of a live query using the query action ID.
- Parameters:
id (str) – The ID of the live query result you want to retrieve (the live query
action_id).action_id (str) – The ID of the query action that generated the live query results (the per-query
action_idfrom thequerieslist of the live query).kuery (str | None) – The kuery to filter the results by.
page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to get the results from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains anedgeslist of result documents and atotalcount.- Raises:
NotFoundError – If the query action does not exist (“Action not found”).
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> results = client.osquery.get_live_query_results( ... id="3c42c847-eb30-4452-80e0-728584042334", ... action_id="609c4c66-ba3d-43fa-afdd-53e244577aa0", ... page_size=100, ... ) >>> print(results.body["data"]["total"])
AsyncOsqueryClient¶
Asynchronous version of the OsqueryClient for use with async/await syntax.
- class kibana._async.client.osquery.AsyncOsqueryClient(client, default_space_id=None, validate_spaces=True)[source]¶
Bases:
AsyncNamespaceClientAsync client for the Kibana Security Osquery API.
Run live queries against Elastic Agents with Osquery Manager, and manage reusable saved queries and scheduled query packs. The Osquery integration must be added to an agent policy for queries to actually execute on hosts.
The API manages three resource types:
Packs (
/api/osquery/packs): named sets of queries scheduled to run at an interval on the agent policies the pack is assigned to.Saved queries (
/api/osquery/saved_queries): reusable single queries that can be run as live queries or included in packs.Live queries (
/api/osquery/live_queries): one-off queries dispatched to a selection of agents, with per-action results.
All Osquery resources are space-aware: every method accepts an optional
space_idto target a specific space (Nonetargets the default space or the space the client is scoped to).Example
>>> from kibana import AsyncKibana >>> client = AsyncKibana("http://localhost:5601", api_key="...") >>> >>> # Create a pack with one scheduled query >>> pack = await client.osquery.create_pack( ... name="my_pack", ... queries={ ... "uptime": {"query": "select * from uptime;", "interval": 3600} ... }, ... ) >>> pack_id = pack.body["data"]["saved_object_id"] >>> >>> # Run a live query on all agents and fetch its results >>> live = await client.osquery.create_live_query( ... query="select * from uptime;", agent_all=True ... ) >>> action_id = live.body["data"]["action_id"] >>> details = await client.osquery.get_live_query(id=action_id)
Usage
The AsyncOsqueryClient provides the same methods as OsqueryClient but all methods are async and must be awaited:
from kibana import AsyncKibana import asyncio async def main(): async with AsyncKibana("http://localhost:5601") as client: # Create a saved query (async) saved = await client.osquery.create_saved_query( id="my_async_saved_query", query="select * from uptime;", interval="60", ) saved_object_id = saved.body["data"]["saved_object_id"] # List packs and saved queries (async) packs = await client.osquery.find_packs(page_size=20) queries = await client.osquery.find_saved_queries(page_size=20) # Clean up (async) await client.osquery.delete_saved_query(id=saved_object_id) asyncio.run(main())
- __init__(client, default_space_id=None, validate_spaces=True)[source]¶
Initialize the AsyncOsqueryClient.
- Parameters:
client (AsyncKibana) – The parent AsyncKibana client instance to delegate requests to.
default_space_id (str | None) – Optional default space ID for all operations.
validate_spaces (bool) – Whether to validate space existence before space-scoped operations (default: True).
Example
>>> osquery_client = AsyncOsqueryClient(kibana_client)
- async create_pack(*, name, queries, description=None, enabled=None, policy_ids=None, shards=None, space_id=None, validate_spaces=None)[source]¶
Create a query pack.
Creates an Osquery pack: a named set of queries that are scheduled to run on the agent policies the pack is assigned to.
- Parameters:
name (str) – The pack name.
queries (dict[str, Any]) – An object of queries keyed by query ID. Each value may contain
query(the SQL to run),interval(seconds between runs),platform,version,ecs_mapping,snapshotandremoved. Kibana requiresqueryandintervalfor each entry.description (str | None) – The pack description.
enabled (bool | None) – Enables the pack. Enabled packs run on the agent policies listed in
policy_ids.policy_ids (list[str] | None) – A list of agent policy IDs to schedule the pack on.
shards (dict[str, Any] | None) – An object with shard configuration for policies included in the pack. For each policy, set the shard configuration to a percentage (1-100) of target hosts.
space_id (str | None) – Optional space ID to create the pack in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the created pack, includingsaved_object_id(use it for get/update/delete),name,queries,enabledand audit metadata.- Raises:
BadRequestError – If required fields are missing or invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> pack = await client.osquery.create_pack( ... name="my_pack", ... description="Track uptime", ... enabled=False, ... queries={ ... "uptime": { ... "query": "select * from uptime;", ... "interval": 3600, ... } ... }, ... ) >>> print(pack.body["data"]["saved_object_id"])
- async find_packs(*, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get a list of all query packs.
- Parameters:
page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to list packs from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse containing
page,per_page,totaland adatalist of packs. Live Kibana 9.4.3 returns flattened pack objects (name,queries,saved_object_id, …), not theid/attributeswrapper shown in the OpenAPI example.- Raises:
BadRequestError – If a query parameter is invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> packs = await client.osquery.find_packs(page=1, page_size=10) >>> for pack in packs.body["data"]: ... print(pack["saved_object_id"], pack["name"])
- async get_pack(*, id, space_id=None, validate_spaces=None)[source]¶
Get the details of a query pack using the pack ID.
- Parameters:
- Returns:
name,description,enabled,queries,policy_ids,read_onlyand audit metadata.- Return type:
ObjectApiResponse whose
dataobject contains the pack- Raises:
NotFoundError – If the pack does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
Example
>>> pack = await client.osquery.get_pack( ... id="3c42c847-eb30-4452-80e0-728584042334" ... ) >>> print(pack.body["data"]["name"])
- async update_pack(*, id, name=None, description=None, enabled=None, policy_ids=None, queries=None, shards=None, space_id=None, validate_spaces=None)[source]¶
Update a query pack using the pack ID.
You cannot update a prebuilt pack. Note that the live Kibana server treats this as a replacement update: optional fields omitted from the request (for example
description) may be reset to their defaults, so pass every field you want to keep.- Parameters:
id (str) – The ID of the pack you want to update (the pack’s saved object ID).
name (str | None) – The pack name.
description (str | None) – The pack description.
enabled (bool | None) – Enables the pack.
policy_ids (list[str] | None) – A list of agent policy IDs to schedule the pack on.
queries (dict[str, Any] | None) – An object of queries keyed by query ID (same shape as in
create_pack()).shards (dict[str, Any] | None) – An object with shard configuration for policies included in the pack. For each policy, set the shard configuration to a percentage (1-100) of target hosts.
space_id (str | None) – Optional space ID the pack lives in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the updated pack. Live Kibana 9.4.3 returns the flattened pack (as increate_pack()) whenenabledis included in the request, and the raw saved object (attributeswrapper) otherwise.- Raises:
BadRequestError – If the request body is invalid or the pack is prebuilt.
NotFoundError – If the pack does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> await client.osquery.update_pack( ... id="3c42c847-eb30-4452-80e0-728584042334", ... name="updated_pack_name", ... description="Still tracking uptime", ... queries={ ... "uptime": { ... "query": "select * from uptime;", ... "interval": 3600, ... } ... }, ... )
- async delete_pack(*, id, space_id=None, validate_spaces=None)[source]¶
Delete a query pack using the pack ID.
- Parameters:
- Returns:
ObjectApiResponse with an empty object body on success.
- Raises:
NotFoundError – If the pack does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> await client.osquery.delete_pack( ... id="3c42c847-eb30-4452-80e0-728584042334" ... )
- async create_saved_query(*, id, query, interval, description=None, ecs_mapping=None, platform=None, removed=None, snapshot=None, version=None, space_id=None, validate_spaces=None)[source]¶
Create a saved query.
Creates a reusable Osquery saved query that can be run as a live query or added to packs.
- Parameters:
id (str) – The saved query identifier (its name, for example
"my_saved_query"). This is distinct from the saved object ID generated by Kibana.query (str) – The SQL query you want to run.
interval (str) – An interval, in seconds, on which to run the query, as a string (for example
"60"). The live server rejects integer values.description (str | None) – The saved query description.
ecs_mapping (dict[str, Any] | None) – Map osquery results columns or static values to Elastic Common Schema (ECS) fields, for example
{"host.uptime": {"field": "total_seconds"}}.platform (str | None) – Restricts the query to a specified platform. The default is all platforms. To specify multiple platforms, use commas, for example
"linux,darwin".removed (bool | None) – Indicates whether the query is removed.
snapshot (bool | None) – Indicates whether the query is a snapshot.
version (str | None) – Uses the Osquery versions greater than or equal to the specified version string.
space_id (str | None) – Optional space ID to create the saved query in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the created saved query, includingsaved_object_id(use it for get/update/delete) and audit metadata.- Raises:
BadRequestError – If required fields are missing or invalid.
ConflictError – If a saved query with the same
idexists.AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> saved = await client.osquery.create_saved_query( ... id="my_saved_query", ... query="select * from uptime;", ... interval="60", ... description="Host uptime", ... ecs_mapping={"host.uptime": {"field": "total_seconds"}}, ... ) >>> print(saved.body["data"]["saved_object_id"])
- async find_saved_queries(*, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get a list of all saved queries.
- Parameters:
page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to list saved queries from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse containing
page,per_page,totaland adatalist of saved queries. Live Kibana 9.4.3 returns flattened objects whereidis the saved query name andsaved_object_idis the saved object ID, not theid/attributeswrapper shown in the OpenAPI example.- Raises:
BadRequestError – If a query parameter is invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> queries = await client.osquery.find_saved_queries(page_size=100) >>> for saved in queries.body["data"]: ... print(saved["saved_object_id"], saved["id"])
- async get_saved_query(*, id, space_id=None, validate_spaces=None)[source]¶
Get the details of a saved query using the query ID.
- Parameters:
- Returns:
ObjectApiResponse whose
dataobject contains the saved query attributes (id,query,interval,ecs_mapping,prebuilt, …) and audit metadata.- Raises:
NotFoundError – If the saved query does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> saved = await client.osquery.get_saved_query( ... id="3c42c847-eb30-4452-80e0-728584042334" ... ) >>> print(saved.body["data"]["query"])
- async update_saved_query(*, id, new_id, query=None, description=None, interval=None, ecs_mapping=None, platform=None, removed=None, snapshot=None, version=None, space_id=None, validate_spaces=None)[source]¶
Update a saved query using the query ID.
You cannot update a prebuilt saved query. Note that the live Kibana server treats this as a replacement update: optional fields omitted from the request (for example
intervalordescription) may be reset or removed, so pass every field you want to keep. Also note that whileintervalmust be sent as a string, the server stores and returns it as an integer after an update.- Parameters:
id (str) – The ID of the saved query you want to update (the saved query’s saved object ID).
new_id (str) – The saved query identifier to set (the body
idfield). Required by the server; pass the existing identifier to keep it unchanged, or a different one to rename the saved query.query (str | None) – The SQL query you want to run.
description (str | None) – The saved query description.
interval (str | None) – An interval, in seconds, on which to run the query, as a string (for example
"60").ecs_mapping (dict[str, Any] | None) – Map osquery results columns or static values to Elastic Common Schema (ECS) fields.
platform (str | None) – Restricts the query to a specified platform, for example
"linux,darwin".removed (bool | None) – Indicates whether the query is removed.
snapshot (bool | None) – Indicates whether the query is a snapshot.
version (str | None) – Uses the Osquery versions greater than or equal to the specified version string.
space_id (str | None) – Optional space ID the saved query lives in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the updated saved query.- Raises:
BadRequestError – If the request body is invalid or the saved query is prebuilt.
NotFoundError – If the saved query does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> await client.osquery.update_saved_query( ... id="3c42c847-eb30-4452-80e0-728584042334", ... new_id="my_saved_query", ... query="select * from uptime;", ... interval="120", ... )
- async delete_saved_query(*, id, space_id=None, validate_spaces=None)[source]¶
Delete a saved query using the query ID.
- Parameters:
- Returns:
ObjectApiResponse with an empty object body on success.
- Raises:
NotFoundError – If the saved query does not exist.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> await client.osquery.delete_saved_query( ... id="3c42c847-eb30-4452-80e0-728584042334" ... )
- async create_live_query(*, query=None, queries=None, saved_query_id=None, pack_id=None, agent_all=None, agent_ids=None, agent_platforms=None, agent_policy_ids=None, alert_ids=None, case_ids=None, event_ids=None, ecs_mapping=None, metadata=None, space_id=None, validate_spaces=None)[source]¶
Create and run a live query.
Dispatches an Osquery query (or a pack of queries) to a selection of agents. Specify what to run via
query,queries,saved_query_idorpack_id, and select agents viaagent_all,agent_ids,agent_platformsoragent_policy_ids.Note: on a stack where no Elastic Agent has ever enrolled, the live server responds with a 500
index_not_found_exception(missing.fleet-agentsindex) instead of accepting the query.- Parameters:
query (str | None) – The SQL query you want to run.
queries (list[dict[str, Any]] | None) – An array of queries to run. Each entry may contain
id,query,platform,version,ecs_mapping,snapshotandremoved.saved_query_id (str | None) – The ID of a saved query to run.
pack_id (str | None) – The ID of the pack you want to run.
agent_all (bool | None) – When True, the query runs on all agents.
agent_ids (list[str] | None) – A list of agent IDs to run the query on.
agent_platforms (list[str] | None) – A list of agent platforms to run the query on.
agent_policy_ids (list[str] | None) – A list of agent policy IDs to run the query on.
alert_ids (list[str] | None) – A list of alert IDs associated with the live query.
case_ids (list[str] | None) – A list of case IDs associated with the live query.
event_ids (list[str] | None) – A list of event IDs associated with the live query.
ecs_mapping (dict[str, Any] | None) – Map osquery results columns or static values to Elastic Common Schema (ECS) fields.
metadata (dict[str, Any] | None) – Custom metadata object associated with the live query.
space_id (str | None) – Optional space ID to run the live query in.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the queued live query:action_id,agents,expirationand aquerieslist with a per-queryaction_id(use it withget_live_query_results()).- Raises:
BadRequestError – If the request body is invalid (e.g. no query and no pack specified).
ApiError – If the query cannot be dispatched (e.g. no agents have ever enrolled on the stack).
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> live = await client.osquery.create_live_query( ... query="select * from uptime;", ... agent_all=True, ... ecs_mapping={"host.uptime": {"field": "total_seconds"}}, ... ) >>> print(live.body["data"]["action_id"])
- async find_live_queries(*, kuery=None, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get a list of all live queries.
- Parameters:
kuery (str | None) – The kuery to filter the results by, for example
"agent.id: 16d7caf5-efd2-4212-9b62-73dafc91fa13".page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to list live queries from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains the raw search response with anitemslist of live query actions.- Raises:
BadRequestError – If a query parameter is invalid.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> live_queries = await client.osquery.find_live_queries(page_size=10) >>> print(live_queries.body["data"]["total"])
- async get_live_query(*, id, space_id=None, validate_spaces=None)[source]¶
Get the details of a live query using the query ID.
Note: on the live Kibana 9.4.3 server, requesting an unknown live query ID returns a 500 error (“no elements in sequence”) rather than a 404.
- Parameters:
- Returns:
ObjectApiResponse whose
dataobject contains the live query details:action_id,agents,expiration,statusand per-query result counts.- Raises:
ApiError – If the live query does not exist (the server returns a 500 rather than a 404) or another API error occurs.
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> details = await client.osquery.get_live_query( ... id="3c42c847-eb30-4452-80e0-728584042334" ... ) >>> print(details.body["data"]["status"])
- async get_live_query_results(*, id, action_id, kuery=None, page=None, page_size=None, sort=None, sort_order=None, space_id=None, validate_spaces=None)[source]¶
Get the results of a live query using the query action ID.
- Parameters:
id (str) – The ID of the live query result you want to retrieve (the live query
action_id).action_id (str) – The ID of the query action that generated the live query results (the per-query
action_idfrom thequerieslist of the live query).kuery (str | None) – The kuery to filter the results by.
page (int | None) – The page number to return. The default is 1.
page_size (int | None) – The number of results to return per page. The default is 20.
sort (str | None) – The field that is used to sort the results. The default is
createdAt.sort_order (str | None) – Specifies the sort order, either
ascordesc.space_id (str | None) – Optional space ID to get the results from.
validate_spaces (bool | None) – Override space validation setting for this operation.
- Returns:
ObjectApiResponse whose
dataobject contains anedgeslist of result documents and atotalcount.- Raises:
NotFoundError – If the query action does not exist (“Action not found”).
AuthenticationException – If authentication fails.
AuthorizationException – If insufficient privileges.
SpaceNotFoundError – If the space doesn’t exist and validation is enabled.
- Return type:
Example
>>> results = await client.osquery.get_live_query_results( ... id="3c42c847-eb30-4452-80e0-728584042334", ... action_id="609c4c66-ba3d-43fa-afdd-53e244577aa0", ... page_size=100, ... ) >>> print(results.body["data"]["total"])