---
title: "alpacon exec"
description: "Run commands or verified scripts with Alpacon CLI. Find account, approval, and file flags, background execution examples, and commands to retrieve results."
---

> Full documentation index: https://docs.alpacax.com/llms.txt

# alpacon exec

Run a command or verified script on a remote server.

## Usage

`alpacon exec [flags] [USER@]SERVER [--] [COMMAND...]`

`alpacon exec [command]`

## Key facts

- Place every CLI flag before the server name.
- Use `--` after the server to separate the remote command.
- Use `--detach` for background execution and `exec logs JOB_ID` for results.
- Use `--file` to submit a script for verified execution.

## Flags

### Command and account

| Flag | Type | Description |
| --- | --- | --- |
| `-u, --username` | `string` | Specify the username for command execution. |
| `-g, --groupname` | `string` | Specify the group name for command execution. |
| `--env` | `strings` | Pass `KEY` to read a value from your shell, or `KEY=VALUE` for a literal value. Repeatable. Use the key-only form for secrets; literal values remain in local command history. |
| `--work-session` | `string` | Attach this command to a work-session. Overrides the workspace's active session set via 'alpacon work-session use'. |
| `--purpose` | `string` | Explain this command’s purpose in up to 2,000 characters. State facts specific to this host; purpose does not reduce the command’s risk. |

### Script execution

| Flag | Type | Description | Default |
| --- | --- | --- | --- |
| `--file` | `string` | Absolute script path on the server. Reads matching local content (up to 64 KB); arguments follow `--`. Cannot use a command line or `--env`. | — |
| `--file-from` | `string` | Read the script from this local path. Its contents must match the server file. | — |
| `--upload` | `bool` | Write the local script to `--file` before submitting it. Existing files need `--overwrite`; the path cannot contain `.`, `..`, repeated slashes, or a trailing slash. | `false` |
| `--overwrite` | `bool` | With `--upload`, replace an existing file while keeping its owner and mode. | `false` |
| `--from-server` | `bool` | Read the script on the server as the selected account and group. Cannot combine with `--upload` or `--file-from`. | `false` |
| `--interpreter` | `string` | Absolute interpreter path for `--file`. | `/bin/bash` |
| `--reuse-days` | `int` | Propose 1–366 days of approval reuse for `--file`. The approver decides; requests above the workspace limit are refused. | — |

### Approval and output

| Flag | Type | Description | Default |
| --- | --- | --- | --- |
| `--detach` | `bool` | Return the job ID without waiting for completion. Read results with `exec logs JOB_ID`; an agent command may still wait for its purpose. | `false` |
| `--wait` | `bool` | Wait and retry a sudo command until console approval or timeout (5 minutes by default). | `false` |
| `--wait-approval` | `string` | Set a custom approval wait, such as `30m`. Implies `--wait`; the usual wait is `5m`. | — |
| `-h, --help` | `bool` | help for exec | `false` |
| `--output` | `string` | Output format: table or json | `table` |

## Examples

Execute a command on a server

```bash
alpacon exec my-server ls -la /var/log
```

Execute as a specific user

```bash
alpacon exec admin@my-server cat /etc/hostname
alpacon exec -u admin my-server cat /etc/hostname
```

Execute with a specific group

```bash
alpacon exec -g developers my-server whoami
```

Use `--` to pass flags to the remote command

```bash
alpacon exec root@db-server -- docker exec postgres psql -U myproject -d myproject
alpacon exec my-server -- grep -r "pattern" /var/log
```

Run multiple commands—the quotes keep `&&` from being interpreted by your local shell

```bash
alpacon exec my-server -- "df -h && free -m"
```

Shell metacharacters (`;`, `|`, `&`, `$`) are interpreted by your local shell first—quote the remote command to send them to the server, where the remote shell interprets them again. To pass one as a literal character, add inner quotes so the remote shell does not interpret it either

```bash
alpacon exec my-server -- "echo 'hello;world'"
```

Attach the command to a specific work session

```bash
alpacon exec --work-session 11111111-2222-3333-4444-555555555555 my-server -- df -h
```

Pass an environment variable to the remote command

Use `--env=KEY=VALUE` to pass a value, or `--env=KEY` to copy it from your local shell. If the local variable is unset, the CLI warns and skips it.

`--env` keys must match `[A-Za-z_][A-Za-z0-9_]*`. Keys matching the platform’s denied names or prefixes are refused case-insensitively with `command_dangerous_env`; invalid names are refused with `command_invalid_env`. Only string values are accepted, with at most 64 keys, at most 4096 characters per value and no NUL characters; violations are refused with `command_invalid_env`. See [Command environment policy](/reference/api/commands/#command-environment-policy) for the full list.

```bash
alpacon exec --env="KEY1=VALUE1" --env="KEY2=VALUE2" my-server -- printenv KEY1
```

Read a secret from the current shell without putting it on the command line or in the audit log

```bash
alpacon exec --env="PGPASSWORD" db-server -- psql -h localhost -U app -c 'SELECT 1'
```

If a secret ends up on the command line anyway—a secret-like `KEY=VALUE` pair, a password flag (e.g. `-pSecret123`), or a connection string with an embedded password—the server rejects the command with `command_inline_credential` before it runs. Move the secret to `--env` instead.

## Details

Execute a command directly on a remote server without opening an interactive terminal session. This is useful for running one-off commands, automation scripts, or retrieving output from a server.

All flags must be placed before the server name—everything after the server name is treated as the remote command. Use `--` to separate the remote command explicitly, so its flags (such as `-U` or `-d`) are not interpreted as `alpacon` flags.

## Subcommands

- `alpacon exec ls`: List recent command executions.
- `alpacon exec logs JOB_ID`: Fetch an asynchronous execution result.
- `alpacon exec purpose JOB_ID PURPOSE`: Answer a held command’s purpose request.

## exec ls

List recent remote command executions, most recent first.

`alpacon exec ls [flags]`

**Aliases**: `ls`, `list`

| Flag | Type | Description | Default |
| --- | --- | --- | --- |
| `-h, --help` | `bool` | help for ls | `false` |
| `-s, --server` | `string` | Filter by server name | — |
| `-t, --tail` | `int` | Number of command entries to show, newest first | `25` |
| `-u, --user` | `string` | Filter by requesting user | — |
| `--output` | `string` | Output format: table or json | `table` |

List the 25 most recent executions

```bash
alpacon exec ls
```

Narrow to one server and one user

```bash
alpacon exec ls --tail 10 --server my-server --user admin
```

`--tail` returns exactly the number of entries you ask for—`--tail 250` gets you 250 entries.

## exec purpose

When a command from an AI agent's work session would wait for a person, Alpacon may hold it and ask what it is for instead. `alpacon exec` then exits with code **7** and prints the job ID. Answer within about a minute and the command is judged again with your answer in hand; if you don't answer, it continues on its usual path. Only the requester who submitted the command can answer.

`alpacon exec purpose JOB_ID PURPOSE [flags]`

Answer a held command

```bash
alpacon exec purpose a1b2c3d4-5678-abcd-ef01-234567890abc \
  'The host clock is 40s ahead, so the renewed cert reads as not-yet-valid.'
```

To skip the question, state the purpose when you run the command

```bash
alpacon exec --purpose 'chronyd drifted; the cert reads as future-dated' \
  prod-web -- systemctl restart chronyd
```

A useful purpose states a fact about this server that the work session's description doesn't already say. It can't lower a command's own risk.

## Verified file execution

Use `--file` to run a script on the target server, instead of typing a command line. The reviewer sees the exact bytes you are about to run, and the platform makes sure the server executes those same bytes—not whatever happens to be at that path by the time the command runs.

`--file PATH` takes the absolute path of the script on the target server. The CLI reads the script's content from the same path on your local machine, unless you pass `--file-from LOCAL_PATH` to read it from somewhere else. Either way, the local copy must be byte-identical to the file on the server, or the agent refuses to run it. Two flags save you from putting the script in both places by hand:

- `--upload` writes the local script to the `--file` path on the server, then submits the same bytes, in one step. The file is written as the account and group the script runs as (`-u` or `USER@`, `-g`, or the server's default account when neither is given); a new file takes that account's umask, missing directories are created, and no execute bit is needed. A file already at that path is refused unless you pass `--overwrite`, and an overwritten file keeps its owner and mode. The path must be clean: no `.` or `..` and no repeated or trailing slash. A failed write stops the run before anything is submitted; a successful write stays on the server even if the submission is then refused.
- `--from-server` reads the script from the `--file` path on the server, as the account and group the script runs as, and submits those bytes, so no local copy is needed. A file that cannot be read, is empty, exceeds 64 KB, or is not UTF-8 text is refused before anything is submitted. `--from-server` cannot be combined with `--upload` or `--file-from`.

In both cases the agent still checks the file on the server against the submitted bytes when it runs.

`--interpreter PATH` sets the interpreter that runs the script (default `/bin/bash`) and must be an absolute path. Script arguments go after `--`; `--file` does not take a command line or `--env`.

An approval binds those exact bytes, on that server, as that account, with those arguments—not "the file in general". A reviewer can mark an approval as standing, and an unchanged re-run then stops asking anyone; one changed byte sends it back for review.

`--reuse-days N` proposes how long a standing approval stays reusable, from 1 to 366 days. A proposal is not a grant: the approver decides whether to grant reuse at all. A standing approval always expires, after the proposed days or at the workspace ceiling, which is 1 to 366 days (90 by default). If `N` is above the ceiling, the server refuses the request with `file_exec_reuse_exceeds_max` rather than shortening it; resubmit with a shorter `--reuse-days` or none. Without the flag, the request proposes no duration, and the approver may still grant reuse up to the ceiling. `--reuse-days` requires `--file`.

The reviewer sees the script's arguments along with its content, so never put a secret in an argument or in the script itself. Have the script read it from an environment variable or a file on the host at run time. The server refuses a script that carries a credential, the same way it refuses a command line that does. The script itself is limited to 64 KB.

Run a script the reviewer can read, verified byte-for-byte on the server:

```bash
alpacon exec --file /opt/deploy.sh root@prod-web -- --fast
```

Read the local copy from a different path and choose an interpreter:

```bash
alpacon exec --file /opt/deploy.sh --file-from ./deploy.sh --interpreter /bin/sh prod-web
```

Run a script that exists only on the server:

```bash
alpacon exec --file /opt/deploy.sh --from-server root@prod-web -- --fast
```

Write a local script to the server and run it, in one step:

```bash
alpacon exec --upload --file /opt/deploy.sh --file-from ./deploy.sh root@prod-web -- --fast
```

Propose that the approval stay reusable for 30 days:

```bash
alpacon exec --file /opt/deploy.sh --reuse-days 30 root@prod-web -- --fast
```

For multi-step work in a container, use a [verified shell script with embedded code sent through stdin](/use/work-sessions/commands/file-execution/#run-reviewed-code-inside-a-container).

## Asynchronous execution

Use `--detach` to submit a command and return immediately instead of waiting for it to finish. The CLI prints `Job submitted: JOB_ID` to stdout (or `{"job_id": "..."}` with `--output json`).

```bash
alpacon exec --detach web-server -- apt-get update
```

Retrieve the result later with `alpacon exec logs`:

```bash
alpacon exec logs a1b2c3d4-5678-abcd-ef01-234567890abc
```

`JOB_ID` must be a UUID. `exec logs` reports the job's status as follows:

| Job status | Exit code |
| --- | --- |
| Running, queued, delivered, verifying, acknowledged, or scheduled | 0; check the same job again later |
| Awaiting purpose, if your workspace asks for one | 7 |
| Awaiting approval | 4 |
| Rejected | 6 |
| Stuck, error, or cancelled | 1 |
| Finished | The remote command's exit code |

A 0 while the command is still running does not mean it finished. For work that may take longer than about 10 minutes, use `--detach`: a foreground `exec` reports stuck and exits 1 after 10 minutes without a result following acknowledgment or delivery, while the command keeps running on the server for up to 30 minutes. See [long-running commands](/use/work-sessions/commands/run/#long-running-commands).

## Exit codes

For a finished command, `alpacon exec` returns the remote command's exit code. CLI failures and held commands have these outcomes:

- 1: general failure, including stuck, error, cancelled, the CLI giving up its wait for a result (`client_timeout`, set by `ALPACON_EXEC_TIMEOUT`), or an inline credential refusal.
- 2: the CLI rejected the command line before sending anything, such as an unknown flag, an invalid job ID, or `exec ls` with a `--tail` of zero or less. Fix the command line and run it again. A finished remote command can also exit 2 on its own; with `--output json`, a rejected command line is the one that prints an error envelope with `usage_error`.
- 6: rejected, or not approved before the request expired.
- 7: purpose required, if your workspace asks for one. Answer with `alpacon exec purpose JOB_ID PURPOSE`.

See [command troubleshooting](/use/work-sessions/commands/troubleshooting/) for recovery steps.

Exit code 3 indicates the command was denied by the work session gate (for example, no active session or the session does not cover the target server). With `--output json`, a machine-readable diagnostic is printed to stderr. See [Gate errors](/reference/cli/work-session/#gate-errors) for the error codes.

Exit code 4 indicates the sudo command is pending human approval. Approve it in the Alpacon console, then re-run—or pass `--wait` to block until it is approved. If `--wait` ends before anyone decides, because the wait timed out or the CLI could not read the approval status, the command is still pending and the CLI also exits 4. With `--output json`, the CLI emits `{"status": "pending_approval", ...}` on stdout. The message also names the approval request, its deadline and a status command when the server sends them; see [held sudo approval](#held-sudo-approval).

A command held for approval in the Alpacon console also exits with code 4, and so does a `--wait` on it that ends before anyone decides. The exception is a run where the CLI warns that real-time output is unavailable and falls back to polling: there, a `--wait` that runs out exits 1 with `client_timeout`. When that command runs a script on the server, such as `bash /opt/deploy.sh`, the pending-approval message also suggests the `--file --from-server` form of it; a sudo request waiting for approval gets no suggestion. If the command named its interpreter by a bare name such as `bash`, the suggestion carries an `--interpreter` placeholder; replace it with the absolute path that `command -v bash` prints on the server. The suggestion is left out when the command used `--env`. The held command stays queued and runs if approved, and the CLI cannot cancel it. Cancel it in the Alpacon console's [command history](/use/audit/events/commands/) before you submit the suggested form, or the script waits on two approval requests.

When the server sends no `file_execution_suggestion` but reports that the held command line carries a script body, the pending-approval message suggests an `--upload --file` template instead. A `file_execution_suggestion` the CLI cannot render as a `--file --from-server` command still takes precedence, so that case gets neither form. A script body is a multi-line program passed to an interpreter such as `python -c` or `bash -c`, a heredoc, or an encoded body decoded into an interpreter (such as `base64 -d | bash`); a plain one-line pipeline such as `cat x.py | python3` does not count, and chaining commands with `&&` does not count by itself. The template is `alpacon exec --upload --file /path/to/script.sh --file-from ./script.sh SERVER`, keeping any `-u`, `-g` and `--work-session` flags you gave. Save the body to the local file and fill in the paths. For code that runs inside a container, put the container command and the program in that one script, as in [running reviewed code inside a container](/use/work-sessions/commands/file-execution/#run-reviewed-code-inside-a-container). The approver then reviews the script's content, and a standing approval can let unchanged re-runs skip review; the first run still waits for approval. The template is not the held command rewritten, and the same rule applies: cancel the held command before you submit the script.

## Held sudo approval

A `sudo` that needs an approval is denied at once, and `alpacon exec` exits 4 with the approval request left open. When the server names the approval that holds the command, the pending-approval message lists it after the re-run command and the console note:

- `Approval request: ID`: the approval request's ID, for reference. Left out when the ID the server sent cannot be shown as is. Reading the approval request itself takes access that the command does not; see [sudo approval](/reference/api/commands/#sudo-approval) in the API reference.
- `The approval must be decided by DEADLINE`: the deadline, in RFC 3339. Left out when the server sets no deadline.
- `alpacon api PATH`: reads the command's own detail, where `sudo_grant_status` reads `authorized` once the request is approved. Left out when the server's path is not a plain API path.

The plain output goes to stderr:

```text
Warning: Approval required—a human must approve this sudo command in the Alpacon web console. Re-run after approval, or use --wait (or --wait-approval DURATION for a longer wait) to block until it is approved.
  alpacon exec web-server -- sudo systemctl restart nginx
  Approve it out of band in the Alpacon console (web/Slack). Where supported, pass --wait (or --wait-approval DURATION for a longer timeout) on the original command to block until approval.
  Approval request: 3f1c9a2e-7b4d-4e8a-9c6f-0d2b5e8a1f47
  The approval must be decided by 2027-06-30T17:20:00+09:00
  alpacon api /api/events/commands/a1b2c3d4-5678-abcd-ef01-234567890abc/  # Where to read the command's sudo_grant_status while waiting; once it reads authorized, re-run the command
```

With `--output json`, `request_id` is the approval request's ID, and `next_actions` carries the same lines in the same order on stdout:

```json
{
  "ok": false,
  "status": "pending_approval",
  "exit_code": 4,
  "message": "Approval required—a human must approve this sudo command in the Alpacon web console. Re-run after approval, or use --wait (or --wait-approval DURATION for a longer wait) to block until it is approved.",
  "request_id": "3f1c9a2e-7b4d-4e8a-9c6f-0d2b5e8a1f47",
  "context": {
    "request_id": "3f1c9a2e-7b4d-4e8a-9c6f-0d2b5e8a1f47"
  },
  "next_actions": [
    {
      "command": "alpacon exec web-server -- sudo systemctl restart nginx"
    },
    {
      "description": "Approve it out of band in the Alpacon console (web/Slack). Where supported, pass --wait (or --wait-approval DURATION for a longer timeout) on the original command to block until approval."
    },
    {
      "description": "Approval request: 3f1c9a2e-7b4d-4e8a-9c6f-0d2b5e8a1f47"
    },
    {
      "description": "The approval must be decided by 2027-06-30T17:20:00+09:00"
    },
    {
      "command": "alpacon api /api/events/commands/a1b2c3d4-5678-abcd-ef01-234567890abc/",
      "description": "Where to read the command's sudo_grant_status while waiting; once it reads authorized, re-run the command"
    }
  ]
}
```

Approval does not resume the denied command. Once `sudo_grant_status` reads `authorized`, run the command again. To have the CLI wait instead, pass `--wait` (or `--wait-approval DURATION`) when you first run the command: the CLI waits on `sudo_grant_status` and runs the command again once it is approved. If the wait ends while the request is still open, the CLI exits 4 with the details from its last status read.

While the request is open, running the same command again shares that request, and only the first command reports its status. So adding `--wait` to a re-run does not wait on the open request: it times out even after the request is approved. Read the first command with its `alpacon api` line instead, and run the command again once `sudo_grant_status` reads `authorized`.

An approval given after the deadline cannot be used. Once the deadline has passed, the deadline line becomes `The approval deadline (DEADLINE) has passed; an approval given now cannot be used, so re-run the command to request a new one`, and the `alpacon api` line is left out. Running the command again files a new approval request. When `--wait` runs the command again after approval and the deadline has passed, a second denial prints `The approval deadline (DEADLINE) has passed and the command was denied again. Re-run the command to request a new approval.`

The message lists none of these lines when the server sends no approval details: an older server, or a request that is no longer open because it was approved, rejected, expired or cancelled. The output is then what it was without them. A cancel does not end `--wait`: the command's `sudo_grant_status` stays `pending_approval` until the request expires, and the wait follows that status.

## Work session requirement

When you sign in with browser login, `alpacon exec` requires an active [work session](/reference/cli/work-session/) that includes the `command` scope; `--upload` and `--from-server` also need the `webftp` scope. Service-token authentication bypasses this requirement.

New personal API tokens cannot hold command-execution or file-transfer scopes. Existing tokens may still hold those scopes. From December 1, 2026 (00:00 UTC), command and REST file-transfer creation with such a token needs an active, approved work session and still passes the token’s ACL checks. Until then, those calls outside a work session still run, with a warning header in each response; see [Token restrictions](/use/settings/api-tokens/#token-restrictions). Reads and work-session requests retain their existing permission rules. Use a [service token](/use/iam/applications/service-tokens/) for automation and CI.

The session to attach is resolved from the `--work-session` flag, the `ALPACON_WORK_SESSION` environment variable, or the active session set with [`alpacon work-session use`](/reference/cli/work-session/use/)—in that order.

## MFA authentication

When executing commands as a system account (e.g., `root@my-server`), your workspace's [Authentication](/use/policies/authentication/) settings may require additional MFA verification. The CLI MFA flow is the same as `alpacon websh`—see [websh MFA authentication](/reference/cli/websh/#mfa-authentication) for details.

## API token ACLs

A token must have ACL rules for each command you intend to execute. Tokens cannot open interactive Websh; non-interactive exec commands require matching command ACL rules.

```bash
# Allow the commands this token can run on servers
alpacon token acl command add my-token --command="df *"
alpacon token acl command add my-token --command="cat /etc/hostname"
```

`--upload` and `--from-server` also need a file ACL that covers the `--file` path: the `upload` action for `--upload`, and the `download` action for `--from-server`. See [`alpacon token acl file add`](/reference/cli/token/acl-file-add/).

See [Token ACL management](/reference/cli/token/acl/) for details on wildcard patterns.

Source: https://docs.alpacax.com/reference/cli/exec/
