# Processes, files and ports

Run commands in a miniVM, keep long-lived processes running, push files in, and reach a port from your machine.

This page covers what you do inside a running miniVM with `ons`. Every command here takes the miniVM's id, `<minivm-id>`: the id `ons create` printed. `ons ls` lists yours.

Every command also takes `--json` for one stable JSON object on stdout. Use it in scripts and agents.

## Run one command: `ons exec`

```bash
ons exec <minivm-id> -- uname -a
```

- Everything after `--` is the program and its arguments. There is **no shell**: pipes, globs, `cd` and redirections need one.

  ```bash
  ons exec <minivm-id> -- sh -c 'cd /home/user/work && ls | wc -l'
  ```

- `--timeout <seconds>` bounds the command (default 60).

- `ons exec` exits with the command's exit code. `255` means `ons` itself failed (network, auth, miniVM not running), as with `ssh`.

- With `--json`, stdout and stderr are captured, up to 16 MiB, and returned in `stdout`, `stderr` and `exitCode`. Drop `--json` to stream larger output.

## Open a terminal: `ons shell`

```bash
ons shell <minivm-id>
```

An interactive shell in the miniVM. It is for people; scripts and agents use `ons exec`.

## Create, push, run, kill: `ons run`

`ons run` does it all in one command: it creates a miniVM, pushes a directory to `/home/user/work`, runs the command there, kills the miniVM and exits with the command's code.

```bash
ons run --push . -- npm test
```

- The template is the `name` of the directory's `minisandbox.yaml`. Otherwise pass `--template <name>`.
- `--timeout <seconds>` (default 1800) bounds both the command and the miniVM.
- `--keep` leaves the miniVM running afterwards, for more `ons exec`.
- `--metadata <key>=<value>` (repeatable) labels the miniVM.
- Exit codes: the command's own, `255` if `ons` failed, `130` on Ctrl-C (which kills the miniVM too).

## Long-running processes: `ons proc`

`ons exec` holds the command for at most its timeout. `ons proc` starts a process that keeps running after `ons` exits, such as a dev server or a coding agent. You read its output later, from anywhere.

```bash
ons proc start <minivm-id> --tag server --cwd /home/user/work -- npm run dev
ons proc logs --follow <minivm-id> server
```

`server` is the tag you choose, to find the process again.

| Command                                               | What it does                                                                                                                                               |
| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ons proc start <minivm-id> --tag <tag> -- <command>` | Starts the process with stdin open. `--cwd <dir>`, `--env <key>=<value>` (repeatable), `--pty` to run it on a terminal.                                    |
| `ons proc ls <minivm-id>`                             | Lists running processes. `--all` also lists ended ones.                                                                                                    |
| `ons proc logs <minivm-id> <tag>`                     | Prints the output kept so far. `--follow` keeps printing until the process ends. `--from <offset>` starts at a byte offset.                                |
| `ons proc send <minivm-id> <tag> <text>`              | Writes the text and a newline to the process's input. `-` passes your stdin through. `--no-newline`, `--eof` to close its stdin.                           |
| `ons proc wait <minivm-id> <tag>`                     | Waits for the process to end and exits with its code. `--timeout <duration>` (`30s`, `5m`, `2h`) gives up with exit code `124`; the process keeps running. |
| `ons proc kill <minivm-id> <tag>`                     | Signals the process and its process group. `--signal TERM` (default) or `KILL`.                                                                            |

`logs`, `wait` and `kill` also take `--pid <pid>` instead of a tag.

What to know:

- A tag is unique among **running** processes. An ended process frees its tag.
- The miniVM keeps the last 4 MiB of each process's output, and remembers ended processes for 24 hours (the last 64).
- `logs --follow` and `wait` survive a dropped connection (laptop sleep, network loss, a paused miniVM woken on reconnect). They reconnect for up to 10 minutes and never print a byte twice.
- With `--json`, `logs` prints one JSON line per output chunk, then a last line with `next_offset`. Pass it as `--from` to resume where you stopped.

> **Note:** The E2B SDK's sandbox logs call returns an empty list on onshore.sh: we never see your miniVM's output. Use `ons proc logs`, or read the output of your commands directly.

## Push files: `ons push`

```bash
ons push <minivm-id> .
```

`ons push` copies a local directory into a running miniVM, by default to `/home/user/work`.

- `--to <path>` sets another absolute directory in the miniVM. It is created if missing; existing files are overwritten.
- Only new and changed files are sent. A second push with nothing changed rewrites nothing, so builds in the miniVM stay incremental.
- In a git repository, it pushes what git tracks, up to 500 MiB. `--untracked include` also pushes what git would track (untracked, not ignored).
- Outside a git repository, pass `--no-git` to push every file.
- `--delete` also removes from `--to` what your directory no longer has. Files ignored by `.gitignore` there (such as `node_modules/` or `target/`) stay.
- Files keep their modification time, so `make` and `cargo` rebuild only what changed.

### Secrets are refused

A file that is not committed as is, and that looks like a secret, refuses the whole push. Examples: `.env` files, private keys, `*.pem`, cloud credential directories, or a file that contains an API token. The error names the file and why, never its content.

Ignore the file in `.gitignore`, or pass `--include-secrets` if you really mean to push it.

### Single files and downloads

For one small file, go through `ons exec`:

```bash
ons exec <minivm-id> -- cat /home/user/work/out.json
```

For many or large files in both directions, use the E2B SDK's files API (`files.write`, `files.read`, `files.list`, `files.watch_dir`). See [Migrate from E2B](https://onshore.sh/docs/guides/migrate-from-e2b).

## Reach a port: `ons forward`

```bash
ons forward 3000 --sandbox <minivm-id>
```

This serves port 3000 of the miniVM on `127.0.0.1:3000` of your machine, until you press Ctrl-C.

- `--local-port <port>` picks another local port; `0` picks a free one (printed with `--json`).
- It carries HTTP and WebSocket. A paused miniVM wakes on the next request.
- It listens on loopback only (`--bind` accepts `127.0.0.1` or `::1`). Anyone who reaches that local port reaches the miniVM's port.
- Browser requests are accepted only from pages served by the forward itself. To allow another web origin, such as a local dev server on another port, add `--allow-origin http://localhost:5173` (repeatable).

### Ports from the SDK

Each port of a miniVM has its own HTTPS host: `<port>-<minivm-id>.onshore.sh`. The E2B SDK returns it with `get_host(<port>)` (Python) or `getHost(<port>)` (JavaScript).

Ports are never public. Every request must carry the header `e2b-traffic-access-token` with the miniVM's traffic token, which the create response returns as `trafficAccessToken`. Without it, the answer is `401`. A create with `allowPublicTraffic: true` is refused with `400`.

The E2B SDK keeps the token on the sandbox object: `sbx.traffic_access_token` in Python,
`sbx.trafficAccessToken` in JavaScript.
The examples serve a directory with Python's built-in web server, so the template needs `python3`.
If yours has none, start a server your template has.

#### Python

```python
import urllib.request

from e2b import Sandbox

sbx = Sandbox.create()
sbx.commands.run("python3 -m http.server 8000", background=True)

url = f"https://{sbx.get_host(8000)}/"
req = urllib.request.Request(url, headers={"e2b-traffic-access-token": sbx.traffic_access_token})
print(urllib.request.urlopen(req).read().decode())
```

#### JavaScript

```javascript
import { Sandbox } from 'e2b'

const sbx = await Sandbox.create()
await sbx.commands.run('python3 -m http.server 8000', { background: true })

const res = await fetch(`https://${sbx.getHost(8000)}/`, {
  headers: { 'e2b-traffic-access-token': sbx.trafficAccessToken },
})
console.log(await res.text())
```

A server can take a moment to start: retry the first request if it is refused.

### Show a preview to someone else

A browser cannot add the header by itself, so a preview URL does not open in a browser as is. To
show a preview to a user of your app, serve it through your own backend: your backend receives the
user's request, checks that this user may see this preview, and forwards it to
`https://<port>-<minivm-id>.onshore.sh` with the `e2b-traffic-access-token` header. Keep the token
on your server.

- The traffic token opens every port of its miniVM. Never put it in a page, a URL or a link you
  share.
- To look at a preview yourself, use `ons forward`: it adds the token and serves the port on your
  machine.

## Exit codes

| Code  | Meaning                                                                                                       |
| ----- | ------------------------------------------------------------------------------------------------------------- |
| `0`   | Success. For `exec`, the command exited 0.                                                                    |
| `1`   | `ons` failed. The error says why and what to do.                                                              |
| `2`   | Bad usage (unknown flag, missing argument). Read `ons <command> --help`.                                      |
| `124` | `ons proc wait`: its `--timeout` passed before the process ended.                                             |
| `255` | `exec`, `shell` or `proc wait` could not run the command (network, auth, miniVM state), or a signal ended it. |
| other | `exec`, `proc wait`: the command's own exit code.                                                             |

## Related

- [Lifecycle](https://onshore.sh/docs/guides/lifecycle): pause, resume and wake-ups.
- [Egress](https://onshore.sh/docs/guides/egress): what the miniVM may reach.
- [CLI reference](https://onshore.sh/docs/reference/cli)

Markdown version: https://onshore.sh/docs/guides/processes-files-ports.md
