diff --git a/docs/en/plugins/pandora-cli.md b/docs/en/plugins/pandora-cli.md new file mode 100644 index 0000000..20f3714 --- /dev/null +++ b/docs/en/plugins/pandora-cli.md @@ -0,0 +1,750 @@ +# Pandora CLI + +*Article last updated: 2026-10-08.* + +## Introduction + +`pandora-cli` is a command-line client for the Pandora FMS **API v2**. It lets you read and change +console data from a terminal or a script, without going through the web interface. + +**Type**: Standalone command-line tool + +Every command follows the same shape: + +``` +pandora-cli [arguments] [flags] +``` + +```bash +pandora-cli user list +pandora-cli event list --size 10 +pandora-cli tag get 5 +pandora-cli group create --set name=Servers +``` + +It is a single self-contained executable with no runtime dependencies. It performs one API call per +command: all validation, permissions and business rules stay in the console. + +## Compatibility matrix + +| **Consoles where tested** | Pandora FMS v8.0NG.800.4 (LTS), v8.0NG.804 (RRR) | +| --- | --- | +| **Consoles where it works** | Consoles publishing API v2. Whether a filter parameter is accepted is decided by the console per entity, at request time; older consoles may reject more of them. See [Filtering features by entity](#filtering-features-by-entity). | +| **Systems where tested** | Linux x86-64 | +| **Executables provided for** | Linux (x86-64, ARM64), macOS (Intel, Apple silicon), Windows (x86-64) | + +## Prerequisites + +**An API v2 token.** Create it in the console under the user whose permissions the CLI should use. +Every command runs with that user's ACL profile. + +**Network access to the console** over HTTP or HTTPS. + +**The client's address allowed by the API ACL.** The console restricts API access by IP. If the +address is not on the list, every call fails with: + +``` +401 IP 10.0.0.5 is not in ACL list +``` + +That is a console setting, not a CLI one: add the address to the API ACL list in the console +configuration before continuing. + +## Configure access + +### Store a token + +`auth login` checks the token against the console **before** writing anything. If it is rejected, +nothing is stored. + +```bash +pandora-cli auth login --token --url https://console.example.com/pandora_console/api/v2/ +``` + +The URL defaults to `http://localhost/pandora_console/api/v2/`. It must point at the API root and +end in `/api/v2/`. + +Credentials are written to `~/.pandora-cli/config.json` with the directory set to `0700` and the +file to `0600`. The token is stored base64-encoded, which keeps it out of casual terminal output; +the file permissions are what actually protects it. The CLI refuses to read a configuration file +whose permissions are wider than `0600`. + +Set `PANDORA_CLI_HOME` to keep the configuration somewhere else. + +### Several consoles + +Each console is a named context. + +```bash +pandora-cli auth login --token --url https://prod/pandora_console/api/v2/ --context prod +pandora-cli auth login --token --url https://lab/pandora_console/api/v2/ --context lab --insecure + +pandora-cli auth context list +pandora-cli auth context use prod +pandora-cli user list --context lab # one command against another console +``` + +`--token` and `--url` can also be passed to any command directly. Used that way the token is never +written to disk, which suits a CI job that already holds it in a secret. + +### AI session correlation + +Use an optional AI session ID to attach correlation metadata to API v2 requests. Save it in a +named context when logging in. Tokens passed as command arguments may appear in shell history or +the operating system process list. + +```bash +pandora-cli auth login --token '' --url https://console.example.com/pandora_console/api/v2/ --context prod --ai-session-id ai-session-example-001 +pandora-cli user list --context prod +``` + +After a successful login, the first command stores `ai_session_id` in the destination context in +`~/.pandora-cli/config.json`. The later command reuses that ID without repeating the flag. + +Resolution order is **explicit `--ai-session-id` (including an empty value) → selected/current +context `ai_session_id` → absent**. A nonempty ID sends `X-Pandora-AI-Session` on every API v2 +request, including authentication and the console specification fetch. An absent or empty ID omits +the header. Control characters are rejected. + +Login and other commands treat overrides differently: + +| Invocation | Effect on the stored ID | +| --- | --- | +| Successful `auth login --ai-session-id ` | Saves the explicit ID in the destination context. | +| Successful `auth login` without the flag | Preserves that context's prior ID. | +| Successful `auth login --ai-session-id=` | Clears that context's stored ID; the empty field is omitted from JSON. | +| Failed login or invalid ID | Writes nothing; the existing configuration remains unchanged. | +| Any other command with `--ai-session-id ` or `--ai-session-id=` | Overrides or disables the header for that invocation only; never changes the stored ID. | + +For example, disable the header for one read without clearing the saved ID, or clear it with a +successful login: + +```bash +pandora-cli user list --context prod --ai-session-id= +pandora-cli auth login --token '' --url https://console.example.com/pandora_console/api/v2/ --context prod --ai-session-id= +``` + +The ID is correlation metadata, not a credential: it does not authenticate the caller or grant +permissions. Sending the header does not establish that the console records or displays it in an +audit log. + +### Self-signed certificates + +`--insecure` skips TLS verification. It is never applied by default. Passed to `auth login` it is +remembered for that context; passed to any other command it applies to that command only. + +## Verify + +```bash +pandora-cli auth status +``` + +``` +Context: prod +URL: https://console.example.com/pandora_console/api/v2/ +Insecure: false +Config: /home/user/.pandora-cli/config.json +Token: valid + +Console specification: 282 operations, 46 entities (read 2026-09-22T09:12:37Z) +``` + +`Token: valid` means the console accepted it. The command exits non-zero if it did not. With `-o json` +the output is exactly five values — `context`, `url`, `insecure`, `config` and `token` — without the +informational summary line shown above in table format. + +Then read something real: + +```bash +pandora-cli user list +``` + +``` +IDUSER FULLNAME EMAIL ISADMIN DISABLED +admin Pandora admin@example.com true false + +1 shown, 1 total. +``` + +## Understand the output + +Output is a **table on a terminal** and **JSON when redirected or piped**, so scripts get parseable +output without passing a flag: + +```bash +pandora-cli user list # table +pandora-cli user list | jq '.[].idUser' # JSON +pandora-cli user list > users.json # JSON +``` + +Force a format with `-o json`, `-o table` or `-o yaml`. + +Informational lines such as `1 shown, 1 total.` appear only in table format. In JSON and YAML they +are suppressed, so piped output is always valid. + +Listings are paginated by the console. `1 shown, 1 total.` reports how many rows came back and how +many exist; use `--page` and `--size` to walk a large result. Pagination is **1-based**: `--page 1` +is the first page. `--size` alone also returns the first page, because the console ignores a page +size without a page number on some endpoints; the CLI sends both. + +### Filtering features by entity + +`--where`, `--fields` and `--in` map to API parameters that each console entity implements on its +own: acceptance is **per entity**, not per console. `/user/list` may accept `fieldConditions` while +`/event/list` rejects it. The CLI keeps no per-console capability cache: it always sends the request +and the console answers. + +| Feature | Flag | +| --- | --- | +| `fieldConditions` | `--where` | +| `requestedFields` | `--fields` | +| `multipleSearchString` | `--in` | + +If the entity does not accept the parameter, the console rejects the request with +`400 Field: ... is not a valid parameter` and the CLI explains what happened, naming the flag that +sent the parameter. The flag stays usable on the entities that do accept it; only the rejected +request fails: + +``` +Error: POST event/list failed: 400 Field: fieldConditions is not a valid parameter +--where (fieldConditions) is not available on this console. +The console at https://console.example.com/pandora_console/api/v2/ rejects that parameter. +``` + +## Operate + +### Filtering a list + +```bash +pandora-cli user list --filter isAdmin=true +pandora-cli user list --where 'fullName like admin' --sort fullName +pandora-cli user list --search backup +pandora-cli user list --in idUser=admin,root +pandora-cli user list --fields idUser,email --size 50 +``` + +All filter flags are repeatable and combine with **AND**. When the field's schema declares it as an +array, repeating `--filter` for the same field accumulates into one array parameter instead of +ANDing: `--filter severity=4 --filter severity=2` sends `{"severity":[4,2]}`. An explicit `null` +value is the exception: it is sent as a plain null (never as `[null]`), so it clears the field +regardless of position among the repeated flags. + +**Two different field sets apply per entity.** `--filter` accepts any field of the entity, but +`--where`, `--fields` and `--in` accept a narrower, per-entity set — for `agent-secondary-group` it +is just `idAgent` and `idGroup`; for `user` it is a fixed subset of 20 fields out of the entity's 81. +The two sets are not nested: an entity may accept a field for `--fields` that is not a normal entity +field. The CLI validates both locally and lists the valid names when it refuses, so read the error +rather than guessing again. Several entities — including `group`, `tag`, `profile`, `token` and +`data-translation` — accept a wider `--where`/`--fields`/`--in` field set than earlier builds; run +`pandora-cli --help` to see the exact list for the installed build. + +`agent list` additionally accepts module counters — `criticalCount`, `warningCount`, +`unknownCount`, `normalCount`, `notinitCount`, `totalCount` and `firedCount` — in `--fields`, +`--where` and `--in`, alongside the entity's own columns: + +```bash +pandora-cli agent list --fields idAgent,alias,criticalCount,totalCount +``` + +The new entities follow the same rule. `policy` accepts `applyToSecondaryGroups`, +`createLinkedModules`, `description`, `forceApply`, `idGroup`, `idPolicy`, `name` and `status`; +`collection` accepts `description`, `idCollection`, `idGroup`, `name`, `shortName` and `status`; +`service` accepts `asynchronous`, `autoCalculate`, `cascadeProtection`, `cpsInhibit`, `critical`, +`description`, `evaluateSla`, `idGroup`, `idService`, `isFavourite`, `name`, `quiet`, +`serviceInterval`, `slaInterval`, `status`, `unknownAsCritical`, `utimestamp` and `warning`. The +`token` set now includes `isPandoraAi`, next to `idToken`, `idUser`, `label`, `lastUsage` and +`validity`. `--filter` still accepts every other field of each entity. + +`module-alert list` takes an optional `idAgentModule`. With it, it lists that module's alerts, as +before. Without it, it lists every module alert on the console: + +```bash +pandora-cli module-alert list +pandora-cli module-alert list --where 'timesFired = 1' +``` + +Module alerts also expose a `status` field — `fired`, `notFired`, `disabled` or `allEnabled` — +usable with `--filter` (`--filter status=fired`), but not with `--where`, `--fields` or `--in`. + +`event` is the one exception: the CLI does not validate `--where`, `--fields` or `--in` locally for +it. It sends whatever is passed and lets the console decide, because the console's event listing +does not implement `fieldConditions`, `requestedFields` or `multipleSearchString` for any field. A +rejection therefore always comes back from the console, explained the same way described in +[Filtering features by entity](#filtering-features-by-entity). + +`event list`'s `dateRange` filter takes a JSON string, not a `" - "` string: + +```bash +pandora-cli event list --filter 'dateRange={"preset":{"value":"last_24_hours"}}' +pandora-cli event list --filter 'dateRange={"start":{"mode":"relative","value":1,"unit":"hours"},"end":{"mode":"now"}}' +``` + +The older `" - "` string now fails with `400 Invalid date range format. Must be valid +JSON`. + +In Windows PowerShell 5.1 (and PowerShell 7 before 7.3), the double quotes inside an argument are +removed before it reaches `pandora-cli`, so the console receives invalid JSON and answers with the +same `400`. Escape each inner double quote with a backslash: + +```powershell +pandora-cli event list --filter 'dateRange={\"preset\":{\"value\":\"last_24_hours\"}}' +``` + +Values are converted to their JSON type: `true` and `false` become booleans, digits become numbers, +`null` becomes null. Quote to force a string: + +```bash +pandora-cli tag list --filter name='"42"' +``` + +### Creating and changing + +```bash +pandora-cli user create --set idUser=jdoe --set fullName='Jane Doe' --set password=secret +pandora-cli user update jdoe --set email=jane@example.com +pandora-cli user delete jdoe --yes +``` + +`--set` is repeatable. For a full payload, read JSON from a file or from standard input: + +```bash +pandora-cli user create --from-file user.json +cat user.json | pandora-cli user create --from-file - +``` + +`--set` and `--from-file` cannot be combined. + +`--set` values are converted to their JSON type exactly like filter values. A string field whose +value looks like a number is therefore sent as a number: `--set permissions=0755` sends the number `755`. +Quote the value to force a string, or send the payload with +`--from-file`: + +```bash +pandora-cli --set permissions='"0755"' +``` + +When the schema declares a field as an **array** — for example `severity` on `event-filter` or +`wildcardAgents` on `report-datasource` — a `--set` value is serialized as an array with one +element, and repeating the flag accumulates elements into that array. As with `--filter`, an +explicit `null` is sent as a plain null and clears the accumulated array. + +`--from-file` accepts a JSON **array** as the whole body, not only an object. Endpoints whose body is +a list require it, such as `pandora-cli monitoring create` below. A leading UTF-8 BOM in the file is +tolerated, so files written by Windows editors work as-is. One edge case: the schema may +declare a scalar where the console endpoint expects an array (a documented mismatch, for example +`position` on `report-design-page-widget`); write the array into the file and send it with +`--from-file`. + +`delete` asks for confirmation. In a non-interactive session it **refuses** instead of prompting, so +a script that forgot `--yes` fails loudly rather than deleting silently. + +Some entities enforce server-side rules that are not visible in their field list: `agent create` +needs a real group — `idGroup=0` is rejected with `400 Agent group is missing`; the console assigns +the agent's `name` itself regardless of the payload, so use `alias` for the label you actually +control; `module create` needs `idModule` (the module's server type) together with `idModuleType`, +not only the columns listed under `--where`/`--fields`/`--in`; and a non-admin user created with +`user create` needs at least one profile assigned with `user profile add` before it can log in; an +`event-alert-rule` created with `event-alert-rule create` needs the alert's first ordered rule to +have `operation=NOP` — the console rejects any other operation on that first rule. +`module force-check` requests an immediate check of an agent module; the check itself completes out +of band, so a successful call returns `202` with no body. The console rejects it with `400` for +module types that do not support an immediate check, such as data-push modules. The optional +`--serverId` flag targets a federated node's module from a metaconsole. + +### Pushing monitoring data + +`pandora-cli monitoring create` pushes agent data into Pandora FMS. Its body is an **array** of +payloads with snake_case keys — `agent_data` and `module_data`: + +```bash +cat > payload.json << 'EOF' +[ + { + "agent_data": {"agent_name": "web1", "address": "10.0.0.5", "interval": 300}, + "module_data": [ + {"name": "cpu_usage", "type": "generic_data", "data": 12.5}, + {"name": "mem_used", "type": "generic_data", "datalist": [{"value": 2048, "timestamp": "2026/09/07 11:00:00"}]} + ] + } +] +EOF +pandora-cli monitoring create --from-file payload.json +``` + +The agent is created if it does not exist. `agent_name`, `address` and `interval` are required; +the console rejects the request without any of them. Other `agent_data` keys are optional. Every entry in +`module_data` needs a `type` such as `generic_data`; the console rejects the request without it. A payload may also carry +`events`, `inventory_data`, `log_data`, `trap_data`, `discovery_data` and `cmd_data`. Re-sending the +same agent, module and timestamp updates the existing value instead of duplicating it. + +### Nested entities + +Some entities live under a parent. Their commands take the parent identifier first: + +```bash +pandora-cli report-design-page list 12 +pandora-cli report-design-page-widget list 12 3 +``` + +Nested list commands that read with a filter body also take payload flags: their `--set` fields are +serialized the same way, so a field the endpoint declares as an array — like `requestedFields` — +accumulates from repeated flags: + +```bash +pandora-cli user profile list admin --set requestedFields=idUserProfile +``` + +`user profile get` and `user profile remove` take that same `idUserProfile` — the assignment's own +id, not the profile's id (`idProfile`). `user profile add` is unchanged and still takes `idProfile`: + +```bash +pandora-cli user profile get operator1 3 +pandora-cli user profile remove operator1 3 +``` + +**Breaking change**: earlier builds took `idProfile` for `user profile get`. When the same profile +is assigned to a user on more than one group, each assignment has its own `idUserProfile`. + +### Policies, collections and services + +`policy`, `collection` and `service` group part of their commands in **child groups**. The syntax is +` `, and `pandora-cli --help` lists the groups of an entity: + +```bash +pandora-cli policy module list 7 +pandora-cli collection file upload 3 --file ./a.conf +pandora-cli service element add 2 --set description='Frontend CPU' --set idAgenteModulo=42 +``` + +The groups are `policy agent`, `policy alert`, `policy alert-action`, `policy collection`, +`policy group`, `policy log-module`, `policy module`, `policy plugin` and `policy queue`; +`collection file`, `collection folder` and `collection agent`; and `service element`. Collections +are also assigned from the agent side with `agent collection list`, `agent collection add` and +`agent collection remove`. + +**Removing marks, it does not delete.** In a policy, `remove`, `delete` and `bulk-delete` on a child +(agent, alert, collection, group, log module, module or plugin) only mark it `pendingDelete`. The +removal takes effect when the policy queue is applied, and `restore` undoes the mark before that +happens. `policy alert-action remove` and `policy queue delete` are not marked: they act at once. + +**Purging and the queue are asynchronous.** `policy purge` and the `policy queue` operations enqueue +work and return without waiting. A policy cannot be deleted while queue entries are pending: check +`policy queue list` (or `policy queue summary`) and use `policy queue clear`, or wait, before +deleting it. Nor can it be deleted while it still has assigned agents: run `policy purge` and wait +for the queue to finish first. + +**Bulk plugin operations need a JSON array.** `policy plugin bulk-delete`, `bulk-disable`, +`bulk-enable` and `bulk-restore` take a top-level array of plugin ids, which `--set` cannot build. +Send it from standard input or a file with `--from-file`; the result reports the successes and +errors per plugin: + +```bash +echo '[4,5]' | pandora-cli policy plugin bulk-enable 7 --from-file - +``` + +Policy children are identified by their own id, which follows the policy id on the command line +(` `, ` `, and so on). The options a user needs +most: + +| Group | Verbs | Main options | +| --- | --- | --- | +| `policy agent` | `list`, `get`, `add`, `remove`, `restore` | `add`: `--set idAgent=`. | +| `policy group` | `list`, `get`, `add`, `remove`, `restore` | `add`: `--set idGroup=`. | +| `policy collection` | `list`, `available`, `get`, `add`, `remove`, `restore` | `add`: `--set idCollection=`. `available` lists the collections not linked yet. | +| `policy module` | `list`, `get`, `create`, `update`, `delete`, `enable`, `disable`, `restore` | `create`: `--set name=...`, `--set moduleType=...`, `--set idModule=` and `--set idModuleType=`. | +| `policy log-module` | `list`, `get`, `create`, `update`, `delete`, `enable`, `disable`, `restore` | `create`: `--set collectorMode=...`, `--set moduleName=...`, `--set source=...` and `--set sourceType=...`. | +| `policy plugin` | `list`, `get`, `create`, `update`, `delete`, `enable`, `disable`, `restore`, `bulk-delete`, `bulk-disable`, `bulk-enable`, `bulk-restore` | `create`: `--set pluginExecution=`. The `bulk-*` verbs take a JSON array (see above). | +| `policy alert` | `list`, `get`, `create`, `update`, `delete`, `restore` | `create`: `--set idPolicyModule=` and `--set idAlertTemplate=`. `update`: `--set disabled=true`. | +| `policy alert-action` | `list`, `add`, `remove` | Take ` `. `add`: `--set idAlertAction=`, `--set firesMin=` and `--set firesMax=`. `remove` also takes ``. | +| `policy queue` | `list`, `get`, `summary`, `add`, `apply-pending`, `clear`, `delete` | `add`: `--set operation=apply` and `--set idAgent=`. `apply-pending` queues the pending changes. `clear` and `delete` ask for confirmation unless `--yes` is given. | + +`policy copy` takes `--set name=...` and `--set idGroup=` for the new policy; `policy purge` +takes no options. + +```bash +pandora-cli policy agent add 7 --set idAgent=42 +pandora-cli policy queue apply-pending 7 +pandora-cli policy queue summary 7 +``` + +**Fixed after creation.** The `moduleType`, `idModule` and `idModuleType` of a policy module cannot +be changed once it exists; create a new policy module instead. + +**Collections need a remote agent.** Assigning a collection to an agent (`agent collection add`; +`collection agent list` shows the result) requires an agent with remote configuration (`remote=1`) +that is available on the console. Otherwise the console answers +`Agent remote configuration is unavailable`, including for an agent that has `remote=1` but no +remote configuration yet. The assignment is only recorded in the agent's remote configuration; run `collection apply` after changing the files of a collection so that agents pick +up the new package. + +**`isPandoraAi` on `token`** can only be set when the token is created. + +### Transferring files + +Two commands of `collection` move file contents. They use their own flags, and `--from-file` does +not apply to them. + +**Upload** (`collection file upload`) sends the request as `multipart/form-data`. Pass each file with +`--file `, or with `--file =` to name the form field; the flag is repeatable and at +least one is required. The text form fields (`folder`, `decompress`, `overwrite` and `permissions`) +go in `--set field=value` and are sent as strings, so no extra quoting is needed there. File +contents are never printed by `-v`. + +```bash +pandora-cli collection file upload 3 --file ./a.conf +``` + +**Download** (`collection file download`) returns raw bytes, so `--output-file ` is required; +`--output-file -` writes to standard output. An existing file is replaced only with `--force`, and a +failed download leaves no partial file. `--output-file` is the destination: `-o/--output` still +selects the output format. + +```bash +pandora-cli collection file download 3 --path a.conf --output-file ./a.conf +pandora-cli collection file download 3 --path a.conf --output-file ./a.conf --force +``` + +The other commands of the `collection` file groups take the collection id and these options. +`--path` is always relative to the collection, never an absolute server path. + +| Command | Options | +| --- | --- | +| `collection file list` | `--set folder=` is optional; omitting it lists the root. | +| `collection file read` | `--path ` (required). Prints the text content of the file. | +| `collection file create` | `--set path=` (required) and `--set content=`; without `content` an empty file is created. | +| `collection file update` | `--set path=` and `--set content=` replace the content of an existing file. | +| `collection file delete` | `--path ` (required) and `--yes`. | +| `collection folder create` | `--set path=` (required); `--set recursive=true` also creates missing parent folders. | +| `collection folder delete` | `--path ` (required) and `--yes`. The folder must be empty. | +| `collection agent list` | No options. Lists the agents assigned to the collection. | +| `collection apply` | No options. Generates the collection package again. | + +```bash +pandora-cli collection folder create 3 --set path=scripts --set recursive=true +pandora-cli collection file create 3 --set path=scripts/check.sh --set content='echo ok' +pandora-cli collection file read 3 --path scripts/check.sh +``` + +### Module graphs + +`module graph` asks the console to render a graph of an agent module. The options (`period`, +`graphType`, `width`, `height` and others) travel in the body as `--set` fields. The response is not +a binary stream: it carries the image base64-encoded in its `graph` field, with its `mimeType` +(`image/png` or `image/jpeg`) and `encoding` (`base64`) next to it. `period` is expressed in seconds +(minimum 300; the default is one day). + +```bash +pandora-cli module graph 12 --set period=3600 -o json | jq -r .graph | base64 -d > graph.png +``` + +### Inspecting the console's API + +`spec` reads the API description the console publishes about itself, so you can see which fields an +entity accepts without opening the console's `swagger.json`: + +```bash +pandora-cli spec list # schemas the console publishes +pandora-cli spec show EventFilter # one schema, allOf resolved: types, enums, readOnly +pandora-cli spec raw # the console's full swagger.json +``` + +For `create` and `update`, ask for the entity's schema with `spec show `; for the fields a +list filter accepts, ask for the matching filter schema with `spec show Filter`. `allOf` +composition is resolved, so inherited fields appear as the schema's own properties. Schema names are +the ones the console publishes — `EventFilter`, `EventFilterFilter`, `ReportDataSource` — which are +not the CLI's hyphenated entity names; `spec list` shows the exact names, and `spec show` suggests +the closest match if you mistype one. Output follows the usual `-o json`, `-o table` or `-o yaml` +format. + +### Documentation and agent usage + +```bash +pandora-cli docs # full command reference for this build +pandora-cli docs --out ref.md +``` + +For coding agents working in a terminal, install a usage skill describing this build: + +```bash +pandora-cli skill install # writes ~/.claude/skills/pandora-cli/SKILL.md +pandora-cli skill install --print # show it without installing +pandora-cli skill install --force # overwrite an existing one +``` + +Re-run it after upgrading so the skill keeps matching the executable. + +Use one correlation ID per AI session and rotate it when starting a new session. Save it with +`auth login --ai-session-id ` for reuse in the destination context. On other commands, +`--ai-session-id ` is a transient override and `--ai-session-id=` disables the header for that +invocation without clearing the stored ID. Later calls without the flag reuse the saved ID. See +the AI session correlation section for login save and clear behavior. + +### Diagnosing a call + +`--verbose` traces the request line, the request body and the response status to standard error, +leaving standard output clean for piping: + +```bash +pandora-cli user list --filter isAdmin=true -v -o json > users.json +``` + +``` +→ POST https://console.example.com/pandora_console/api/v2/user/list +→ body: {"isAdmin":true} +← 200, 1834 bytes +``` + +## Troubleshoot + +| Symptom | Cause and remedy | +| --- | --- | +| `401 ... token was rejected` | The token is wrong or expired. Re-run `auth login`. | +| `401 IP ... is not in ACL list` | The client address is not permitted by the console's API ACL. Add it in the console configuration. | +| `403 ... lacks permission` | The token is valid but the owning user's ACL profile does not allow the operation. | +| `404 ... or the API base URL is wrong` | Check `auth status`; the URL must end in `/api/v2/`. | +| `TLS verification failed` | Self-signed certificate. Re-run with `--insecure`, or store it for the context at login. | +| `has permissions 0644` | The configuration file is readable by others. Run `chmod 0600 ~/.pandora-cli/config.json`. | +| `--fields ... is not available on this console` | The entity does not implement that filter parameter; the console rejected the request and the CLI named the flag that sent it. See [Filtering features by entity](#filtering-features-by-entity). | +| `unknown field "..."` | The field does not exist on that entity. The message lists the valid names. | +| `the "..." entity does not exist on this console` | The console does not publish that entity. Run `auth status --refresh` if it was upgraded. | +| `--... is required by this endpoint` | A parameter the API declares as required was not supplied (for example `--path` in `collection file download`). | +| A policy cannot be deleted | The policy still has pending queue entries or assigned agents. Check `policy queue list` and use `policy queue clear` or wait; run `policy purge` to unassign its agents. | +| A policy child still appears after `remove` | The removal only marks it `pendingDelete` until the policy queue is applied. Use `restore` to undo it. | +| A collection cannot be assigned to an agent (`Agent remote configuration is unavailable`) | The agent needs remote configuration (`remote=1`) available on the console. | +| A value such as `0755` arrives as `755` | `--set` converts numeric-looking values. Use `--set permissions='"0755"'` or `--from-file`. | + +A command exits `0` on success and non-zero on failure, so it can be used directly in a script's +control flow. + +## Reference + +### Global flags + +| Flag | Meaning | +| --- | --- | +| `--context ` | Named context to use. Defaults to the current one. | +| `--url ` | API base URL, overriding the context. | +| `--token ` | Token for this command only. Never written to disk. | +| `--ai-session-id ` | Optional correlation ID; overrides the selected/current context. Successful `auth login` saves it; other commands use it transiently. `--ai-session-id=` omits the header and clears the stored ID only on successful login. | +| `--insecure` | Skip TLS certificate verification. | +| `-o, --output json\|table\|yaml` | Output format. Table on a terminal, JSON otherwise. | +| `-v, --verbose` | Trace requests to standard error. | +| `--timeout ` | Request timeout. Defaults to `30s`. | + +### List flags + +| Flag | Effect | Example | +| --- | --- | --- | +| `--filter =` | Field equality. | `--filter isAdmin=true` | +| `--where ' '` | Advanced condition. | `--where 'fullName like admin'` | +| `--search ` | Free-text search. | `--search backup` | +| `--in =` | Field within a list of values. | `--in idUser=admin,root` | +| `--fields ` | Restrict the returned fields. | `--fields idUser,email` | +| `--page ` | Page number, 1-based (`--page 1` is the first page). | `--page 2` | +| `--size ` | Rows per page. | `--size 50` | +| `--sort ` | Field to sort by. | `--sort fullName` | +| `--order asc\|desc` | Sort direction. | `--order desc` | + +Operators accepted by `--where`: `=`, `like`, `regex`, `in`, `between`, `is_not_empty`. For a JSON +column, address a path with `--where ': '`. + +### Write flags + +| Flag | Effect | +| --- | --- | +| `--set =` | One payload field. Repeatable. | +| `--from-file ` | Read the whole JSON payload from a file, or `-` for standard input. | +| `--yes` | Skip the confirmation prompt on a destructive command. | + +### File transfer flags + +| Flag | Effect | +| --- | --- | +| `--file ` or `--file =` | File to upload with a multipart command (`collection file upload`). Repeatable; at least one is required. | +| `--output-file ` | Destination of a raw-bytes command (`collection file download`). Required; `-` writes to standard output. | +| `--force` | Replace an existing `--output-file`. | + +### Authentication commands + +| Command | Effect | +| --- | --- | +| `auth login` | Validate a token and store it in a context. On success, an explicit `--ai-session-id` saves the ID in that context, omission preserves the prior ID, and `--ai-session-id=` clears it. Failed login or an invalid ID writes nothing. | +| `auth status` | Show the active context, verify the token and report the console's published specification. `--refresh` re-reads that specification. | +| `auth context list` | List stored contexts. | +| `auth context use ` | Select the current context. | +| `auth logout [context]` | Remove a stored context. | + +### Entities + +Every entity supports the verbs listed. Run `pandora-cli --help` for its exact commands and +arguments, and `pandora-cli docs` for the full reference of the installed build. + +| Entity | Covers | Verbs | +| --- | --- | --- | +| `agent` | Monitoring agents | `list`, `get`, `create`, `update`, `delete` + 4 more (`status` and the `collection` group) | +| `agent-extended-data` | Extended data attached to agents | `list`, `get`, `create`, `update`, `delete` | +| `agent-secondary-group` | Secondary groups of an agent | `list`, `create`, `delete` | +| `alert-action` | Alert actions | `list`, `get`, `create`, `update`, `delete` + 1 more | +| `alert-calendar` | Alert calendars | `list`, `get`, `create`, `update`, `delete` | +| `alert-command` | Alert commands | `list`, `get`, `create`, `update`, `delete` + 1 more | +| `alert-special-day` | Special days of an alert calendar | `list`, `get`, `create`, `update`, `delete` | +| `alert-template` | Alert templates | `list`, `get`, `create`, `update`, `delete` + 1 more | +| `bulk-draft` | Bulk operation drafts | `list`, `get`, `delete` + 1 more | +| `bulk-queue` | Bulk operation queue | `list`, `get`, `delete` | +| `collection` | File collections distributed to agents | `list`, `get`, `create`, `update`, `delete` + 11 more (`apply` and the `file`, `folder` and `agent` groups) | +| `dashboard` | Dashboards | `list`, `get`, `create`, `update`, `delete` | +| `dashboard-widget` | Widgets placed on a dashboard | `list`, `get`, `create`, `update`, `delete` | +| `data-translation` | Data translation definitions | `list`, `get`, `create`, `update`, `delete` | +| `event` | Monitoring events | `list`, `get`, `create`, `update`, `delete` + 12 more | +| `event-alert` | Event alerts | `list`, `get`, `create`, `update`, `delete` | +| `event-alert-action` | Actions of an event alert | `list`, `get`, `create`, `update`, `delete` | +| `event-alert-rule` | Rules that trigger an event alert | `list`, `get`, `create`, `update`, `delete` | +| `event-filter` | Saved event filters | `list`, `get`, `create`, `update`, `delete` | +| `event-tag` | Event tags | `list`, `get`, `create`, `update`, `delete` | +| `group` | Agent groups | `list`, `get`, `create`, `update`, `delete` | +| `module` (alias `agent-module`) | Agent modules | `list`, `get`, `create`, `update`, `delete` + 2 more (`force-check`, `graph`) | +| `module-alert` | Alerts assigned to an agent module | `list`, `get`, `create`, `update`, `delete` | +| `module-alert-action` | Actions fired by an agent module alert | `list`, `get`, `create`, `update`, `delete` | +| `module-data` | Historical data of an agent module | `list`, `get` + 1 more | +| `module-group` | Module groups | `list`, `get`, `create`, `update`, `delete` | +| `module-state` | Current polling state of agent modules | `list`, `get` | +| `module-tag` | Tags attached to an agent module | `list`, `get`, `create`, `delete` | +| `module-type` | Module types | `list`, `get` | +| `monitoring` | Push monitoring data | `create` | +| `pandora-itsm-inventory` | Pandora ITSM inventory | `list`, `get` | +| `policy` | Policies applied to agents | `list`, `get`, `create`, `update`, `delete` + 62 more (`copy`, `purge` and the `agent`, `alert`, `alert-action`, `collection`, `group`, `log-module`, `module`, `plugin` and `queue` groups) | +| `profile` | ACL profiles | `list`, `get`, `create`, `update`, `delete` | +| `report-datasource` | Report data sources | `list`, `get`, `create`, `update`, `delete` | +| `report-datasource-agent` | Agents attached to a report data source | `list`, `get`, `create`, `update`, `delete` | +| `report-datasource-group` | Groups attached to a report data source | `list`, `get`, `create`, `update`, `delete` | +| `report-design` | Report designs | `list`, `get`, `create`, `update`, `delete` + 5 more | +| `report-design-page` | Pages of a report design | `list`, `get`, `create`, `update`, `delete` | +| `report-design-page-widget` | Widgets on a report design page | `list`, `get`, `create`, `update`, `delete` | +| `report-design-report` | Report entries of a report design | `list`, `get`, `create`, `update`, `delete` | +| `report-design-template` | Templates of a report design | `list`, `get`, `create`, `update`, `delete` | +| `service` | Services | `list`, `get`, `create`, `update`, `delete` + 5 more (the `element` group) | +| `siem-group` | SIEM groups | `list`, `get`, `create`, `update`, `delete` | +| `siem-rule` | SIEM rules | `list`, `get`, `create`, `update`, `delete` + 4 more | +| `tag` | Module tags | `list`, `get`, `create`, `update`, `delete` | +| `token` | API tokens | `list`, `get`, `create`, `update`, `delete` | +| `user` | Console users and their profile assignments | `list`, `get`, `create`, `update`, `delete` + 5 more | +| `widget` | Dashboard widgets | `list`, `get` | + +The entities an executable knows are those of the API version it was built against. A console newer +than the executable may publish more; `pandora-cli auth status` reports what the console itself +publishes. + +### Files and environment + +| Path or variable | Purpose | +| --- | --- | +| `~/.pandora-cli/config.json` | Stored contexts and tokens. Mode `0600`. | +| `~/.pandora-cli/schema-.json` | Cached description of that console's API. | +| `PANDORA_CLI_HOME` | Overrides the configuration directory. | +| `CLAUDE_CONFIG_DIR` | Overrides where `skill install` writes. | + +Optional field in each context in `config.json`: + +| Name | Required | Default | Description | +| --- | --- | --- | --- | +| `ai_session_id` | No | Absent | Correlation ID reused when `--ai-session-id` is omitted. A nonempty value sends `X-Pandora-AI-Session`; an empty value omits the header. Successful login can save or clear it; an empty field is omitted from the saved JSON. Existing contexts without this field need no change. | diff --git a/docs/es/plugins/pandora-cli.md b/docs/es/plugins/pandora-cli.md new file mode 100644 index 0000000..feaa601 --- /dev/null +++ b/docs/es/plugins/pandora-cli.md @@ -0,0 +1,775 @@ +# Pandora CLI + +*Última actualización del artículo: 2026-10-08.* + +## Introducción + +`pandora-cli` es un cliente de línea de comandos para la **API v2** de Pandora FMS. Permite consultar +y modificar los datos de la consola desde un terminal o un script, sin pasar por la interfaz web. + +**Tipo**: Herramienta de línea de comandos independiente + +Todos los comandos siguen la misma forma: + +``` +pandora-cli [argumentos] [opciones] +``` + +```bash +pandora-cli user list +pandora-cli event list --size 10 +pandora-cli tag get 5 +pandora-cli group create --set name=Servers +``` + +Es un único ejecutable autocontenido, sin dependencias en tiempo de ejecución. Realiza una llamada a +la API por comando: toda la validación, los permisos y las reglas de negocio permanecen en la +consola. + +## Matriz de compatibilidad + +| **Consolas donde se ha probado** | Pandora FMS v8.0NG.800.4 (LTS), v8.0NG.804 (RRR) | +| --- | --- | +| **Consolas donde funciona** | Consolas que publiquen la API v2. La aceptación de un parámetro de filtrado la decide la consola por entidad, en el momento de la petición; las consolas antiguas pueden rechazar más. Consulte [Funciones de filtrado por entidad](#funciones-de-filtrado-por-entidad). | +| **Sistemas donde se ha probado** | Linux x86-64 | +| **Ejecutables disponibles para** | Linux (x86-64, ARM64), macOS (Intel, Apple silicon), Windows (x86-64) | + +## Requisitos previos + +**Un token de la API v2.** Créelo en la consola bajo el usuario cuyos permisos deba emplear la +herramienta. Cada comando se ejecuta con el perfil ACL de ese usuario. + +**Acceso de red a la consola** por HTTP o HTTPS. + +**La dirección del cliente autorizada en la ACL de la API.** La consola restringe el acceso a la API +por IP. Si la dirección no está en la lista, todas las llamadas fallan con: + +``` +401 IP 10.0.0.5 is not in ACL list +``` + +Es un ajuste de la consola, no de la herramienta: añada la dirección a la lista ACL de la API en la +configuración de la consola antes de continuar. + +## Configurar el acceso + +### Guardar un token + +`auth login` comprueba el token contra la consola **antes** de escribir nada. Si lo rechaza, no se +guarda ningún dato. + +```bash +pandora-cli auth login --token --url https://consola.ejemplo.com/pandora_console/api/v2/ +``` + +La URL por defecto es `http://localhost/pandora_console/api/v2/`. Debe apuntar a la raíz de la API y +terminar en `/api/v2/`. + +Las credenciales se escriben en `~/.pandora-cli/config.json`, con el directorio en `0700` y el +fichero en `0600`. El token se guarda codificado en base64, lo que evita que aparezca a simple vista +en la salida del terminal; lo que realmente lo protege son los permisos del fichero. La herramienta +se niega a leer un fichero de configuración con permisos más abiertos que `0600`. + +Defina `PANDORA_CLI_HOME` para guardar la configuración en otra ubicación. + +### Varias consolas + +Cada consola es un contexto con nombre. + +```bash +pandora-cli auth login --token --url https://prod/pandora_console/api/v2/ --context prod +pandora-cli auth login --token --url https://lab/pandora_console/api/v2/ --context lab --insecure + +pandora-cli auth context list +pandora-cli auth context use prod +pandora-cli user list --context lab # un comando contra otra consola +``` + +`--token` y `--url` también pueden pasarse directamente a cualquier comando. Usados así, el token no +se escribe nunca en disco, lo que resulta adecuado para un trabajo de integración continua que ya lo +tiene en un secreto. + +### Correlación de sesiones de IA + +Use un ID de sesión de IA opcional para adjuntar metadatos de correlación a las peticiones de la +API v2. Guárdelo en un contexto con nombre al iniciar sesión. Los tokens pasados como argumentos +pueden aparecer en el historial del shell o en la lista de procesos del sistema operativo. + +```bash +pandora-cli auth login --token '' --url https://console.example.com/pandora_console/api/v2/ --context prod --ai-session-id ai-session-example-001 +pandora-cli user list --context prod +``` + +Tras un inicio de sesión correcto, el primer comando guarda `ai_session_id` en el contexto de +destino en `~/.pandora-cli/config.json`. El comando posterior reutiliza ese ID sin repetir la +opción. + +El orden de resolución es **`--ai-session-id` explícito (incluido un valor vacío) → +`ai_session_id` del contexto seleccionado/actual → ausente**. Un ID no vacío envía +`X-Pandora-AI-Session` en cada petición de la API v2, incluidas la autenticación y la consulta de la +especificación de la consola. Un ID ausente o vacío omite la cabecera. Los caracteres de control se +rechazan. + +El inicio de sesión y los demás comandos tratan las sustituciones de forma distinta: + +| Invocación | Efecto sobre el ID guardado | +| --- | --- | +| `auth login --ai-session-id ` correcto | Guarda el ID explícito en el contexto de destino. | +| `auth login` correcto sin la opción | Conserva el ID previo de ese contexto. | +| `auth login --ai-session-id=` correcto | Borra el ID guardado de ese contexto; el campo vacío se omite del JSON. | +| Inicio de sesión fallido o ID no válido | No escribe nada; la configuración existente permanece sin cambios. | +| Cualquier otro comando con `--ai-session-id ` o `--ai-session-id=` | Sustituye o desactiva la cabecera solo para esa invocación; nunca modifica el ID guardado. | + +Por ejemplo, desactive la cabecera para una consulta sin borrar el ID guardado, o bórrelo mediante +un inicio de sesión correcto: + +```bash +pandora-cli user list --context prod --ai-session-id= +pandora-cli auth login --token '' --url https://console.example.com/pandora_console/api/v2/ --context prod --ai-session-id= +``` + +El ID es un metadato de correlación, no una credencial: no autentica al solicitante ni concede +permisos. El envío de la cabecera no demuestra que la consola la registre o la muestre en un +registro de auditoría. + +### Certificados autofirmados + +`--insecure` omite la verificación TLS. Nunca se aplica por defecto. Pasada a `auth login`, la +opción queda recordada para ese contexto; pasada a cualquier otro comando, se aplica solo a ese +comando. + +## Verificar + +```bash +pandora-cli auth status +``` + +``` +Context: prod +URL: https://consola.ejemplo.com/pandora_console/api/v2/ +Insecure: false +Config: /home/usuario/.pandora-cli/config.json +Token: valid + +Console specification: 282 operations, 46 entities (read 2026-09-22T09:12:37Z) +``` + +`Token: valid` indica que la consola lo aceptó. El comando termina con un código distinto de cero si +no fue así. Con `-o json` la salida son exactamente cinco valores — `context`, `url`, `insecure`, +`config` y `token` — sin la línea informativa que se muestra arriba en formato tabla. + +Después, consulte datos reales: + +```bash +pandora-cli user list +``` + +``` +IDUSER FULLNAME EMAIL ISADMIN DISABLED +admin Pandora admin@example.com true false + +1 shown, 1 total. +``` + +## Interpretar la salida + +La salida es una **tabla en un terminal** y **JSON cuando se redirige o se encadena**, de modo que +los scripts obtienen una salida analizable sin necesidad de indicar ninguna opción: + +```bash +pandora-cli user list # tabla +pandora-cli user list | jq '.[].idUser' # JSON +pandora-cli user list > usuarios.json # JSON +``` + +Fuerce un formato con `-o json`, `-o table` o `-o yaml`. + +Las líneas informativas como `1 shown, 1 total.` solo aparecen en formato tabla. En JSON y YAML se +suprimen, de manera que la salida encadenada siempre es válida. + +Los listados los pagina la consola. `1 shown, 1 total.` indica cuántas filas se han devuelto y +cuántas existen; use `--page` y `--size` para recorrer un resultado extenso. La paginación es +**basada en 1**: `--page 1` es la primera página. `--size` solo también devuelve la primera página, +porque la consola ignora un tamaño de página sin número de página en algunos extremos; la +herramienta envía ambos. + +### Funciones de filtrado por entidad + +`--where`, `--fields` y `--in` corresponden a parámetros de la API que cada entidad de la consola +implementa por su cuenta: la aceptación es **por entidad**, no por consola. `/user/list` puede +aceptar `fieldConditions` mientras que `/event/list` lo rechaza. La herramienta no mantiene ninguna +caché de capacidades por consola: envía siempre la petición y la consola responde. + +| Función | Opción | +| --- | --- | +| `fieldConditions` | `--where` | +| `requestedFields` | `--fields` | +| `multipleSearchString` | `--in` | + +Si la entidad no acepta el parámetro, la consola rechaza la petición con +`400 Field: ... is not a valid parameter` y la herramienta explica lo sucedido, indicando la opción +que envió el parámetro. La opción sigue siendo válida en las entidades que sí lo aceptan; solo falla +la petición rechazada: + +``` +Error: POST event/list failed: 400 Field: fieldConditions is not a valid parameter +--where (fieldConditions) is not available on this console. +The console at https://consola.ejemplo.com/pandora_console/api/v2/ rejects that parameter. +``` + +## Uso habitual + +### Filtrar un listado + +```bash +pandora-cli user list --filter isAdmin=true +pandora-cli user list --where 'fullName like admin' --sort fullName +pandora-cli user list --search backup +pandora-cli user list --in idUser=admin,root +pandora-cli user list --fields idUser,email --size 50 +``` + +Todas las opciones de filtrado son repetibles y se combinan con **AND**. Cuando el esquema declara el +campo como array, repetir `--filter` sobre el mismo campo acumula en un único parámetro de tipo +array en lugar de combinarse con AND: `--filter severity=4 --filter severity=2` envía +`{"severity":[4,2]}`. La excepción es un `null` explícito: se envía como nulo plano (nunca como +`[null]`), de modo que limpia el campo con independencia de su posición entre los flags repetidos. + +**Cada entidad tiene dos conjuntos de campos distintos.** `--filter` acepta cualquier campo de la +entidad, mientras que `--where`, `--fields` y `--in` aceptan un conjunto más reducido y propio de +cada entidad: en `agent-secondary-group` son únicamente `idAgent` e `idGroup`; en `user` es un +subconjunto fijo de 20 campos de los 81 de la entidad. Los dos conjuntos no están anidados: una +entidad puede aceptar en `--fields` un campo que no es un campo normal de la entidad. La herramienta +valida ambos localmente y enumera los nombres válidos cuando rechaza uno, así que conviene leer el +error en lugar de volver a probar a ciegas. Varias entidades — entre ellas `group`, `tag`, `profile`, +`token` y `data-translation` — aceptan un conjunto de campos `--where`/`--fields`/`--in` más amplio +que en versiones anteriores; ejecute `pandora-cli --help` para ver la lista exacta de la +versión instalada. + +`agent list` acepta además los contadores de módulos — `criticalCount`, `warningCount`, +`unknownCount`, `normalCount`, `notinitCount`, `totalCount` y `firedCount` — en `--fields`, +`--where` e `--in`, junto con las columnas propias de la entidad: + +```bash +pandora-cli agent list --fields idAgent,alias,criticalCount,totalCount +``` + +Las entidades nuevas siguen la misma regla. `policy` acepta `applyToSecondaryGroups`, +`createLinkedModules`, `description`, `forceApply`, `idGroup`, `idPolicy`, `name` y `status`; +`collection` acepta `description`, `idCollection`, `idGroup`, `name`, `shortName` y `status`; +`service` acepta `asynchronous`, `autoCalculate`, `cascadeProtection`, `cpsInhibit`, `critical`, +`description`, `evaluateSla`, `idGroup`, `idService`, `isFavourite`, `name`, `quiet`, +`serviceInterval`, `slaInterval`, `status`, `unknownAsCritical`, `utimestamp` y `warning`. El +conjunto de `token` incluye ahora `isPandoraAi`, junto a `idToken`, `idUser`, `label`, `lastUsage` y +`validity`. `--filter` sigue aceptando todos los demás campos de cada entidad. + +`module-alert list` admite un `idAgentModule` opcional. Con él, lista las alertas de ese módulo, +como antes. Sin él, lista todas las alertas de módulo de la consola: + +```bash +pandora-cli module-alert list +pandora-cli module-alert list --where 'timesFired = 1' +``` + +Las alertas de módulo también exponen un campo `status` — `fired`, `notFired`, `disabled` o +`allEnabled` —, utilizable con `--filter` (`--filter status=fired`), pero no con `--where`, +`--fields` ni `--in`. + +`event` es la única excepción: la herramienta no valida localmente `--where`, `--fields` ni `--in` +para esta entidad. Envía lo que se le indique y deja que decida la consola, porque el listado de +eventos de la consola no implementa `fieldConditions`, `requestedFields` ni `multipleSearchString` +para ningún campo. El rechazo, por tanto, llega siempre desde la consola, explicado de la misma +forma descrita en [Funciones de filtrado por entidad](#funciones-de-filtrado-por-entidad). + +El filtro `dateRange` de `event list` recibe una cadena JSON, no una cadena `" - "`: + +```bash +pandora-cli event list --filter 'dateRange={"preset":{"value":"last_24_hours"}}' +pandora-cli event list --filter 'dateRange={"start":{"mode":"relative","value":1,"unit":"hours"},"end":{"mode":"now"}}' +``` + +El formato anterior `" - "` ahora falla con `400 Invalid date range format. Must be +valid JSON`. + +En Windows PowerShell 5.1 (y en PowerShell 7 anterior a la 7.3), las comillas dobles internas de un +argumento se eliminan antes de llegar a `pandora-cli`, por lo que la consola recibe un JSON no válido +y responde con el mismo `400`. Escape cada comilla doble interna con una barra invertida: + +```powershell +pandora-cli event list --filter 'dateRange={\"preset\":{\"value\":\"last_24_hours\"}}' +``` + +Los valores se convierten a su tipo JSON: `true` y `false` pasan a booleanos, los dígitos a números +y `null` a nulo. Entrecomille para forzar una cadena: + +```bash +pandora-cli tag list --filter name='"42"' +``` + +### Crear y modificar + +```bash +pandora-cli user create --set idUser=jdoe --set fullName='Jane Doe' --set password=secret +pandora-cli user update jdoe --set email=jane@example.com +pandora-cli user delete jdoe --yes +``` + +`--set` es repetible. Para un cuerpo completo, lea el JSON desde un fichero o desde la entrada +estándar: + +```bash +pandora-cli user create --from-file usuario.json +cat usuario.json | pandora-cli user create --from-file - +``` + +`--set` y `--from-file` no pueden combinarse. + +Los valores de `--set` se convierten a su tipo JSON exactamente igual que los de los filtros. Por +tanto, un campo de texto cuyo valor parece un número se envía como número: `--set permissions=0755` +envía el número `755`. Entrecomille el valor para forzar una cadena, o envíe la carga con +`--from-file`: + +```bash +pandora-cli --set permissions='"0755"' +``` + +Cuando el esquema declara un campo como **array** — por ejemplo `severity` en `event-filter` o +`wildcardAgents` en `report-datasource` — un valor de `--set` se serializa como un array de un solo +elemento, y repetir la opción acumula elementos en ese array. Igual que con `--filter`, un `null` +explícito se envía como nulo plano y limpia el array acumulado. + +`--from-file` acepta un **array** JSON como cuerpo completo, no solo un objeto. Los extremos cuyo +cuerpo es una lista lo requieren, como `pandora-cli monitoring create` más abajo. Un BOM UTF-8 al +principio del fichero es tolerado, de modo que los ficheros escritos por editores de Windows +funcionan sin cambios. Un caso límite: el +esquema puede declarar un escalar donde el extremo de la consola espera un array (un desajuste +documentado, por ejemplo `position` en `report-design-page-widget`); escriba el array en el fichero y +envíelo con `--from-file`. + +`delete` pide confirmación. En una sesión no interactiva **se niega** en lugar de preguntar, de modo +que un script que haya olvidado `--yes` falla de forma visible en vez de borrar en silencio. + +Algunas entidades imponen reglas del lado del servidor que no aparecen en su lista de campos: +`agent create` necesita un grupo real — `idGroup=0` se rechaza con `400 Agent group is missing`; la +consola asigna el `name` del agente por su cuenta con independencia de la carga enviada, así que +`alias` es el campo que realmente controla la etiqueta; `module create` necesita `idModule` (el tipo +de servidor del módulo) junto con `idModuleType`, no solo las columnas indicadas en +`--where`/`--fields`/`--in`; y un usuario no administrador creado con `user create` necesita al menos +un perfil asignado con `user profile add` antes de poder iniciar sesión; una `event-alert-rule` +creada con `event-alert-rule create` necesita que la primera regla ordenada de la alerta tenga +`operation=NOP` — la consola rechaza cualquier otra operación en esa primera regla. +`module force-check` solicita una comprobación inmediata de un módulo de agente; la comprobación en +sí se completa de forma asíncrona, así que una llamada correcta devuelve `202` sin cuerpo. La +consola la rechaza con `400` en los tipos de módulo que no admiten una comprobación inmediata, como +los módulos data-push. La opción `--serverId`, opcional, apunta al módulo de un nodo federado desde +un metaconsole. + +### Envío de datos de monitorización + +`pandora-cli monitoring create` envía datos de agente a Pandora FMS. Su cuerpo es un **array** de +cargas con claves en snake_case — `agent_data` y `module_data`: + +```bash +cat > payload.json << 'EOF' +[ + { + "agent_data": {"agent_name": "web1", "address": "10.0.0.5", "interval": 300}, + "module_data": [ + {"name": "cpu_usage", "type": "generic_data", "data": 12.5}, + {"name": "mem_used", "type": "generic_data", "datalist": [{"value": 2048, "timestamp": "2026/09/07 11:00:00"}]} + ] + } +] +EOF +pandora-cli monitoring create --from-file payload.json +``` + +El agente se crea si no existe. `agent_name`, `address` e `interval` son obligatorios; la consola +rechaza la petición si falta cualquiera. Las demás claves de `agent_data` son opcionales. Cada entrada de +`module_data` necesita un `type`, por ejemplo `generic_data`; la consola rechaza la petición sin él. Una carga también +puede incluir `events`, `inventory_data`, `log_data`, `trap_data`, `discovery_data` y `cmd_data`. +Reenviar el mismo agente, módulo y marca de tiempo actualiza el valor existente en lugar de +duplicarlo. + +### Entidades anidadas + +Algunas entidades dependen de una entidad superior. Sus comandos reciben primero el identificador de +la entidad superior: + +```bash +pandora-cli report-design-page list 12 +pandora-cli report-design-page-widget list 12 3 +``` + +Los comandos `list` anidados que leen con un cuerpo de filtro también aceptan opciones de carga: sus +campos `--set` se serializan del mismo modo, de manera que un campo que el extremo declara como +array — como `requestedFields` — se acumula con flags repetidos: + +```bash +pandora-cli user profile list admin --set requestedFields=idUserProfile +``` + +`user profile get` y `user profile remove` reciben ese mismo `idUserProfile` — el id propio de la +asignación, no el id del perfil (`idProfile`). `user profile add` no ha cambiado y sigue recibiendo +`idProfile`: + +```bash +pandora-cli user profile get operator1 3 +pandora-cli user profile remove operator1 3 +``` + +**Cambio disruptivo**: las versiones anteriores recibían `idProfile` en `user profile get`. Cuando +el mismo perfil está asignado a un usuario en varios grupos, cada asignación tiene su propio +`idUserProfile`. + +### Políticas, colecciones y servicios + +`policy`, `collection` y `service` agrupan parte de sus comandos en **grupos hijos**. La sintaxis es +` `, y `pandora-cli --help` enumera los grupos de una +entidad: + +```bash +pandora-cli policy module list 7 +pandora-cli collection file upload 3 --file ./a.conf +pandora-cli service element add 2 --set description='Frontend CPU' --set idAgenteModulo=42 +``` + +Los grupos son `policy agent`, `policy alert`, `policy alert-action`, `policy collection`, +`policy group`, `policy log-module`, `policy module`, `policy plugin` y `policy queue`; +`collection file`, `collection folder` y `collection agent`; y `service element`. Las colecciones +también se asignan desde el lado del agente con `agent collection list`, `agent collection add` y +`agent collection remove`. + +**Quitar marca, no borra.** En una política, `remove`, `delete` y `bulk-delete` sobre un elemento +hijo (agente, alerta, colección, grupo, módulo de log, módulo o plugin) solo lo marcan como +`pendingDelete`. La eliminación se hace efectiva cuando se aplica la cola de la política, y +`restore` deshace la marca antes de que eso ocurra. `policy alert-action remove` y +`policy queue delete` no se marcan: actúan de inmediato. + +**La purga y la cola son asíncronas.** `policy purge` y las operaciones de `policy queue` encolan +trabajo y devuelven el control sin esperar. Una política no puede eliminarse mientras tenga entradas +pendientes en la cola: consulte `policy queue list` (o `policy queue summary`) y use +`policy queue clear`, o espere, antes de eliminarla. Tampoco puede eliminarse mientras tenga agentes +asignados: ejecute antes `policy purge` y espere a que la cola termine. + +**Las operaciones masivas de plugins requieren un array JSON.** `policy plugin bulk-delete`, +`bulk-disable`, `bulk-enable` y `bulk-restore` reciben un array de ids de plugin de nivel superior, +que `--set` no puede construir. Envíelo por la entrada estándar o desde un fichero con +`--from-file`; el resultado informa de los aciertos y errores por plugin: + +```bash +echo '[4,5]' | pandora-cli policy plugin bulk-enable 7 --from-file - +``` + +Los elementos hijo de una política se identifican por su propio id, que sigue al id de la política en +la línea de comandos (` `, ` `, etc.). Las +opciones que más se necesitan: + +| Grupo | Verbos | Opciones principales | +| --- | --- | --- | +| `policy agent` | `list`, `get`, `add`, `remove`, `restore` | `add`: `--set idAgent=`. | +| `policy group` | `list`, `get`, `add`, `remove`, `restore` | `add`: `--set idGroup=`. | +| `policy collection` | `list`, `available`, `get`, `add`, `remove`, `restore` | `add`: `--set idCollection=`. `available` lista las colecciones que aún no están vinculadas. | +| `policy module` | `list`, `get`, `create`, `update`, `delete`, `enable`, `disable`, `restore` | `create`: `--set name=...`, `--set moduleType=...`, `--set idModule=` y `--set idModuleType=`. | +| `policy log-module` | `list`, `get`, `create`, `update`, `delete`, `enable`, `disable`, `restore` | `create`: `--set collectorMode=...`, `--set moduleName=...`, `--set source=...` y `--set sourceType=...`. | +| `policy plugin` | `list`, `get`, `create`, `update`, `delete`, `enable`, `disable`, `restore`, `bulk-delete`, `bulk-disable`, `bulk-enable`, `bulk-restore` | `create`: `--set pluginExecution=`. Los verbos `bulk-*` reciben un array JSON (véase arriba). | +| `policy alert` | `list`, `get`, `create`, `update`, `delete`, `restore` | `create`: `--set idPolicyModule=` y `--set idAlertTemplate=`. `update`: `--set disabled=true`. | +| `policy alert-action` | `list`, `add`, `remove` | Reciben ` `. `add`: `--set idAlertAction=`, `--set firesMin=` y `--set firesMax=`. `remove` recibe además ``. | +| `policy queue` | `list`, `get`, `summary`, `add`, `apply-pending`, `clear`, `delete` | `add`: `--set operation=apply` y `--set idAgent=`. `apply-pending` encola los cambios pendientes. `clear` y `delete` piden confirmación salvo que se indique `--yes`. | + +`policy copy` recibe `--set name=...` y `--set idGroup=` para la política nueva; `policy purge` no +recibe opciones. + +```bash +pandora-cli policy agent add 7 --set idAgent=42 +pandora-cli policy queue apply-pending 7 +pandora-cli policy queue summary 7 +``` + +**Inmutables tras la creación.** `moduleType`, `idModule` e `idModuleType` de un módulo de política +no pueden cambiarse una vez creado; cree un módulo de política nuevo. + +**Las colecciones necesitan un agente remoto.** Asignar una colección a un agente +(`agent collection add`; `collection agent list` muestra el resultado) requiere un agente con +configuración remota (`remote=1`) disponible en la consola. En caso contrario, la consola responde +`Agent remote configuration is unavailable`, también con un agente que tiene `remote=1` pero aún no +tiene configuración remota. La asignación solo se registra en la configuración remota del agente; ejecute +`collection apply` tras cambiar los ficheros de una colección para que los agentes recojan el +paquete nuevo. + +**`isPandoraAi` en `token`** solo puede establecerse al crear el token. + +### Transferir ficheros + +Dos comandos de `collection` mueven el contenido de ficheros. Usan sus propias opciones, y +`--from-file` no se aplica a ellos. + +**Subida** (`collection file upload`) envía la petición como `multipart/form-data`. Indique cada +fichero con `--file `, o con `--file =` para nombrar el campo del formulario; la +opción es repetible y se requiere al menos una. Los campos de texto del formulario (`folder`, +`decompress`, `overwrite` y `permissions`) se pasan con `--set campo=valor` y se envían como +cadenas, por lo que no hace falta entrecomillarlos. `-v` nunca imprime el contenido de los ficheros. + +```bash +pandora-cli collection file upload 3 --file ./a.conf +``` + +**Descarga** (`collection file download`) devuelve bytes sin procesar, así que `--output-file ` +es obligatorio; `--output-file -` escribe en la salida estándar. Un fichero existente solo se +reemplaza con `--force`, y una descarga fallida no deja ningún fichero parcial. `--output-file` es el +destino: `-o/--output` sigue seleccionando el formato de salida. + +```bash +pandora-cli collection file download 3 --path a.conf --output-file ./a.conf +pandora-cli collection file download 3 --path a.conf --output-file ./a.conf --force +``` + +Los demás comandos de los grupos de ficheros de `collection` reciben el id de la colección y estas +opciones. `--path` es siempre relativa a la colección, nunca una ruta absoluta del servidor. + +| Comando | Opciones | +| --- | --- | +| `collection file list` | `--set folder=` es opcional; si se omite, lista la raíz. | +| `collection file read` | `--path ` (obligatoria). Imprime el contenido de texto del fichero. | +| `collection file create` | `--set path=` (obligatoria) y `--set content=`; sin `content` se crea un fichero vacío. | +| `collection file update` | `--set path=` y `--set content=` reemplazan el contenido de un fichero existente. | +| `collection file delete` | `--path ` (obligatoria) y `--yes`. | +| `collection folder create` | `--set path=` (obligatoria); `--set recursive=true` crea también las carpetas padre que falten. | +| `collection folder delete` | `--path ` (obligatoria) y `--yes`. La carpeta debe estar vacía. | +| `collection agent list` | Sin opciones. Lista los agentes asignados a la colección. | +| `collection apply` | Sin opciones. Genera de nuevo el paquete de la colección. | + +```bash +pandora-cli collection folder create 3 --set path=scripts --set recursive=true +pandora-cli collection file create 3 --set path=scripts/check.sh --set content='echo ok' +pandora-cli collection file read 3 --path scripts/check.sh +``` + +### Gráficas de módulo + +`module graph` pide a la consola que genere una gráfica de un módulo de agente. Las opciones +(`period`, `graphType`, `width`, `height` y otras) viajan en el cuerpo como campos `--set`. La +respuesta no es un flujo binario: lleva la imagen codificada en base64 en su campo `graph`, junto con su `mimeType` +(`image/png` o `image/jpeg`) y su `encoding` (`base64`). `period` se expresa en segundos +(mínimo 300; por defecto, un día). + +```bash +pandora-cli module graph 12 --set period=3600 -o json | jq -r .graph | base64 -d > graph.png +``` + +### Inspeccionar la API de la consola + +`spec` lee la descripción de la API que la propia consola publica sobre sí misma, de modo que puede +ver qué campos acepta una entidad sin abrir el `swagger.json` de la consola: + +```bash +pandora-cli spec list # esquemas que publica la consola +pandora-cli spec show EventFilter # un esquema con allOf resuelto: tipos, enums, readOnly +pandora-cli spec raw # el swagger.json completo de la consola +``` + +Para `create` y `update`, consulte el esquema de la entidad con `spec show `; para los +campos que acepta un filtro de listado, consulte el esquema de filtro correspondiente con +`spec show Filter`. La composición `allOf` está resuelta, de modo que los campos heredados +aparecen como propiedades propias del esquema. Los nombres de esquema son los que publica la consola +— `EventFilter`, `EventFilterFilter`, `ReportDataSource` —, que no son los nombres de entidad con +guiones de la herramienta; `spec list` muestra los nombres exactos y `spec show` sugiere la +coincidencia más cercana si escribe mal uno. La salida admite el formato habitual `-o json`, `-o +table` o `-o yaml`. + +### Documentación y uso por agentes + +```bash +pandora-cli docs # referencia completa de comandos de esta versión +pandora-cli docs --out ref.md +``` + +Para agentes de programación que trabajan en un terminal, instale una skill de uso que describe esta +versión: + +```bash +pandora-cli skill install # escribe ~/.claude/skills/pandora-cli/SKILL.md +pandora-cli skill install --print # muestra el contenido sin instalarlo +pandora-cli skill install --force # sobrescribe una skill existente +``` + +Vuelva a ejecutarlo tras una actualización para que la skill siga correspondiéndose con el +ejecutable. + +Use un ID de correlación por sesión de IA y cámbielo al iniciar una sesión nueva. Guárdelo con +`auth login --ai-session-id ` para reutilizarlo en el contexto de destino. En los demás comandos, +`--ai-session-id ` es una sustitución temporal y `--ai-session-id=` desactiva la cabecera para +esa invocación sin borrar el ID guardado. Las llamadas posteriores sin la opción reutilizan el ID +guardado. Consulte la sección de correlación de sesiones de IA para conocer el comportamiento de +guardado y borrado durante el inicio de sesión. + +### Diagnosticar una llamada + +`--verbose` traza la línea de petición, el cuerpo enviado y el estado de la respuesta por la salida +de error estándar, dejando limpia la salida estándar para poder encadenarla: + +```bash +pandora-cli user list --filter isAdmin=true -v -o json > usuarios.json +``` + +``` +→ POST https://consola.ejemplo.com/pandora_console/api/v2/user/list +→ body: {"isAdmin":true} +← 200, 1834 bytes +``` + +## Resolución de problemas + +| Síntoma | Causa y solución | +| --- | --- | +| `401 ... token was rejected` | El token es incorrecto o ha caducado. Vuelva a ejecutar `auth login`. | +| `401 IP ... is not in ACL list` | La dirección del cliente no está autorizada en la ACL de la API. Añádala en la configuración de la consola. | +| `403 ... lacks permission` | El token es válido, pero el perfil ACL del usuario propietario no permite la operación. | +| `404 ... or the API base URL is wrong` | Revise `auth status`; la URL debe terminar en `/api/v2/`. | +| `TLS verification failed` | Certificado autofirmado. Repita con `--insecure` o guárdelo para el contexto al iniciar sesión. | +| `has permissions 0644` | El fichero de configuración es legible por otros usuarios. Ejecute `chmod 0600 ~/.pandora-cli/config.json`. | +| `--fields ... is not available on this console` | La entidad no implementa ese parámetro de filtrado; la consola rechazó la petición y la herramienta indicó la opción que lo envió. Consulte [Funciones de filtrado por entidad](#funciones-de-filtrado-por-entidad). | +| `unknown field "..."` | El campo no existe en esa entidad. El mensaje enumera los nombres válidos. | +| `the "..." entity does not exist on this console` | La consola no publica esa entidad. Ejecute `auth status --refresh` si se ha actualizado. | +| `--... is required by this endpoint` | No se ha indicado un parámetro que la API declara como obligatorio (por ejemplo `--path` en `collection file download`). | +| Una política no puede eliminarse | La política aún tiene entradas pendientes en la cola o agentes asignados. Consulte `policy queue list` y use `policy queue clear` o espere; ejecute `policy purge` para desasignar sus agentes. | +| Un elemento hijo de una política sigue apareciendo tras `remove` | La eliminación solo lo marca como `pendingDelete` hasta que se aplica la cola de la política. Use `restore` para deshacerla. | +| Una colección no puede asignarse a un agente (`Agent remote configuration is unavailable`) | El agente necesita configuración remota (`remote=1`) disponible en la consola. | +| Un valor como `0755` llega como `755` | `--set` convierte los valores de aspecto numérico. Use `--set permissions='"0755"'` o `--from-file`. | + +Un comando termina con `0` si tiene éxito y con un valor distinto de cero si falla, de modo que +puede emplearse directamente en el flujo de control de un script. + +## Referencia + +### Opciones globales + +| Opción | Significado | +| --- | --- | +| `--context ` | Contexto con nombre que se debe usar. Por defecto, el actual. | +| `--url ` | URL base de la API, que prevalece sobre el contexto. | +| `--token ` | Token solo para este comando. No se escribe nunca en disco. | +| `--ai-session-id ` | ID de correlación opcional; prevalece sobre el contexto seleccionado/actual. Un `auth login` correcto lo guarda; los demás comandos lo usan de forma temporal. `--ai-session-id=` omite la cabecera y borra el ID guardado solo si el inicio de sesión es correcto. | +| `--insecure` | Omite la verificación del certificado TLS. | +| `-o, --output json\|table\|yaml` | Formato de salida. Tabla en terminal, JSON en el resto de casos. | +| `-v, --verbose` | Traza las peticiones por la salida de error estándar. | +| `--timeout ` | Tiempo máximo de la petición. Por defecto, `30s`. | + +### Opciones de listado + +| Opción | Efecto | Ejemplo | +| --- | --- | --- | +| `--filter =` | Igualdad de campo. | `--filter isAdmin=true` | +| `--where ' '` | Condición avanzada. | `--where 'fullName like admin'` | +| `--search ` | Búsqueda de texto libre. | `--search backup` | +| `--in =` | Campo dentro de una lista de valores. | `--in idUser=admin,root` | +| `--fields ` | Limita los campos devueltos. | `--fields idUser,email` | +| `--page ` | Número de página, basada en 1 (`--page 1` es la primera). | `--page 2` | +| `--size ` | Filas por página. | `--size 50` | +| `--sort ` | Campo por el que ordenar. | `--sort fullName` | +| `--order asc\|desc` | Sentido de la ordenación. | `--order desc` | + +Operadores admitidos por `--where`: `=`, `like`, `regex`, `in`, `between`, `is_not_empty`. Para una +columna JSON, indique una ruta con `--where ': '`. + +### Opciones de escritura + +| Opción | Efecto | +| --- | --- | +| `--set =` | Un campo del cuerpo. Repetible. | +| `--from-file ` | Lee el cuerpo JSON completo de un fichero, o `-` para la entrada estándar. | +| `--yes` | Omite la confirmación en un comando destructivo. | + +### Opciones de transferencia de ficheros + +| Opción | Efecto | +| --- | --- | +| `--file ` o `--file =` | Fichero que se sube con un comando multipart (`collection file upload`). Repetible; se requiere al menos una. | +| `--output-file ` | Destino de un comando de bytes sin procesar (`collection file download`). Obligatorio; `-` escribe en la salida estándar. | +| `--force` | Reemplaza un `--output-file` existente. | + +### Comandos de autenticación + +| Comando | Efecto | +| --- | --- | +| `auth login` | Valida un token y lo guarda en un contexto. Si tiene éxito, un `--ai-session-id` explícito guarda el ID en ese contexto, su omisión conserva el ID previo y `--ai-session-id=` lo borra. Un inicio de sesión fallido o un ID no válido no escribe nada. | +| `auth status` | Muestra el contexto activo, verifica el token e informa de la especificación publicada por la consola. Con `--refresh` vuelve a leer esa especificación. | +| `auth context list` | Enumera los contextos guardados. | +| `auth context use ` | Selecciona el contexto actual. | +| `auth logout [contexto]` | Elimina un contexto guardado. | + +### Entidades + +Cada entidad admite los verbos indicados. Ejecute `pandora-cli --help` para conocer sus +comandos y argumentos exactos, y `pandora-cli docs` para la referencia completa de la versión +instalada. + +| Entidad | Contenido | Verbos | +| --- | --- | --- | +| `agent` | Agentes de monitorización | `list`, `get`, `create`, `update`, `delete` + 4 más (`status` y el grupo `collection`) | +| `agent-extended-data` | Datos extendidos asociados a agentes | `list`, `get`, `create`, `update`, `delete` | +| `agent-secondary-group` | Grupos secundarios de un agente | `list`, `create`, `delete` | +| `alert-action` | Acciones de alerta | `list`, `get`, `create`, `update`, `delete` + 1 más | +| `alert-calendar` | Calendarios de alerta | `list`, `get`, `create`, `update`, `delete` | +| `alert-command` | Comandos de alerta | `list`, `get`, `create`, `update`, `delete` + 1 más | +| `alert-special-day` | Días especiales de un calendario de alerta | `list`, `get`, `create`, `update`, `delete` | +| `alert-template` | Plantillas de alerta | `list`, `get`, `create`, `update`, `delete` + 1 más | +| `bulk-draft` | Borradores de operaciones masivas | `list`, `get`, `delete` + 1 más | +| `bulk-queue` | Cola de operaciones masivas | `list`, `get`, `delete` | +| `collection` | Colecciones de ficheros distribuidas a los agentes | `list`, `get`, `create`, `update`, `delete` + 11 más (`apply` y los grupos `file`, `folder` y `agent`) | +| `dashboard` | Dashboards | `list`, `get`, `create`, `update`, `delete` | +| `dashboard-widget` | Widgets colocados en un dashboard | `list`, `get`, `create`, `update`, `delete` | +| `data-translation` | Definiciones de traducción de datos | `list`, `get`, `create`, `update`, `delete` | +| `event` | Eventos de monitorización | `list`, `get`, `create`, `update`, `delete` + 12 más | +| `event-alert` | Alertas de evento | `list`, `get`, `create`, `update`, `delete` | +| `event-alert-action` | Acciones de una alerta de evento | `list`, `get`, `create`, `update`, `delete` | +| `event-alert-rule` | Reglas que disparan una alerta de evento | `list`, `get`, `create`, `update`, `delete` | +| `event-filter` | Filtros de eventos guardados | `list`, `get`, `create`, `update`, `delete` | +| `event-tag` | Etiquetas de eventos | `list`, `get`, `create`, `update`, `delete` | +| `group` | Grupos de agentes | `list`, `get`, `create`, `update`, `delete` | +| `module` (alias `agent-module`) | Módulos de agente | `list`, `get`, `create`, `update`, `delete` + 2 más (`force-check`, `graph`) | +| `module-alert` | Alertas asignadas a un módulo de agente | `list`, `get`, `create`, `update`, `delete` | +| `module-alert-action` | Acciones que dispara una alerta de módulo de agente | `list`, `get`, `create`, `update`, `delete` | +| `module-data` | Datos históricos de un módulo de agente | `list`, `get` + 1 más | +| `module-group` | Grupos de módulos | `list`, `get`, `create`, `update`, `delete` | +| `module-state` | Estado actual de sondeo de los módulos de agente | `list`, `get` | +| `module-tag` | Etiquetas asociadas a un módulo de agente | `list`, `get`, `create`, `delete` | +| `module-type` | Tipos de módulo | `list`, `get` | +| `monitoring` | Envío de datos de monitorización | `create` | +| `pandora-itsm-inventory` | Inventario de Pandora ITSM | `list`, `get` | +| `policy` | Políticas aplicadas a agentes | `list`, `get`, `create`, `update`, `delete` + 62 más (`copy`, `purge` y los grupos `agent`, `alert`, `alert-action`, `collection`, `group`, `log-module`, `module`, `plugin` y `queue`) | +| `profile` | Perfiles ACL | `list`, `get`, `create`, `update`, `delete` | +| `report-datasource` | Orígenes de datos de informes | `list`, `get`, `create`, `update`, `delete` | +| `report-datasource-agent` | Agentes asociados a un origen de datos | `list`, `get`, `create`, `update`, `delete` | +| `report-datasource-group` | Grupos asociados a un origen de datos | `list`, `get`, `create`, `update`, `delete` | +| `report-design` | Diseños de informe | `list`, `get`, `create`, `update`, `delete` + 5 más | +| `report-design-page` | Páginas de un diseño de informe | `list`, `get`, `create`, `update`, `delete` | +| `report-design-page-widget` | Widgets de una página de diseño de informe | `list`, `get`, `create`, `update`, `delete` | +| `report-design-report` | Informes de un diseño de informe | `list`, `get`, `create`, `update`, `delete` | +| `report-design-template` | Plantillas de un diseño de informe | `list`, `get`, `create`, `update`, `delete` | +| `service` | Servicios | `list`, `get`, `create`, `update`, `delete` + 5 más (el grupo `element`) | +| `siem-group` | Grupos SIEM | `list`, `get`, `create`, `update`, `delete` | +| `siem-rule` | Reglas SIEM | `list`, `get`, `create`, `update`, `delete` + 4 más | +| `tag` | Etiquetas de módulos | `list`, `get`, `create`, `update`, `delete` | +| `token` | Tokens de la API | `list`, `get`, `create`, `update`, `delete` | +| `user` | Usuarios de la consola y sus perfiles asignados | `list`, `get`, `create`, `update`, `delete` + 5 más | +| `widget` | Widgets de dashboard | `list`, `get` | + +Las entidades que conoce un ejecutable son las de la versión de la API con la que se construyó. Una +consola más reciente que el ejecutable puede publicar más; `pandora-cli auth status` informa de lo +que publica la propia consola. + +### Ficheros y variables de entorno + +| Ruta o variable | Finalidad | +| --- | --- | +| `~/.pandora-cli/config.json` | Contextos y tokens guardados. Permisos `0600`. | +| `~/.pandora-cli/schema-.json` | Descripción almacenada de la API de esa consola. | +| `PANDORA_CLI_HOME` | Cambia el directorio de configuración. | +| `CLAUDE_CONFIG_DIR` | Cambia dónde escribe `skill install`. | + +Campo opcional en cada contexto de `config.json`: + +| Nombre | Obligatorio | Por defecto | Descripción | +| --- | --- | --- | --- | +| `ai_session_id` | No | Ausente | ID de correlación reutilizado cuando se omite `--ai-session-id`. Un valor no vacío envía `X-Pandora-AI-Session`; un valor vacío omite la cabecera. Un inicio de sesión correcto puede guardarlo o borrarlo; un campo vacío se omite del JSON guardado. Los contextos existentes sin este campo no necesitan cambios. |