Files
ssh-netbox-wrapper/README.md
T
Sebastian UnterschützandClaude Opus 5.5 080e52b437
Test / test (pull_request) Successful in 4m16s
docs: document DNS suggestions, dns settings and links (v1.3.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:09 +01:00

2057 lines
103 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# netssh
> **Vibe-coded project** — this codebase was written entirely by an AI assistant (Claude) without human code review. Use in production at your own risk.
A transparent SSH wrapper that resolves hostnames via [NetBox](https://netbox.dev/) before connecting.
Instead of looking up an IP manually, you just type the hostname as it appears in NetBox:
```sh
netssh my-router-01
netssh -p 2222 admin@app-server-03 uptime
```
`netssh` looks up the host in NetBox, resolves the right IP using a configurable strategy chain, and replaces the process with the native `ssh` binary — so all your existing SSH configs, keys, and agent forwarding work without any changes.
The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the interactive search, shell completion, and generated shell aliases.
## Contents
- [Features](#features)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Configuration](#configuration) — [wizard](#interactive-wizard), [manual config](#manual-config), [reference](#configuration-reference), [environment variables](#environment-variables), [files](#files-and-directories), [multiple instances](#multiple-netbox-instances)
- [Usage](#usage) — [command overview](#command-overview), [SSH options](#ssh-options), [pre-connect hook](#pre-connect-hook), [SFTP & SCP](#sftp-and-scp), [port forwarding](#port-forwarding), [static hosts](#static-hosts), [multiple servers](#multiple-servers-in-one-window), [shortcuts](#host-shortcuts), [TUI](#interactive-tui), [notes](#server-notes), [cache](#cache-management)
- [Operations](#operations) — post scripts, favorites, history, diagnostics, batch commands, configuration sharing
- [NetBox insights and host tools](#netbox-insights-and-host-tools) — `info`, `open`, `whois`, status warnings, TUI columns and reachability, address fallback, `copy-id`, `known-hosts`, `export`, keyring tokens
- [Custom host commands](#custom-host-commands) — automatic aliases for mtr, ping, and other programs
- [Hotkey cheat sheet](#hotkey-cheat-sheet) — search, editors, tmux and zellij
- [Recipes](#recipes)
- [IP Resolution Strategies](#ip-resolution-strategies)
- [Shell Completion](#shell-completion) and [Shell Hook](#shell-hook)
- [Troubleshooting](#troubleshooting)
- [Uninstall](#uninstall), [Development](#development), [How it works](#how-it-works)
## Features
- **Transparent proxy** — replaces itself with `ssh` via `syscall.Exec`, preserving all SSH flags and options
- **Flexible IP resolution** — configurable chain of strategies: management subnet, primary IP, named interface, or the hostname itself
- **Static hosts** — add hosts that are not in NetBox (`netssh hosts add router 192.168.1.1`); they work everywhere, also without any NetBox
- **Interactive TUI** — fuzzy search with live NetBox queries and 300 ms debouncing (start with `netssh`, no arguments)
- **Recently-used list** — TUI opens with your most-recently-connected hosts (10 by default, configurable with `tui.history_limit`), no typing needed
- **Tag/kind filter** — press `Ctrl+F` in the TUI to filter by `tag:prod` or `kind:vm`
- **User/port override** — press `Ctrl+E` in the TUI to override the SSH user or port before connecting
- **Server notes** — multiline local notes or optional NetBox comments, available in the TUI and CLI
- **Persistent cache** — successful lookups are cached to `~/.cache/netssh/hosts.json` for instant shell completion
- **Full pagination** — `cache refresh` fetches all hosts from NetBox (not just the first 50)
- **Selective refresh** — `cache refresh --tag prod --kind vm` limits what gets synced
- **Setup wizard** — interactive first-run onboarding; re-run anytime with `netssh configure`
- **Shell completion** — install without sudo via `netssh completion install`
- **Default SSH user** — set a fallback username once in config instead of typing it every time
- **Default SSH port** — set a fallback port in config; injected as `-p` when not specified on the command line
- **Host shortcuts** — type `web01` instead of `web01.example.com`; configurable domain strip, hyphen folding, and regex rewrite rules (`fsn1-bx1.hoster.de` → `fsnbx1`)
- **Shell aliases** — `netssh alias` generates shell aliases for all cached hosts
- **Automatic 24h cache refresh** — the cache is refreshed in the background every 24 hours
- **Jump hosts and SSH options** — `proxy_jump`, host key checking, connection target, and free `-o` options per netssh, per NetBox instance, or per tag/name rule — without touching `~/.ssh/config`
- **SFTP & SCP** — `netssh sftp host` and `netssh scp file host:/tmp/` with the same host lookup, shortcuts, and SSH options as ssh
- **Several servers in one window** — `netssh multi` opens hosts, a tag, a NetBox cluster, or a saved group side by side in tmux or zellij, with optional typing into all of them
- **Port forwarding** — named forwards in the config (`netssh tunnel host web`, `netssh --forward web host`), ad hoc specs, and `Ctrl+T` in the TUI
- **Dry run** — `netssh --dry-run host` prints the final `ssh` command instead of connecting
- **Host details** — `netssh info host` (and `Ctrl+L` in the TUI) shows site, the nested locations down to rack and rack units, role, platform, tenant, status and all IP addresses per interface; `netssh open host` (`Ctrl+G`) opens the NetBox page
- **DNS names and links** — `netssh mx123.webseite.de` (or `netssh mx123`) for a name that is only in DNS: netssh finds the host owning the address in NetBox, suggests it, and can save `mx123` as a link — `netssh mx123` and the shell alias `mx123` then connect directly
- **Reverse lookup** — `netssh whois 10.1.2.3` names the device or VM, interface, DNS name and prefixes of an address
- **Status warning** — asks before connecting to hosts that are `offline`, `planned`, `decommissioning` …; TUI badge and `status:` filter
- **Configurable TUI** — choose what is shown next to each host (`tui.columns`: IP, source, status, site, location path, role, platform, tenant, cluster, tags, kind, alias); the optional `reachability` column marks hosts ✓/✗ after a quick TCP check of their SSH port; `resolver.fallback` connects to another known address when the chosen one does not answer
- **Rules by NetBox attributes** — `ssh.rules` and command restrictions match `site`, `role`, `platform`, `tenant` and `status`, e.g. legacy ciphers for `platform: junos`
- **ssh-copy-id, known_hosts cleanup, exports** — `netssh copy-id tag:lab`, `netssh known-hosts reset host`, `netssh export ansible` (YAML or INI) and `netssh export ssh-config`
- **Keyring tokens** — `netssh token migrate` moves API tokens from the config into the system keyring
- **Clean uninstall** — `netssh uninstall` removes the binary, profile entries of all versions, completions, cache, and config
## Installation
### One-liner (Linux & macOS)
```sh
curl -fsSL https://git.zb-server.de/Sebi/ssh-netbox-wrapper/raw/branch/main/install.sh | bash
```
The script detects your OS and architecture, downloads the matching binary from the [latest release](https://git.zb-server.de/Sebi/ssh-netbox-wrapper/releases/latest), verifies the SHA-256 checksum, and installs to `/usr/local/bin/netssh` (using `sudo` only if necessary).
To install to a custom directory:
```sh
curl -fsSL https://git.zb-server.de/Sebi/ssh-netbox-wrapper/raw/branch/main/install.sh | INSTALL_DIR="$HOME/.local/bin" bash
```
### Updating an existing installation
Run the same one-liner again to update to the latest release. The installer uses
an existing `netssh` found in `PATH`, or `/usr/local/bin/netssh` for a new installation.
`INSTALL_DIR` explicitly overrides the destination. The replacement is atomic,
so an installed binary can be updated while it is running.
The installer checks all required programs before downloading or modifying files:
`curl`, `uname`, `sed`, `awk`, `mktemp`, `rm`, `dirname`, `readlink`, `mkdir`, `cat`,
`install`, `mv`, `cp`, `chmod`, `cmp`, and either `sha256sum` (Linux) or `shasum`
(macOS). Bash runs the installer; `sudo` is checked beforehand only if the target
directory requires elevated permissions. Missing programs are listed together;
install them with your package manager and retry. **Python is not required. SHA-256 verification is mandatory:** missing,
duplicate or mismatched checksums abort the update before replacing anything.
It also consolidates netssh integration in existing Bash, Zsh and Fish profiles
and creates the current shell's rc file when needed. Old standalone netssh hooks,
inline host aliases and `eval "$(netssh alias)"` entries are replaced by a single
managed block per rc file. Legacy entries in login profiles are removed as well.
Other shell settings, NetBox configuration, cache and local notes are preserved.
Every changed existing profile gets a `.netssh-backup.XXXXXX` backup; symlinks
and permissions are preserved. `XDG_CONFIG_HOME`, `XDG_CACHE_HOME` and `ZDOTDIR`
are respected. Alias files and installed shell completions are regenerated.
Open a **new terminal** after updating to load the new aliases and hooks.
### Release downloads and change history
Each new release includes `install.sh`, binaries for Linux and macOS (amd64 and
arm64), and `checksums.txt` covering all of these files. The release notes include
an installation command pointing directly to that release's `install.sh` asset
and a list of changes since the previous version tag.
See [CHANGELOG.md](CHANGELOG.md) for the change history. The installer attached to
a release installs or updates to the latest published binary release.
### Build from source
```sh
git clone ssh://git@git.zb-server.de:30022/Sebi/ssh-netbox-wrapper.git
cd ssh-netbox-wrapper
go build -o netssh ./cmd/netssh
```
## Quick start
1. **Install** with the one-liner above and open a new terminal.
2. **Configure** — run `netssh` (or `netssh configure`). The wizard asks for your NetBox URL and an API token; a read-only token is enough unless you want to edit NetBox comments. Everything else has working defaults and can be changed later.
3. **Fill the cache** — `netssh cache refresh` fetches all devices and virtual machines once. Connecting works without it, but completion, shortcuts, aliases, and the recently-used list need cached hosts.
4. **Connect** — `netssh web01`, or just `netssh` for the interactive search.
5. **Optional** — enable completion and aliases with `netssh hook install` (the installer usually did this already), and try `netssh --dry-run web01` to see the exact ssh command.
```sh
netssh configure # NetBox URL + token
netssh cache refresh # fetch all hosts once
netssh web01 # ssh to web01 via its NetBox IP
netssh sftp web01 # sftp to the same host
netssh tunnel web01 8080:localhost:80 # local port 8080 → web01:80
```
## Configuration
### Interactive wizard
On first run (when no config exists), `netssh` automatically starts an interactive setup wizard.
Re-run it at any time to change settings without editing the file manually:
```sh
netssh configure
```
The wizard first lets you add, edit, and remove named NetBox instances and set SSH options per instance. Without any instance you can also continue with static hosts only.
A menu then gives access to every other setting; open only the sections you want to change and choose **Save and exit**:
| Section | Settings |
|---|---|
| SSH defaults | `ssh.default_user`, `ssh.default_port` |
| SSH options | `proxy_jump`, `host_key_checking`, `target`, `address_family`, `extra_args` (one per line), `options` (`Key=Value` per line), `forwards` (`NAME L\|R\|D SPEC` per line), `pre_connect` |
| SSH rules | add, edit, remove `ssh.rules` — match by tag, instance, kind, name pattern, each with its own SSH options |
| Static hosts | add, edit, remove hosts that are not in NetBox, each with user, port, tags, and SSH options |
| Multi-session | multiplexer (auto, tmux, zellij), panes per window, tmux keys for broadcast and excluding a pane, groups (`NAME: sel1, sel2` per line) |
| Resolver & cache | strategies, management subnets, interface name, hostname domain, cache TTL, cache file |
| Shortcuts & command alias | domain suffixes, hyphen stripping, rewrite rules (`REGEX => REPLACEMENT` per line), show shortcuts (`shortcuts.show`), `shell.alias` |
| Completion | `completion.max_results` |
The result is validated and saved to `~/.config/netssh.yaml`; Ctrl+C cancels without writing.
### Manual config
`~/.config/netssh.yaml`:
```yaml
netbox:
url: https://netbox.example.com
token: nbt_your-api-token-here # v2 token (nbt_ prefix) recommended
token_version: 2 # auto-detected from token; 1 = legacy, 2 = nbt_
resolver:
# Strategies are tried in order; the first to return an IP wins.
strategies:
- management_subnet
- primary_ip
# Used by the management_subnet strategy.
management_subnets:
- 10.0.0.0/8
- 172.16.0.0/12
# Used by the interface_name strategy.
interface_name: mgmt0
cache:
ttl: 3600 # seconds; 0 = always query NetBox on connect (cache still used for completion)
# path: ~/.cache/netssh/hosts.json # default
ssh:
default_user: admin # used when no user is specified on the command line
default_port: 2222 # optional; injected as -p if not specified on the command line
# See "SSH options" below for proxy_jump, host_key_checking, target,
# address_family, extra_args, options, and rules.
completion:
max_results: 0 # hostnames offered per <Tab>; 0 = unlimited
shortcuts:
domains: # strip these suffixes to create short aliases
- .example.com
strip_hyphens: false # if true, fsn1-web01 → fsn1web01 (cache-only resolution)
```
Single-instance and shared settings can be overridden with environment variables (`NETSSH_NETBOX_URL`, `NETSSH_NETBOX_TOKEN`, etc.; see [Environment variables](#environment-variables)).
netssh reads `netssh.yaml` from the user config directory only; a file of that name in the working directory is ignored. Unknown keys are ignored; invalid values (an unknown strategy, a bad regex, an invalid SSH option) stop netssh with an error that names the key.
### Configuration reference
Every key, its default, and the section that explains it. Keys marked *layered* can also be set per NetBox instance (`netboxes[].ssh.…`) and per rule (`ssh.rules[].…`).
| Key | Type | Default | Description |
|---|---|---|---|
| `netbox.url` | string | — | NetBox base URL (single instance). Use either `netbox` or `netboxes`. |
| `netbox.token` | string | — | API token; `nbt_…` is v2, anything else v1. `keyring` reads it from the system keyring — see [Keyring tokens](#keyring-tokens). |
| `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. |
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `disable_prefix`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
| `resolver.strategies` | list | `[management_subnet, primary_ip]` | Tried in order, first IP wins — see [IP Resolution Strategies](#ip-resolution-strategies). The wizard suggests `primary_ip`. |
| `resolver.management_subnets` | list of CIDR | `[]` | Used by `management_subnet`. |
| `resolver.interface_name` | string | — | Used by `interface_name`, e.g. `mgmt0`. |
| `resolver.hostname_domain` | string | — | Used by `hostname`: appended to NetBox names without a dot. |
| `resolver.fallback` | bool | `false` | When the chosen address does not answer on the SSH port, connect to the first address of another strategy that does — see [Address fallback](#address-fallback). |
| `resolver.fallback_timeout` | milliseconds | `1000` | Connect timeout per address for the fallback check. |
| `cache.ttl` | seconds | `3600` | How long a cached IP is used without asking NetBox; `0` always asks NetBox when connecting. |
| `cache.path` | path | user cache dir `/netssh/hosts.json` | Cache file; named instances use a subdirectory next to it. |
| `ssh.default_user` | string | — | Login user when none is given (`-l` for ssh, `-o User=` for sftp/scp). |
| `ssh.default_port` | int | — | Port when none is given (`-p` for ssh, `-P` for sftp/scp). |
| `ssh.warn_status` | list | `[offline, planned, staged, failed, inventory, decommissioning]` | NetBox status values that ask before connecting; `[]` disables the question — see [Status warning](#status-warning). |
| `ssh.proxy_jump` | string | — | *Layered.* Jump host (`-J`); `none` disables an inherited one. |
| `ssh.host_key_checking` | `strict` \| `accept-new` \| `off` | ssh's own | *Layered.* See [SSH options](#ssh-options). |
| `ssh.target` | `ip` \| `name` \| `hostname` | `ip` | *Layered.* What is passed to ssh as destination. |
| `ssh.address_family` | `any` \| `inet` \| `inet6` | — | *Layered.* `-o AddressFamily=`. |
| `ssh.extra_args` | list | `[]` | *Layered.* Extra ssh arguments; accumulate across layers; ssh only. |
| `ssh.options` | map | `{}` | *Layered.* `-o Key=Value`; per key, the more specific layer wins. |
| `ssh.forwards` | map | `{}` | *Layered.* Named port forwards (`local`, `remote`, `dynamic`) — see [Port forwarding](#port-forwarding). |
| `ssh.post_disconnect` | string | — | *Layered.* Local shell command after the client exits; `none` disables inheritance. |
| `tui.history_limit` | integer | `10` | Recent hosts shown; `0` means all, favorites are additional. |
| `tui.columns` | list | `[alias, ip, source, status]` | What the TUI shows next to each hostname (also `location`), in order; `[]` shows only names. Adding `reachability` enables the TCP check — see [TUI columns](#tui-columns-and-reachability). |
| `tui.reachability_timeout` | milliseconds | `300` | Timeout of the TCP check of the `reachability` column. |
| `activity.enabled` | boolean | `false` | Enable local execution metadata history. |
| `activity.retention_days` / `activity.max_entries` | integer | `30` / `1000` | History retention limits; `0` disables the respective limit. |
| `ssh.pre_connect` | string | — | *Layered.* Shell command run locally before connecting; a non-zero exit aborts; `none` disables an inherited one — see [Pre-connect hook](#pre-connect-hook). |
| `ssh.rules[]` | list | `[]` | `match` (`tag`, `instance`, `kind`, `name`, `site`, `role`, `platform`, `tenant`, `status`) plus any layered key. |
| `shortcuts.domains` | list | `[]` | Suffixes stripped for shortcuts and tried when expanding a short name. |
| `shortcuts.strip_hyphens` | bool | `false` | Ignore hyphens when matching shortcuts. |
| `shortcuts.rewrites[]` | list | `[]` | `pattern` (Go regex) and `replace` — see [Host shortcuts](#host-shortcuts). |
| `shortcuts.show` | bool | `false` | Show each host's shortcut alias in the TUI, `netssh cache list` and `netssh hosts list`, and offer shortcuts in Tab completion even when the full name matches — see [Showing shortcuts](#showing-shortcuts). |
| `completion.max_results` | int | `0` | Hostnames offered per `<Tab>`; `0` = unlimited. |
| `shell.alias` | string | — | Short command name for netssh, e.g. `j` — see [Short command alias](#short-command-alias). |
| `hosts[]` | list | `[]` | Static hosts with `name`, `address`, `user`, `port`, `tags`, `ssh` — see [Static hosts](#static-hosts). |
| `commands` | map | `{}` | Local command rules with `alias_prefix` and argument list `args`; see [Custom host commands](#custom-host-commands). |
| `groups` | map of lists | `{}` | Named host lists for `netssh multi @NAME`; entries are hosts or selectors. |
| `dns.suggest` | `ask` \| `always` \| `never` | `ask` | Unknown names: suggest the host owning the DNS address (`ask`), take the first suggestion without asking, also in scripts (`always`), or do no DNS lookup (`never`) — see [DNS names and links](#dns-names-and-links). |
| `dns.save_link` | `ask` \| `always` \| `never` | `ask` | Save a link after a suggestion: ask, always, or never. |
| `dns.domains[]` | list | `[]` | `match` (glob on the typed name, e.g. `mx*`; empty = all) and `domain` appended to names without a dot. |
| `links` | map | `{}` | Short names for hosts, `mx123: prod/web07`: `netssh mx123` and the shell alias `mx123` connect to the host — see [DNS names and links](#dns-names-and-links). |
| `multi.multiplexer` | `auto` \| `tmux` \| `zellij` | `auto` | Which multiplexer `netssh multi` uses. |
| `multi.panes_per_window` | int | `9` | More hosts open in further tmux windows or zellij tabs. |
| `multi.sync_key`, `multi.solo_key` | tmux key \| `none` | `S`, `e` | Keys after the tmux prefix: broadcast to all panes, exclude/include the current pane. |
### Environment variables
These variables override the file. Lists are comma-separated (`NETSSH_SHORTCUTS_DOMAINS=.example.com,.example.de`). Settings without a variable (`extra_args`, `options`, `forwards`, `rules`, `rewrites`, `netboxes`, `hosts`, `groups`) can only be set in the file.
| Variable | Key |
|---|---|
| `NETSSH_NETBOX_URL`, `NETSSH_NETBOX_TOKEN`, `NETSSH_NETBOX_TOKEN_VERSION` | `netbox.*` (single instance only; ignored when the file has only `netboxes:`) |
| `NETSSH_RESOLVER_STRATEGIES`, `NETSSH_RESOLVER_MANAGEMENT_SUBNETS`, `NETSSH_RESOLVER_INTERFACE_NAME`, `NETSSH_RESOLVER_HOSTNAME_DOMAIN` | `resolver.*` |
| `NETSSH_CACHE_TTL`, `NETSSH_CACHE_PATH` | `cache.*` |
| `NETSSH_SSH_DEFAULT_USER`, `NETSSH_SSH_DEFAULT_PORT` | `ssh.default_*` |
| `NETSSH_SSH_WARN_STATUS` | `ssh.warn_status` |
| `NETSSH_TUI_COLUMNS`, `NETSSH_TUI_REACHABILITY_TIMEOUT` | `tui.columns`, `tui.reachability_timeout` |
| `NETSSH_RESOLVER_FALLBACK`, `NETSSH_RESOLVER_FALLBACK_TIMEOUT` | `resolver.fallback*` |
| `NETSSH_SSH_PROXY_JUMP`, `NETSSH_SSH_HOST_KEY_CHECKING`, `NETSSH_SSH_TARGET`, `NETSSH_SSH_ADDRESS_FAMILY`, `NETSSH_SSH_PRE_CONNECT` | global `ssh.*` options |
| `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS`, `NETSSH_SHORTCUTS_SHOW` | `shortcuts.*` |
| `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` |
| `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` |
| `NETSSH_SHELL_ALIAS` | `shell.alias` |
| `NETSSH_DNS_SUGGEST`, `NETSSH_DNS_SAVE_LINK` | `dns.suggest`, `dns.save_link` |
netssh also respects `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, `ZDOTDIR`, and `SHELL` (for `hook install`, `completion install`, and `alias` without `--shell`).
### Files and directories
Paths are shown for Linux, where `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` replace `~/.config` and `~/.cache`. On macOS, config and notes live under `~/Library/Application Support`, the host cache and `aliases.sh` under `~/Library/Caches/netssh/` (unless `XDG_CACHE_HOME` is set for `aliases.sh`); fish and completion files use the paths in the table.
| Path | Content |
|---|---|
| `~/.config/netssh.yaml` | Configuration, including API tokens; written with mode `0600`. |
| `~/.config/netssh/notes/` | Local server notes (`0600`), keyed by NetBox URL, kind, and hostname. |
| `~/.cache/netssh/hosts.json` | Host cache (single instance). |
| `~/.cache/netssh/instances-<hash>/hosts.json` | Host cache for a set of named instances; the hash changes when names or URLs change. |
| `~/.cache/netssh/last_refresh` | Time of the last full refresh, for the 24-hour background refresh. |
| `~/.cache/netssh/aliases.sh` | Generated aliases for bash and zsh. |
| `~/.config/fish/conf.d/netssh.fish` | Generated aliases for fish. |
| `~/.local/share/bash-completion/completions/netssh`, `~/.zfunc/_netssh`, `~/.config/fish/completions/netssh.fish` | Installed completions. |
### Multiple NetBox instances
Use `netssh configure` to manage instances, or replace the `netbox:` section with a `netboxes:` list:
```yaml
netboxes:
- name: office
url: https://netbox.office.example
token: nbt_office-token
- name: lab
url: https://netbox.lab.example
token: nbt_lab-token
```
Names must be unique and contain only letters, digits, underscores, or hyphens. Names are normalized to lowercase. Each instance has its own token and optional `token_version`; SSH, resolver, and shortcut settings apply to all instances. Configure either `netbox:` or `netboxes:`. Existing single-instance files continue to work; the wizard migrates them to a named `default` instance when saved.
The legacy `NETSSH_NETBOX_URL` and `NETSSH_NETBOX_TOKEN` variables apply to single-instance configuration. They are ignored when the file contains only a named `netboxes:` list.
Each NetBox keeps its own inventory of devices and virtual machines; either inventory may be empty. The interactive search queries all instances in parallel, including when one already has cached matches. Results show the instance as part of the hostname, for example `office/web01`. If an instance is unavailable, available results and cached hosts remain visible with a warning.
```sh
netssh # search all instances interactively
netssh office/web01 # choose an instance explicitly
netssh admin@lab/web01 uptime
netssh web01 # accepted only if the live lookup is unambiguous
netssh cache refresh # refresh all instances
netssh cache refresh --instance lab # refresh just one instance
netssh notes set office/web01 "Office maintenance"
netssh notes show lab/web01 --netbox --kind device
```
For direct connections without an instance prefix, every instance must be reachable to verify uniqueness. A qualified target queries only its own instance and can use a fresh cached IP while other instances are offline. Qualified shortcuts such as `office/web01` also support configured domain suffixes and hyphen folding.
Cache entries retain the instance name. Generated aliases include it by default (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed.
**Aliases and TUI names without an instance prefix.** Set `disable_prefix: true`
on individual instances, or enable **Hide instance prefix in aliases and TUI?**
when editing an instance in `netssh configure`:
```yaml
netboxes:
- name: office
url: https://netbox.office.example
token: nbt_office-token
disable_prefix: true
- name: lab
url: https://netbox.lab.example
token: nbt_lab-token
```
With the appropriate domain shortcut, this generates `web01` for
`office/web01.example.com` and `lab_web01` for the lab host. The default is
`false`. The alias command still contains the full `instance/hostname`, so it
connects to the selected instance even when another instance has the same host
name. Domain stripping, rewrites and hyphen folding still apply.
If a bare alias conflicts with another generated alias, a reserved qualified
alias, `netssh`, or your configured command alias, the instance prefix is kept.
It is also kept if the bare name is not a valid shell alias (e.g. starts with a digit).
The TUI result list also hides the prefix for this instance; duplicate visible
names keep their prefixes to remain distinguishable. Selection, autocomplete,
connection editors, notes and cache identities still use the full target.
Completion already offers unique hostnames
without an instance prefix.
Open a new shell with the installed netssh hook to regenerate and load aliases.
No cache refresh is needed for this setting. Existing aliases in an already open
shell remain until removed or the shell is replaced.
Local notes remain keyed by the NetBox URL, host kind, and canonical hostname. Migrating a single instance or renaming it preserves its notes. Use `instance/hostname` and `--kind` for uncached local notes; these operations work offline. NetBox comments and interface/IP lookups always use the selected instance's credentials.
### Short command alias
In `netssh configure`, set **Command alias** to `j` to use `j` anywhere you would
use `netssh`:
```sh
j # interactive server search
j server01 # connect to a server
j notes show server01
```
The setting is saved as:
```yaml
shell:
alias: j
```
The wizard regenerates shell aliases and installs the current shell's hook when
an alias is set. Open a new terminal (or follow the displayed reload command).
Changing the setting replaces the old generated alias; leaving it empty disables
it for new shells. The command alias takes priority over a host alias with the
same name and works even when no servers are cached. Environment override:
`NETSSH_SHELL_ALIAS=j`.
The command alias also supports shell completion: `j ser<Tab>` suggests cached
server names, just like `netssh ser<Tab>`. The wizard, shell hook, installer, and
`netssh completion install` maintain the alias completion files automatically.
Changing or disabling the alias removes its old generated completion files.
Bash requires bash-completion to load user completion files; for Zsh, include
`~/.zfunc` in `fpath` before running `compinit` as described below. Fish loads
completion files automatically. Open a new terminal after changing the alias.
### API tokens
NetBox supports two token formats:
| Format | Example | Notes |
|--------|---------|-------|
| v2 (recommended) | `nbt_abc123…` | Create in NetBox → Admin → API Tokens |
| v1 (legacy) | `abc123def456…` | Older format; still works, but v2 is preferred |
`netssh` auto-detects the version from the token prefix and stores it as `token_version` in the config.
A hint is shown during `netssh configure` if a legacy v1 token is entered.
To keep tokens out of the config file, store them in the system keyring with
`netssh token set` or `netssh token migrate` — see [Keyring tokens](#keyring-tokens).
## Usage
### Command overview
| Command | Purpose |
|---|---|
| `netssh` | Interactive search (TUI). |
| `netssh [--dry-run] [--jump HOST\|--no-jump] [--forward NAME]... [ssh options] HOST [command]` | Connect with ssh. |
| `netssh sftp [netssh flags] [sftp options] HOST[:PATH]` | SFTP session — see [SFTP and SCP](#sftp-and-scp). |
| `netssh scp [netssh flags] [scp options] SOURCE... TARGET` | Copy files — see [SFTP and SCP](#sftp-and-scp). |
| `netssh doctor [--online]` / `netssh explain HOST` | Diagnose configuration and explain effective settings. |
| `netssh info [--json] HOST` / `netssh open [--print] HOST` | Show NetBox details of a host / open its NetBox page — see [Host details](#host-details-and-netbox-page). |
| `netssh link list \| add NAME HOST \| remove NAME` | Short names for hosts — see [DNS names and links](#dns-names-and-links). |
| `netssh whois [--json] ADDRESS\|HOSTNAME` | Find the host, interface and prefix of an address — see [Reverse lookup](#reverse-lookup). |
| `netssh copy-id [-i KEY] [-l U] [--dry-run] HOST\|tag:T\|cluster:C\|@GROUP...` | Install your public key with ssh-copy-id — see [ssh-copy-id](#ssh-copy-id). |
| `netssh known-hosts reset [--yes] [--dry-run] HOST...` | Remove stored host keys of re-deployed hosts — see [known_hosts cleanup](#known_hosts-cleanup). |
| `netssh export ansible [--format yaml\|ini] [--group-by …]` / `netssh export ssh-config` | Export cached hosts — see [Exports](#exports-ansible-inventory-and-ssh_config). |
| `netssh token set\|migrate\|delete\|status` | Keep NetBox tokens in the system keyring — see [Keyring tokens](#keyring-tokens). |
| `netssh favorites` / `netssh history` | Manage saved hosts and optional action records. |
| `netssh batch COMMAND HOST...` | Run a configured command with bounded parallelism and retry. |
| `netssh config export\|import FILE` | Share host configuration without secrets or executable settings. |
| `netssh run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]` | Run a [custom host command](#custom-host-commands), e.g. mtr or ping, using the configured resolver. |
| `netssh tunnel [netssh flags] [ssh options] HOST FORWARD...` | Port forwards without a shell — see [Port forwarding](#port-forwarding). |
| `netssh hosts [list] \| add NAME ADDRESS [--user U] [--port P] [--tag T]... [--replace] \| remove NAME` | Manage static hosts — see [Static hosts](#static-hosts). |
| `netssh multi [--sync] [--kind K] [--tmux\|--zellij] [-l U] [--jump H\|--no-jump] HOST\|tag:T\|cluster:C\|@GROUP...` | Several hosts side by side — see [Multiple servers](#multiple-servers-in-one-window). |
| `netssh sync [--pane]` | Toggle typing into all panes of the current tmux window or zellij tab; `--pane` excludes/includes the current tmux pane. |
| `netssh configure` | Setup wizard. |
| `netssh cache list \| refresh [--tag T] [--kind device\|vm] [--instance I] \| clear` | Inspect and manage the host cache. |
| `netssh search QUERY` | Print matching cached hostnames, one per line. |
| `netssh alias [--shell bash\|zsh\|fish] [--test HOSTNAME]` | Print shell aliases, or test how a name is shortened. |
| `netssh notes show\|set\|append HOST [TEXT] [--netbox] [--kind device\|vm]` | Local notes or NetBox comments. |
| `netssh hook install\|uninstall [--shell S]` | Shell integration (aliases, completion, background refresh). |
| `netssh completion install [--shell S]` / `netssh completion bash\|zsh\|fish` | Install or print completion scripts. |
| `netssh uninstall [--dry-run] [--keep-config] [--yes]` | Remove netssh. |
| `netssh version` / `netssh --version` | Print the version. |
The netssh flags `--dry-run`, `--force`, `--jump`, `--no-jump`, and `--forward` must come before the host. `--force` connects without asking about the NetBox status. Everything after the host is passed to ssh as the remote command (for `tunnel`: forward names).
### SSH wrapper mode
Pass any SSH flags and a NetBox hostname:
```sh
netssh my-router-01
netssh -p 2222 admin@app-server-03 uptime
netssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no db-primary
```
The process is replaced by `ssh` with the resolved IP — your `~/.ssh/config`, agent, and keys all work as normal.
### Dry run and version
```sh
netssh --dry-run web01 # print the final ssh command instead of connecting
netssh --version # or: netssh version
```
Long options (`--dry-run`, `--jump`, `--no-jump`) are netssh's own; OpenSSH has
no long options. They must come before the hostname — everything after the
hostname is the remote command.
### SSH options
All settings below go under `ssh:`. The same keys (except `rules`) can be set
per NetBox instance under `netboxes[].ssh` (or `netbox.ssh`), and per rule.
More specific settings win: global → instance → matching rules (in order) →
command-line flags. Options you pass on the command line always take precedence
over the config.
```yaml
ssh:
proxy_jump: "jumphost.example.com" # passed as -J; "none" disables an inherited jump host
host_key_checking: accept-new # strict | accept-new | off; unset = ssh's own setting
target: ip # ip (default) | name | hostname
address_family: inet # any | inet (-4) | inet6 (-6)
extra_args: ["-A"] # inserted before your own arguments
options: # passed as -o Key=Value
ServerAliveInterval: 60
ServerAliveCountMax: 5
rules: # every set match field must match
- match: {tag: dmz} # tag name or slug
proxy_jump: "dmz-jump.example.com"
- match: {instance: lab, name: "*.lab.example.com", kind: vm}
host_key_checking: off
netboxes:
- name: prod
url: "https://netbox.example.com"
token: "nbt_…"
ssh:
proxy_jump: "jumphost.example.com"
- name: staging
url: "https://netbox-staging.example.com"
token: "nbt_…"
ssh:
host_key_checking: off
```
**Jump hosts.** Override the configured jump host for a single call with
`--jump other.example.com` (or ssh's own `-J`), or disable all jump hosts —
including `ProxyJump` from `~/.ssh/config` — with `--no-jump`.
**Host key checking.** `strict` sets `StrictHostKeyChecking=yes`, `accept-new`
accepts keys of new hosts but rejects changed ones. `off` sets
`StrictHostKeyChecking=no`, `UserKnownHostsFile=/dev/null`, and `LogLevel=ERROR`
for netssh connections only and prints a short notice. Use it only for hosts
that are reinstalled often, such as staging; it disables protection against
man-in-the-middle attacks.
**Connection target.** By default netssh calls `ssh <ip>`. With `target: name`,
it calls `ssh -o HostName=<ip> -o HostKeyAlias=<name> <name>`: the resolved IP
is still used, but `Host *.example.com` rules in `~/.ssh/config` apply, and
known_hosts entries belong to the device instead of an IP that may be reused.
With `target: hostname`, ssh resolves the NetBox name itself (DNS or
`~/.ssh/config`). Names that are not valid hostnames fall back to the IP.
Switching to `name` stores new known_hosts entries under the device name, so
ssh asks once to confirm each host key.
**Rules.** A rule applies when every field set in its `match` fits the host:
| Match field | Compared with | Notes |
|---|---|---|
| `tag` | NetBox tags of the host | Tag name or slug, case-insensitive (`DMZ Hosts` matches `dmz-hosts`). |
| `instance` | Name of the NetBox instance | Only useful with `netboxes:`. |
| `kind` | `device`, `vm`, or `static` | Devices come from DCIM, VMs from Virtualization, `static` from `hosts:`. |
| `name` | Hostname without instance prefix | Shell glob, case-insensitive (`*.dmz.example.com`, `fw-??`). |
Tags and kind are taken from the cache or the NetBox answer, so rules work offline for cached hosts. A rule needs at least one match field. All matching rules apply in file order; a later rule overrides an earlier one.
**How layers combine.** netssh merges global → instance (or the static host's own `ssh`) → matching rules:
- single values (`proxy_jump`, `host_key_checking`, `target`, `address_family`, `pre_connect`) — the most specific non-empty value wins;
- `options` and `forwards` — merged per key or name, the more specific layer wins;
- `extra_args` — collected from all layers.
Options you type yourself always win: netssh adds its `-o` options after yours, and ssh uses the first value it sees; `-J`, `-4`/`-6`, or your own `StrictHostKeyChecking` suppress the matching setting. Check the result with `--dry-run`:
```sh
$ netssh --dry-run fw01.dmz.example.com
ssh -A -l admin -J dmz-jump.example.com -o StrictHostKeyChecking=accept-new -o serveraliveinterval=60 192.0.2.10
```
### Pre-connect hook
`pre_connect` runs a shell command (`sh -c`) on your machine right before netssh
starts ssh, sftp, scp, or a tunnel — for example to check or bring up a VPN, or
to log connections. If the command exits non-zero, netssh prints an error and
does not connect.
```yaml
ssh:
pre_connect: 'wg show wg0 >/dev/null 2>&1 || { echo "VPN wg0 is down" >&2; exit 1; }'
rules:
- match: {tag: public}
pre_connect: none # no VPN needed for these hosts
netboxes:
- name: lab
url: "https://netbox-lab.example.com"
ssh:
pre_connect: 'lab-vpn up' # this instance needs its own VPN
```
It is a layered setting like `proxy_jump`: global → instance or static host →
matching rules, the most specific non-empty value wins, and `none` disables an
inherited hook. The hook gets the target in environment variables:
| Variable | Value |
|---|---|
| `NETSSH_HOST` | Hostname without instance prefix (`web01.example.com`) |
| `NETSSH_TARGET` | Name with instance prefix if any (`prod/web01.example.com`) |
| `NETSSH_INSTANCE` | NetBox instance, empty for a single NetBox or static hosts |
| `NETSSH_IP` | Resolved address netssh connects to |
| `NETSSH_KIND` | `device`, `vm`, or `static` |
| `NETSSH_TAGS` | Comma-separated tags |
| `NETSSH_CLIENT` | `ssh`, `sftp`, or `scp` |
The hook's output goes to stderr, so it never mixes with the output of a remote
command or an scp transfer; it can read from the terminal (e.g. a VPN password
prompt). `--dry-run` prints the hook without running it. `netssh multi` runs it
once per pane. It runs only for connections made through netssh, not for a plain
`ssh` call.
### SFTP and SCP
`netssh sftp` and `netssh scp` look up the host exactly like a connection does: cache, shortcuts and rewrite rules, `instance/host`, default user and port, SSH options and rules, `--jump`/`--no-jump`, and `--dry-run`.
```sh
netssh sftp fsnbx1 # interactive sftp
netssh sftp prod/web01:/var/log # start in a directory
netssh scp ./app.tar fsnbx1:/tmp/ # upload
netssh scp -r web01:/etc/nginx ./nginx # download
netssh scp --dry-run app.tar web01:/tmp/ # print the scp command
```
sftp and scp options are passed through. Mind their differences from ssh: the port is `-P`, and `-l` is a bandwidth limit, so the default user is passed as `-o User=`. `extra_args` and `forwards` contain ssh flags and apply to ssh only. All remote operands of one `scp` call must name the same host; copy between two NetBox hosts in two steps. Tab completion offers `host:` for scp and local files otherwise.
### Port forwarding
Plain `-L`, `-R`, and `-D` flags are passed to ssh as usual (`netssh -L 8080:localhost:80 web01`). For tunnels you use often, name them under `ssh.forwards`, globally, per NetBox instance (`netboxes[].ssh.forwards`), or per rule. A more specific layer replaces a forward of the same name.
```yaml
ssh:
forwards:
web: {local: "8080:localhost:80"} # -L
socks: {dynamic: "1080"} # -D, SOCKS proxy
back: {remote: "9000:localhost:9000"} # -R
rules:
- match: {tag: postgres}
forwards:
db: {local: "5432:localhost:5432"}
```
```sh
netssh tunnel fsnbx1 web socks # only forwards: ssh -N, stops with Ctrl+C
netssh tunnel prod/db01 db 6379:localhost:6379 # names and ad hoc specs mixed
netssh --forward web fsnbx1 # shell plus forward (repeatable)
```
A value that is no configured name but a port spec (`[bind:]port:host:hostport`) becomes a local forward. `netssh tunnel` adds `-o ExitOnForwardFailure=yes`, so a port already in use fails instead of leaving a silent session. Without forward names it lists the forwards configured for the host. Forward names are completed after the host (`netssh tunnel fsnbx1 <Tab>`) and after `--forward`. In the TUI, `Ctrl+T` on a host opens an input with its configured forwards.
`sftp`, `scp`, `tunnel`, `hosts`, `multi`, and `sync` are subcommands; to connect to a host with one of these names, use `netssh -- sftp`.
### Static hosts
Hosts that are not in NetBox — a home router, a cloud VM, a customer machine — can be added to the config. netssh checks them before NetBox, so they work offline and even without any NetBox configured.
```sh
netssh hosts add router 192.168.1.1 --user admin --tag home
netssh hosts add backup backup.example.org --port 2222 --tag offsite
netssh hosts # list
netssh hosts add router 192.168.1.254 --replace # change the address, keep its SSH options
netssh hosts remove backup
```
The same in the config (or in `netssh configure` → *Static hosts*):
```yaml
hosts:
- name: router
address: 192.168.1.1 # IP address or DNS name
user: admin # optional, overrides ssh.default_user
port: 2222 # optional, overrides ssh.default_port
tags: [home] # optional, for ssh.rules
ssh: # optional, same keys as ssh: (proxy_jump, options, forwards, …)
proxy_jump: none
```
Static hosts behave like NetBox hosts everywhere: `netssh router`, `sftp`, `scp`, `tunnel`, shortcuts and rewrite rules, Tab completion, shell aliases, the TUI search and its recently-used list, and `ssh.rules` (match `kind: static` or their tags). Their SSH options are merged like an instance's: global → static host → rules. User and port on the command line still win.
- Names may contain letters, digits, dots, underscores, and hyphens, and are matched case-insensitively. They have no instance prefix.
- A static host wins over a NetBox host of the same name. Give them distinct names to keep both reachable.
- Static hosts never expire and are not touched by `cache refresh` or `cache clear`; removing one from the config removes it everywhere.
- `--netbox` notes and NetBox comments are not available for static hosts; local notes work.
### Multiple servers in one window
`netssh multi` opens one pane per host in tmux or zellij — for example every node of a Proxmox or Kubernetes cluster — and can send your typing to all of them at once.
```sh
netssh multi web01 web02 db01 # hosts, shortcuts, instance/host, static hosts
netssh multi tag:k8s-worker # all hosts with a NetBox tag (and static hosts with it)
netssh multi cluster:pve-fsn1 # the devices (nodes) of a NetBox virtualization cluster
netssh multi --kind vm cluster:pve-fsn1 # the cluster's VMs; --kind all for both
netssh multi @k8s # a saved group
netssh multi --sync @k8s # start with typing sent to every pane
netssh multi --dry-run cluster:pve-fsn1 # show the hosts and tmux/zellij commands
```
Each pane runs `netssh HOST`, so lookup, shortcuts, user and port, jump hosts, and rules work as for a single connection. `-l USER`, `--jump HOST`, and `--no-jump` apply to every pane. A pane whose connection fails stays open with the error until you press Enter.
**Groups** collect hosts and selectors under a name (or use `netssh configure` → *Multi-session*):
```yaml
groups:
k8s: [k8s-master1, "tag:k8s-worker"]
pve: ["cluster:pve-fsn1"]
all-web: ["@k8s", "tag:web", legacy-box]
multi:
multiplexer: auto # auto | tmux | zellij
panes_per_window: 9 # more hosts open in further windows/tabs
sync_key: S # tmux: prefix S = broadcast on/off (none = no key)
solo_key: e # tmux: prefix e = exclude/include this pane
```
**tmux and zellij.** With `auto`, netssh uses the multiplexer you are in; otherwise tmux, then zellij, whichever is installed (`--tmux` / `--zellij` choose explicitly).
| | tmux | zellij |
|---|---|---|
| Inside a session | new window in the current session | new tab in the current session |
| Outside | new session `netssh-NAME`, attached | new session from a generated layout |
| Layout | tiled; pane borders show the host | grid; pane titles show the host |
| Broadcast to all panes | `--sync`; toggle with `Ctrl+b S` or `netssh sync` | `--sync` inside zellij; toggle with `Ctrl+t` then `s` or `netssh sync` |
| Exclude one pane | `Ctrl+b e` (again: include) or `netssh sync --pane` | not possible — zellij syncs whole tabs |
| Shown in the border | `[SYNC]` receives broadcast, `[SOLO]` excluded | `(SYNC)` in the tab name |
**Keys in tmux.** The active pane border keeps the available broadcast/solo keys visible after attaching. See the [hotkey cheat sheet](#hotkey-cheat-sheet) for navigation and editor keys.
`S` and `e` are free in a default tmux (`E` would be "spread panes evenly"). netssh binds them after your prefix when it opens panes, but only if your own `tmux.conf` does not already use them — then it keeps your binding and says so. They act only in windows opened by `netssh multi`; elsewhere they just show a message. Change or turn them off with `multi.sync_key` / `multi.solo_key` (`none`), e.g. `sync_key: C-s` for `prefix Ctrl+s`.
**In the TUI**, mark hosts with `Space` (or all listed hosts with `Ctrl+A`) and press `Enter` to open them together.
`tag:` and `cluster:` ask NetBox (all instances); if NetBox is unreachable, netssh uses the cached hosts and prints a warning. More than 24 hosts need `--yes`. The 24-hour background cache refresh runs once, not in every pane.
### Default username
Set `ssh.default_user` in the config to avoid typing a username every time:
```sh
netssh my-router # → ssh -l admin 10.0.0.1
```
The default is only applied when no user is specified on the command line. An explicit user always takes precedence:
```sh
netssh root@my-router # user@ prefix wins → ssh root@10.0.0.1
netssh -l ops my-router # -l flag wins → ssh -l ops 10.0.0.1
```
### Default SSH port
Set `ssh.default_port` in the config to use a non-standard port without specifying it every time:
```sh
netssh my-router # → ssh -p 2222 -l admin 10.0.0.1
```
The default is only applied when `-p` is not already present in the SSH arguments. An explicit `-p` always takes precedence:
```sh
netssh -p 22 my-router # -p flag wins → ssh -p 22 10.0.0.1
```
### Host shortcuts
Configure short aliases so you can type `web01` instead of `web01.example.com`:
```yaml
shortcuts:
domains:
- .example.com
- .example.de
strip_hyphens: false # optional
rewrites: # optional, applied in order
- pattern: '^([a-z]+)[0-9]+-' # fsn1-bx1 → fsnbx1
replace: '$1'
```
Resolution order:
1. **Exact match** — the input is looked up as-is in the cache.
2. **Domain expansion** — if the input contains no dot, each configured domain is appended and tried (`web01` → `web01.example.com`). If no cache hit, NetBox is queried with the expanded name.
3. **Shortcut match** — the input and every cached hostname are shortened the same way and compared: lowercase, strip the domain suffix, apply each rewrite rule in order, then remove hyphens if `strip_hyphens` is set (`fsn1web01` → `fsn1-web01.example.com`, `fsnbx1` → `fsn1-bx1.hoster.de`). This only works when the host is already cached; run `netssh cache refresh` first.
**Rewrite rules** use Go regular expressions ([syntax](https://pkg.go.dev/regexp/syntax)); `replace` may refer to groups as `$1` or `${1}`. Every match in the name is replaced. Because the typed shortcut is rewritten too, write rules that leave an already shortened name unchanged: `^([a-z]+)[0-9]+-` matches `fsn1-bx1` but not `fsnbx1`. Shortcuts also become shell aliases and are offered by Tab completion when the full name does not match what you typed (`fsnb<Tab>` → `fsnbx1`).
Check what a hostname is shortened to, and whether the shortcut is unique in the cache:
```sh
$ netssh alias --test fsn1-bx1.hoster.de
fsn1-bx1.hoster.de → fsnbx1
matches fsn1-bx1.hoster.de
```
Domains may be configured with or without a leading dot. If several cached hosts normalize to the same shortcut, the connection is rejected; use the full hostname. Live host lookups check every result page and reject duplicate exact names.
| Input | Config | Resolved as |
|-------|--------|-------------|
| `web01` | `domains: [.example.com]` | `web01.example.com` |
| `fsn1web01` | `domains: [.example.com]`, `strip_hyphens: true` | `fsn1-web01.example.com` (cache only) |
| `fsnbx1` | `domains: [.hoster.de]`, rewrite `^([a-z]+)[0-9]+-` → `$1` | `fsn1-bx1.hoster.de` (cache only) |
#### Showing shortcuts
By default shortcuts work but stay out of sight. Set `shortcuts.show: true`
(or **Show shortcuts** in `netssh configure`, or `NETSSH_SHORTCUTS_SHOW=true`)
to see them:
- **TUI** — each host shows its alias next to the name: `fsn1-bx1.hoster.de → fsnbx1 10.0.0.5`.
- **Lists** — `netssh cache list` and `netssh hosts list` get an `ALIAS` column. Without the setting, `--aliases` shows it for one call.
- **Tab completion** — shortcuts are offered even when the full name matches what you typed: `fsn<Tab>` lists `fsn1-bx1.hoster.de` and `fsnbx1`.
The alias shown is the shell alias netssh generates for the host (see [Shell
aliases](#shell-aliases)), so you can type it directly. Hosts whose alias would
only replace dots (`web01_example_com`) show none.
```sh
$ netssh cache list --aliases
NAME ALIAS IP KIND CACHED AT
fsn1-bx1.hoster.de fsnbx1 10.0.0.5 device 2026-11-17T07:30:00+01:00
web01.other.de - 10.0.0.9 vm 2026-11-17T07:30:00+01:00
```
### Shell aliases
Generate shell aliases for all cached hosts based on the shortcut settings:
```sh
netssh alias # bash/zsh syntax
netssh alias --shell fish # fish syntax
```
Example output:
```bash
# netssh aliases (3 hosts) — source with: eval "$(netssh alias)"
alias db01='netssh db01.example.com'
alias fsn1web01='netssh fsn1-web01.example.com'
alias web01='netssh web01.example.com'
```
Add to your shell startup file:
```sh
# bash / zsh — in ~/.bashrc or ~/.zshrc
eval "$(netssh alias)"
# fish — in ~/.config/fish/config.fish
netssh alias --shell fish | source
# scripts
source <(netssh alias)
```
Without a `shortcuts` config, the alias name is derived from the full hostname with dots replaced by underscores (e.g. `web01_example_com`). If two hosts would produce the same alias name, the first entry wins and a warning is printed to stderr.
### Custom host commands
Define local commands once and automatically generate an alias for every cached
or static host. For example, if the existing shortcut rules turn
`xzi-groß1` into `xg1`, an alias prefix of `m` creates `mxg1`.
```yaml
shortcuts:
rewrites:
- pattern: '^xzi-groß'
replace: xg
commands:
mtr:
alias_prefix: m
args: [mtr, "{address}"]
ping:
alias_prefix: p
args: [ping, "-c", "3", "{address}"]
```
Use **Custom commands — mtr, ping, scripts** in `netssh configure` to add, edit or
remove rules. Enter the program separately and one argument per line.
An empty `alias_prefix` disables automatic aliases for that rule; it can
still be invoked with `netssh run`.
```sh
mxg1 # mtr to xzi-groß1's resolved address
pxg1 # ping the same address three times
mxg1 --report # append extra arguments to mtr
netssh run mtr office/xzi-groß1 # works without shell aliases
netssh run --dry-run mtr office/xzi-groß1
netssh run mtr office/xzi-groß1 -- --report
```
`{address}` uses the same host lookup, cache and resolver strategy chain as
SSH: management subnet, primary IP, named interface or hostname, according to
your configuration. The address is resolved **when the command runs**, rather
than copied into an alias. It can be an IPv4/IPv6 address or a hostname when
the resolver returns one. Static hosts use their configured address.
| Placeholder | Value |
|---|---|
| `{address}` | Address returned by the configured resolution strategy |
| `{host}` | Canonical hostname without the NetBox instance prefix |
| `{target}` | Full selector, e.g. `office/xzi-groß1` |
Commands run locally with your current user's permissions. Install the programs
you configure. Arguments are passed directly to the program without shell
evaluation; quotes, `$()`, pipes and redirects are literal argument content.
For direct `netssh run` invocations, put extra program flags after `--`.
Generated aliases already include that separator.
Generated command aliases use the existing SSH shortcut, including per-instance
`disable_prefix` and its collision handling. They retain the full instance
selector internally. Existing SSH aliases and the configured command alias have
priority; ambiguous command aliases are omitted. Prefixes must be unique across
rules. Use `netssh run COMMAND HOST` when an alias is omitted.
The shell hook regenerates these aliases on shell startup and cache refresh;
open a new shell after configuration changes. You can inspect them with
`netssh alias`. The TUI continues to show the SSH shortcut. A host named `run`
can still be reached with `netssh -- run`.
#### Own scripts
A rule can invoke an executable script directly, or run a script with an
interpreter such as Bash or Python. The script receives the same resolved
address and host placeholders as any other command.
```yaml
commands:
check:
alias_prefix: c
args: ["/home/user/bin/check-host", "{address}", "{host}"]
maintenance:
alias_prefix: maint
args: [bash, "/home/user/scripts/maintenance.sh", "{address}", "{target}"]
inspect:
alias_prefix: i
args: [python3, "/home/user/scripts/inspect.py", "--host", "{address}"]
```
For example, save this as `/home/user/bin/check-host`:
```sh
#!/bin/sh
set -eu
address=$1
host=$2
shift 2
printf 'Checking %s (%s)\n' "$host" "$address"
exec mtr "$address" "$@"
```
Make a directly invoked script executable with
`chmod +x /home/user/bin/check-host` and give it a valid shebang as above.
Scripts passed to `bash` or `python3` only need to be readable.
```sh
cxg1 --report
netssh run check office/xzi-groß1 -- --report
netssh run --dry-run inspect office/xzi-groß1
```
Use your actual absolute paths (paths containing spaces are supported), or put
executable scripts in `PATH`. Relative paths are relative to the directory
where you invoke the command; `~` and environment variables in `args` are not
expanded. The script runs locally, inherits the terminal and environment, and
its exit status is preserved. You can use `netssh run` inside other scripts
without loading any shell aliases.
### Interactive TUI
Run without arguments to open the interactive search:
```sh
netssh
```
The TUI opens with your most-recently-connected hosts (10 by default, configurable with `tui.history_limit`). Start typing to search all cached hosts or query NetBox live.
See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys.
**Filter** — press `Ctrl+F` to open a second input line:
```
Filter: tag:prod kind:vm status:active site:fsn1 location:building-a role:router platform:junos tenant:acme
```
`location:` matches any level of the location chain (name or slug), `rack:` the rack name.
Multiple `tag:` values are AND-combined. `site:`, `role:`, `platform:` and `tenant:` accept the NetBox name or slug; they need a cache written by this version (`netssh cache refresh`). The filter is applied locally against the cache; when doing a live NetBox search the first tag is also forwarded as a query parameter.
**User/port override** — press `Ctrl+E` on any highlighted host:
```
Connect as: admin@my-router:22
```
Edit the pre-filled value and press `Enter` to connect. `Esc` cancels. The configured default port is pre-filled. An explicit port 22 overrides a different configured default.
**Details and NetBox page** — `Ctrl+L` shows the host's NetBox details (site, rack, role, platform, status, IP addresses) without leaving the TUI; `Enter` connects from there. `Ctrl+G` opens the host's NetBox page in the browser.
**Columns** — by default each host shows its shortcut alias, IP, source and a badge such as `[offline]` when its NetBox status is not `active`. Choose other information, its order, and the optional `✓`/`✗` reachability check with `tui.columns` — see [TUI columns](#tui-columns-and-reachability).
### Server notes
Select a server in the TUI and press `Ctrl+N` for local notes, or `Ctrl+B` for
NetBox comments. Both open a multiline editor: `Ctrl+S` saves, `Esc` cancels.
Existing text is loaded before editing. A failed save keeps your draft in the editor.
Local notes and NetBox comments are independent; there is no automatic synchronization.
The CLI also supports reading, replacing, and appending notes:
```sh
netssh notes set web01 "Maintenance on Friday"
netssh notes append web01 "Reboot completed"
netssh notes show web01
printf 'First line\nSecond line\n' | netssh notes set web01
netssh notes append web01 --netbox --kind vm "Maintenance completed"
netssh notes show web01 --netbox --kind vm
```
`set` replaces the selected note; `append` preserves existing text and adds a new line.
Omitting the text reads it from standard input. An empty string clears the note.
For an uncached local host, specify `--kind device` or `--kind vm`; local operations
work offline. Use the full server name as displayed in the TUI.
Local notes live under `~/.config/netssh/notes/` (`$XDG_CONFIG_HOME` is respected),
with file permissions `0600` and atomic file replacement. They are keyed by NetBox
URL, host kind, and hostname, so cache refreshes and `cache clear` preserve them.
Changing the hostname or NetBox URL creates a separate note identity.
`--netbox` explicitly selects the device/VM's shared `comments` field and requires
a token with write permissions. Existing comments are loaded before modification;
ambiguous names are rejected (specify `--kind` where appropriate).
The client uses the API's ETag/If-Match conflict protection when the server provides
it; older NetBox versions without ETags use the server's last-write-wins behavior.
See the [NetBox REST API documentation](https://netbox.readthedocs.io/en/stable/integrations/rest-api/).
### Cache management
```sh
netssh cache list # show all cached entries
netssh cache list --aliases # … with each host's shortcut alias
netssh cache refresh # re-fetch ALL hosts from NetBox (paginated)
netssh cache refresh --tag prod # only hosts with the "prod" tag
netssh cache refresh --kind vm # only virtual machines
netssh cache refresh --tag prod --kind vm # combine filters
netssh cache clear # wipe the cache
```
The cache is refreshed automatically in the background every 24 hours. The trigger fires on the next SSH connect or TUI start after the interval has elapsed — there is no delay to the connection itself. The timestamp of the last refresh is stored in `~/.cache/netssh/last_refresh`.
To also trigger the check at shell startup (before you run any SSH command), install the shell hook:
```sh
netssh hook install # auto-detects $SHELL
netssh hook install --shell bash
netssh hook install --shell zsh
netssh hook install --shell fish
```
This adds a marked block (`# >>> netssh >>>` … `# <<< netssh <<<`) to your shell profile. To remove it:
```sh
netssh hook uninstall
```
The hook is a no-op when the cache is fresh — it adds no measurable delay to your shell startup.
### Search (for scripting)
```sh
netssh search app- # prints matching hostnames, one per line
```
## Hotkey cheat sheet
Keys depend on the current screen: for example, `Ctrl+B` opens NetBox comments
in the search, while tmux uses `Ctrl+b` as its default prefix.
“Then” means release the first combination before pressing the next key;
`S` is uppercase (`Shift+s`).
### Search and host selection
| Key | Action |
|-----|--------|
| type | filter hosts (300 ms debounce → NetBox query) |
| `Tab` | autocomplete top result into the search field |
| `↑` / `↓` | navigate results |
| `PageUp` / `PageDown` | previous/next results page |
| `Home` / `End` | first/last result (also moves the search cursor) |
| `Enter` | connect to selected host |
| `Space` | mark/unmark the host; with marks, `Enter` opens them side by side (`netssh multi`) |
| `Ctrl+A` | mark all listed hosts (again: unmark all) |
| `Ctrl+R` | choose SSH or a configured command; marked hosts run the command as a batch |
| `Ctrl+D` | toggle favorite for the selected host |
| `Ctrl+P` | toggle pin; pinning also adds the host to favorites |
| `Ctrl+O` | open an SFTP session to the selected host |
| `Ctrl+T` | start a tunnel: enter forward names or specs (`web, 8080:localhost:80`) |
| `Ctrl+E` | open inline editor to override user/port before connecting |
| `Ctrl+N` | edit local notes for the selected server |
| `Ctrl+B` | edit NetBox comments for the selected server |
| `Ctrl+F` | open/close the filter (`tag:prod kind:vm status:active site:fsn1 platform:junos`) |
| `Ctrl+L` | show NetBox details of the selected host (`Enter` connects, `Ctrl+G` opens NetBox, `Esc` back) |
| `Ctrl+G` | open the NetBox page of the selected host in the browser |
| `Esc` | quit search |
| `Ctrl+C` | quit from any TUI mode, including editors |
### Filters, connection/tunnel editors and notes
| Screen | Key | Action |
|---|---|---|
| Filter (`Ctrl+F`) | `Enter` | apply filter and return to results |
| Filter | `Esc` / `Ctrl+F` | close and clear the filter |
| User/port editor (`Ctrl+E`) | `Enter` | connect using the edited user/port |
| Tunnel editor (`Ctrl+T`) | `Enter` | start the requested forwards |
| User/port or tunnel editor | `Esc` | cancel and return to results |
| Local notes / NetBox comments | `Enter` | insert a new line |
| Local notes / NetBox comments | `Ctrl+S` | save |
| Local notes / NetBox comments | `Esc` | cancel and discard unsaved edits (when not loading/saving) |
| Any TUI screen | `Ctrl+C` | quit, discarding unsaved edits |
Text fields also support their standard cursor movement and editing keys.
### Multi-mode: tmux
The active pane's top border shows the configured broadcast/solo shortcuts
throughout the session. A narrow pane may clip the legend; zoom it with
`Ctrl+b` then `z` to make more room. `[SYNC]` means the pane receives broadcast;
`[SOLO]` means it is excluded.
The following uses tmux's default prefix `Ctrl+b`. Use your own prefix if
changed in `tmux.conf`; netssh's legend reads the configured prefix.
Navigation keys below are tmux defaults and can be remapped by your configuration.
| Key | Action |
|---|---|
| `Ctrl+b` then `S` | toggle broadcast for the current window (netssh default) |
| `Ctrl+b` then `e` | exclude/include the active pane in broadcast (netssh default) |
| `Ctrl+b` then arrow key | focus the pane in that direction |
| `Ctrl+b` then `o` | focus the next pane |
| `Ctrl+b` then `z` | zoom/unzoom the active pane |
| `Ctrl+b` then `n` / `p` | next/previous window |
| `Ctrl+b` then `w` | choose a window |
| `Ctrl+b` then `d` | detach; sessions keep running |
| `Ctrl+b` then `?` | show all current tmux bindings |
| `Enter` after a failed connection | close the pane displaying the error |
Change broadcast/solo keys with `multi.sync_key` and `multi.solo_key`;
`none` disables a binding. Existing user bindings take precedence and are
reported in the legend. Command alternatives are `netssh sync` and
`netssh sync --pane` (run locally inside the multiplexer).
Solo excludes a pane from broadcast; it does not toggle zoom.
### Multi-mode: zellij
Zellij's bottom status bar shows the keys for the current mode. These are
standard bindings; custom presets may differ.
| Key | Action |
|---|---|
| `Ctrl+t` then `s` | toggle broadcast for the entire tab |
| `Ctrl+p` then arrow key | move pane focus in pane mode |
| `Ctrl+p` then `f` | toggle fullscreen for the focused pane |
| `Ctrl+t` then left/right arrow | switch tabs in tab mode |
| `Enter` / `Esc` in a control mode | return to normal mode |
| `Ctrl+o` then `d` | detach; session keeps running |
| `Ctrl+g` | toggle locked mode to pass control keys to the remote application |
Zellij cannot exclude individual panes from broadcast. `netssh sync` toggles
the whole tab. When starting a new zellij session, enable broadcast manually
with `Ctrl+t` then `s`; `--sync` is applied automatically only inside an
existing zellij session.
## Operations
### Post scripts
`ssh.post_disconnect` runs a local shell command after the SSH, SFTP, SCP or
tunnel process exits. Configure it globally, per NetBox instance, per static host
or in an SSH rule. More specific values override broader ones; `none` disables
an inherited hook.
```yaml
ssh:
post_disconnect: /home/user/scripts/after-ssh.sh
rules:
- match: {tag: lab}
post_disconnect: none
commands:
maintenance:
alias_prefix: maint
args: [bash, /home/user/scripts/maintenance.sh, "{address}"]
post_run: /home/user/scripts/after-maintenance.sh
match: {instance: prod, tag: router, name: "router*"}
confirm: true
timeout: 5m
```
Post scripts receive the existing `NETSSH_HOST`, `NETSSH_TARGET`,
`NETSSH_INSTANCE`, `NETSSH_IP`, `NETSSH_KIND`, `NETSSH_TAGS` and
`NETSSH_CLIENT` variables, plus `NETSSH_COMMAND` and `NETSSH_EXIT_CODE`.
They run after a started process succeeds, fails or is cancelled, but not after
a failed pre-connect hook, failed process start, or a dry run. Output goes to
stderr, stdin is closed, and post scripts have a 30-second timeout.
A failing main process retains its exit code. If only the post script fails,
its exit code is returned. Hooks cannot run after the wrapper is forcibly killed
with SIGKILL. In multi-mode each connection runs its own post script.
Without a post hook or activity logging, SSH still replaces netssh directly.
With either enabled, netssh waits for the client while preserving terminal I/O.
### Favorites, pins and recent hosts
```yaml
tui:
history_limit: 25 # default 10; 0 = all used hosts
```
Favorites remain on the TUI's opening screen independently of the recent-host
limit. Pins appear first, followed by favorites and recent hosts. `Ctrl+D`
toggles a favorite; `Ctrl+P` toggles a pin. Removing a favorite also unpins it.
A saved host missing from the cache is still shown and resolved when selected.
```sh
netssh favorites
netssh favorites add prod/web01
netssh favorites pin prod/router01
netssh favorites unpin prod/router01
netssh favorites remove prod/web01
```
Favorites use canonical targets such as `prod/web01`, so identical hostnames in
different instances stay independent. Change the recent-host limit in
`netssh configure` → **History & activity logging**.
The TUI labels results as `live`, `static` or `cache AGE`; expired cache entries
also show `stale`. A partial NetBox outage keeps available and cached results
visible and identifies failed instances in the warning. Cached results are not
proof of current reachability; normal resolution rules still apply on connect.
### TUI actions, restrictions and confirmations
Press `Ctrl+R` on a host to choose SSH or one of your configured commands,
including MTR, Ping and scripts. With marked hosts, SSH opens the existing
multi-session layout; custom commands run through `netssh batch`.
A command's `match` uses the same `instance`, `tag`, `kind` and hostname
glob `name` selectors as SSH rules. All supplied selectors must match.
Restrictions apply to generated aliases, the TUI menu and execution itself.
The chosen command is checked again for every batch target.
`confirm: true` asks before execution. Non-interactive callers must explicitly
pass `--yes`; a batch asks once for the entire selected set. For example:
```sh
netssh run --yes maintenance prod/router01
netssh run --status maintenance prod/router01
```
The terminal shows elapsed runtime for custom commands; `--status` also
enables these messages when output is redirected. `timeout` accepts durations
such as `30s` or `5m`; no value means no timeout. Timeout exits with 124.
Ctrl+C cancels foreground commands. Background batch commands run in isolated
process groups; cancellation terminates their descendants, with a two-second
grace period before forced termination. Interactive programs retain foreground
terminal behavior.
### Diagnostics
```sh
netssh doctor # validate configuration, resolver, cache and programs
netssh doctor --online # additionally query each NetBox instance
netssh explain prod/web01 # resolve and print effective settings, without connecting
```
`explain` reports the chosen instance, address, cache/static/live source,
resolver order and recorded winning strategy, matching SSH rule numbers,
effective SSH options and hooks, and username/port defaults. It does not execute
hooks, mark the host as used or modify the cache. It can query NetBox if resolution
requires it. Older cache entries may lack the winning strategy; this is reported
explicitly. A cache refresh records that information for future explanations.
### Batch commands and retry
```sh
netssh batch --parallel 4 mtr prod/router01 prod/router02 -- --report
netssh batch --yes maintenance prod/router01 prod/router02
netssh batch --dry-run maintenance prod/router01 prod/router02
netssh batch --retry-failed --parallel 2 --yes
```
Batch mode accepts explicit host names and shortcuts. All targets are resolved
and checked before launching commands; duplicates are removed. Parallelism is
bounded (default 4, range 1–64). Output is grouped by host, with each exit code
and a final success/failure count. Batch commands receive no interactive stdin.
The last non-dry-run batch saves its command name, extra arguments and failed
canonical targets in `~/.config/netssh/last-failed.json` with mode `0600`.
Retry uses only that failed subset and rechecks the current configuration and
confirmation requirement. A successful batch clears the retry targets.
Concurrent batches each run independently; the last one to finish owns the
retry file. Command output is held in temporary private files and removed at
completion.
### Optional action history
```yaml
activity:
enabled: true # default false
retention_days: 30 # 0 = unlimited age
max_entries: 1000 # 0 = unlimited count
```
```sh
netssh history
netssh history clear
```
History records host, command name, start time, total duration and final exit
code for custom commands and managed SSH/SFTP/SCP/tunnel sessions. It does not
record arguments, environment variables, API tokens or command output.
Retention is applied when writing records or showing history.
Favorites, pins and action records live in `~/.config/netssh/activity.json`
(mode `0600`), with locking and atomic writes for simultaneous sessions.
`history clear` preserves favorites. `XDG_CONFIG_HOME` applies to both state
files. Configure logging and retention in **History & activity logging**.
### Export and import without secrets
```sh
netssh config export team.json
netssh config import team.json --dry-run
netssh config import team.json --yes
```
Export uses an allowlist: instance names/URLs, static hosts, groups, resolver
settings, shortcuts, completion, recent-host limit and SSH user/port defaults.
It excludes API tokens, credentials embedded in URLs, custom command definitions,
hooks, arbitrary SSH options/rules, local history, favorites and cache contents.
The output is JSON, which is also valid YAML.
Import accepts JSON or YAML and strips credentials and executable settings even
if the supplied file contains them. It preserves local commands and global SSH
rules/options. Existing credentials and per-instance SSH options are retained
only when the instance name and URL match; static-host SSH options are retained
only for the same name/address. New instances require a local token afterward.
Import validates before writing, requires confirmation (or `--yes`), and saves
the previous configuration as `netssh.yaml.before-import` with mode `0600`.
The preview does not modify files. Export/import is intended for shared host
configuration, not a complete backup of local executable settings or secrets.
## NetBox insights and host tools
These commands and settings use more of what NetBox knows about a host. Site,
role, platform, tenant, status and the NetBox ID are stored in the cache by
`netssh cache refresh` (and by every live lookup); caches written by older
versions get them with the next refresh.
### Host details and NetBox page
```sh
netssh info prod/sw1 # site, locations, rack/U, role, platform, tenant, type, serial, IPs per interface
netssh info --json web01 # the same as JSON
netssh open web01 # NetBox page in the browser ($BROWSER, open, or xdg-open)
netssh open --print web01 # only print the URL
```
```
sw1 (device, NetBox prod)
Status Active
Site FSN1
Location Building A › Floor 2 › Room 2.04
Rack R12 U20-21 (2U, front)
Path FSN1 › Building A › Floor 2 › Room 2.04 › R12 › U20
Role Core Switch
Platform Junos
Type Juniper QFX5120
Connect 10.0.0.7 (management_subnet, cache)
URL https://netbox.example.com/dcim/devices/7/
IP addresses
* 10.0.0.7/24 em0 sw1.example.com active
192.0.2.7/24 xe-0/0/1 active
```
`Location` lists every nested NetBox location from the one directly below the
site down to the device's own location (NetBox nests them through `parent`).
`Rack` shows the occupied units with the device height and mounting face.
`*` marks primary addresses. In the TUI, `Ctrl+L` shows the same view and
`Ctrl+G` opens the page. Static hosts have no NetBox record; `info` shows their
configured address, user and port.
### Reverse lookup
```sh
netssh whois 10.0.0.7
netssh whois mail.example.com # resolved through DNS first
netssh whois --json 10.0.0.7
```
```
10.0.0.7
IP 10.0.0.7/24 prod/sw1 (device) em0 active dns sw1.example.com
Prefix 10.0.0.0/8 (prod) "internal"
Prefix 10.0.0.0/24 (prod) active site FSN1 vlan 100 (mgmt)
Cache prod/sw1
```
All NetBox instances are queried; prefixes are listed from the widest to the
most specific. The exit code is 1 when nothing is found. A failing instance is
reported as a warning without hiding the answers of the others.
### DNS names and links
Customers and colleagues often know a host by a DNS name such as
`mx123.webseite.de` that is not the device or VM name in NetBox. When netssh
finds a name neither in NetBox nor in the cache, it resolves it through DNS,
looks the addresses up in NetBox (and the cache) and suggests the hosts that
own them:
```
$ netssh mx123.webseite.de
netssh: "mx123.webseite.de" is not in NetBox or the cache. DNS: mx123.webseite.de → 203.0.113.5
1) prod/web07 203.0.113.5 on eth0 (NetBox)
2) connect directly to mx123.webseite.de
Choose [1-2, Enter = 1, q = cancel]:
Save shortcut "mx123" → prod/web07 (netssh mx123, shell alias mx123)? [y/N or another name]: y
```
- Short names get their domain from `dns.domains` (see below), so `netssh mx123`
looks up `mx123.easysahre.de`. `shortcuts.domains` are not used here.
- Choosing a host connects with all of its settings (user, port, jump host,
rules). "Directly" connects to the DNS name with the global settings.
- The shortcut offer saves a **link** under `links:` in the config: from then on
`netssh mx123` connects to `prod/web07` without asking, and new shells get
the alias `mx123` (it also completes with `<Tab>`). Answer with another name
to choose it, or `n` to skip.
- Without a terminal (scripts) netssh does not choose, unless `dns.suggest:
always`: the error lists the suggestions, e.g.
`netssh prod/web07 # 203.0.113.5 on eth0 (NetBox)`.
- `netssh info` and `netssh open` use the same suggestion, and `netssh whois mx123`
also uses `dns.domains`.
```yaml
dns:
suggest: ask # ask | always (first suggestion, also in scripts) | never (no DNS lookup)
save_link: ask # ask | always (save the shortcut without asking) | never
domains: # tried in order for names without a dot
- match: "mx*" # shell glob on the typed name
domain: easysahre.de
- match: "ah*"
domain: jhfduwia.de
# - domain: example.com # without match: every name
```
A name without a dot gets the domain of every matching rule (`mx123` →
`mx123.easysahre.de`); only when no rule matches is the bare name looked up,
using the system resolver's search domains. A name with a dot is looked up as
typed. With `suggest: always` netssh connects to the first suggestion (NetBox
hosts first), or directly to the DNS name when no host owns the address. All
three settings are also in `netssh configure` → **Resolver & cache**.
Manage links directly:
```sh
netssh link add mx123 prod/web07 # or: netssh link add mx123 mx123.webseite.de
netssh link list
netssh link remove mx123
```
```yaml
links:
mx123: "prod/web07"
shop: "lab/web1"
```
A link points to a host netssh knows (NetBox or static host), not to another
link; its name must not be a static host. Links take precedence over NetBox
names. The target is fixed: if the DNS name later points elsewhere, update the
link.
### Status warning
Connecting to a host whose NetBox status is listed in `ssh.warn_status` asks first:
```
prod/web03 has NetBox status "decommissioning" — connect anyway? [y/N]
```
```yaml
ssh:
warn_status: [offline, planned, staged, failed, inventory, decommissioning] # default
# warn_status: [] # never ask
```
`--force` skips the question (`netssh --force web03`). Without a terminal
(scripts, pipes) netssh only prints a warning and connects, so automation keeps
working. `--dry-run` prints the warning as a comment. `copy-id` asks the same
question; `--ignore-status` skips it.
### TUI columns and reachability
`tui.columns` chooses what the TUI shows next to each hostname, in this order:
```yaml
tui:
columns: [reachability, ip, status, site, platform, tags]
reachability_timeout: 300 # ms, only used with the reachability column
```
```
✓ ★ prod/sw1 10.0.0.7 site:fsn1 platform:junos #core
✗ prod/web03 10.0.2.3 [decommissioning] site:nbg1 platform:ubuntu-24-04
```
| Column | Shows |
|---|---|
| `alias` | shortcut alias (`→ fsnbx1`), with `shortcuts.show` |
| `ip` | the address from the cache or NetBox |
| `kind` | `[device]`, `[vm]` or `[static]` |
| `source` | `[live]`, `[static]`, `[cache 5m]`, `stale` |
| `status` | `[offline]` etc. — only when the NetBox status is not `active` |
| `site`, `role`, `platform`, `tenant`, `cluster` | `site:fsn1` — the slug, like in the `Ctrl+F` filter |
| `location` | `⌂ FSN1 › Building A › Room 2.04 › R12 › U20` — site, every nested location, rack and lowest rack unit |
| `tags` | `#prod #web` |
| `reachability` | `✓` / `✗` before the name: TCP check of the SSH port |
Without `tui.columns` the TUI shows `[alias, ip, source, status]`; `columns: []`
shows only the names. Empty values are left out. `netssh configure` →
**History & activity logging** offers the same choice.
The **reachability check is optional** and off by default, because it opens a
TCP connection to every listed host. With the `reachability` column, every host
in the result list is probed on its SSH port (default port, or the static host's
port), in parallel and with `tui.reachability_timeout`. `✓` means the port
answers, `✗` that it does not. Hosts behind a jump host (`proxy_jump`,
`ProxyCommand`) cannot be checked from your machine and get no mark. Each host
is probed once per TUI session.
### Address fallback
```yaml
resolver:
strategies: [management_subnet, primary_ip]
fallback: true
fallback_timeout: 1000 # ms per address
```
With `resolver.fallback`, netssh checks the chosen address before connecting
(ssh, sftp, scp, tunnel). If it does not answer on the SSH port, netssh asks
NetBox for the addresses of all strategies (plus the primary IPv4 and IPv6) and
connects to the first one that answers:
```
netssh: 10.10.0.7 does not answer on port 22, using 192.0.2.7 (primary_ip)
```
The fallback address is used for this connection only; the cache keeps the
address of the configured order. Static hosts, hosts behind a jump host and
`--dry-run` are not checked. When no address answers, netssh still tries the
original one, so ssh reports the actual error.
### Rules by site, role, platform, tenant and status
`ssh.rules[].match` and `commands.*.match` also select by NetBox attributes
(name or slug, case-insensitive; status by value):
```yaml
ssh:
rules:
- match: {platform: junos}
host_key_checking: accept-new
options:
KexAlgorithms: +diffie-hellman-group14-sha1
HostKeyAlgorithms: +ssh-rsa
- match: {site: fsn1, role: core-switch}
proxy_jump: jump-fsn1.example.com
- match: {tenant: customer-a}
options: {User: customer-a} # any layered key
commands:
junos-cli:
args: [ssh, -t, "{address}", cli]
match: {platform: junos, status: active}
```
All selectors of a match must apply. `netssh explain HOST` lists the matching
rule numbers and the host's attributes.
### ssh-copy-id
```sh
netssh copy-id web01
netssh copy-id -i ~/.ssh/id_ed25519.pub tag:lab
netssh copy-id -l root cluster:pve-fsn1 --kind vm
netssh copy-id --dry-run @k8s # print the ssh-copy-id commands
```
Runs `ssh-copy-id` for each host with the same address, user, port, jump host
and `-o` options as `netssh HOST` (a jump host is passed as `-o ProxyJump=`,
since ssh-copy-id has no `-J`). Selectors work like for `netssh multi`. Hosts
run one after another so password prompts stay readable; a failing host does
not stop the others, and the exit code is 1 if any failed. `-f` and `-n` are
passed on to ssh-copy-id.
### known_hosts cleanup
When a live lookup or `netssh cache refresh` finds a new address for a host,
netssh says so:
```
netssh: address of web01 changed from 10.0.0.5 to 10.0.0.9
Remove the known_hosts entry of the old address 10.0.0.5? [y/N]
```
After a host was re-installed (new host key, same address), remove its keys with:
```sh
netssh known-hosts reset web01 # asks first; --yes for scripts
netssh known-hosts reset --dry-run web01 # print the ssh-keygen -R commands
```
Removed are the hostname, the current address, the previously cached address,
and `[name]:port` / `[address]:port` for a non-standard port, using
`ssh-keygen -R` (which keeps `known_hosts.old`). A `UserKnownHostsFile` from
`ssh.options` is honoured.
### Exports: Ansible inventory and ssh_config
```sh
netssh export ansible > inventory.yml # YAML (default)
netssh export ansible --format ini -o hosts.ini # INI
netssh export ansible --group-by site,role,platform # choose groups
netssh export ansible --tag prod --status active --no-static
netssh export ssh-config -o ~/.ssh/netssh.conf # Host blocks for other tools
```
Exports read the cache (run `netssh cache refresh` first) including static hosts.
Filters: `--tag`, `--kind`, `--instance`, `--status`, `--no-static`. A hostname
that exists in several instances is exported as `instance-name`.
**Ansible.** Each host gets `ansible_host` (the address netssh connects to),
`ansible_user`, `ansible_port` (if not 22) and, with a jump host,
`ansible_ssh_common_args: -o ProxyJump=…`. NetBox hosts additionally get
`netbox_instance`, `netbox_kind`, `netbox_status`, `netbox_site`, `netbox_role`,
`netbox_platform`, `netbox_tenant`, `netbox_cluster`, `netbox_location`
(`Building A/Room 2.04`), `netbox_rack`, `netbox_position`, `netbox_id` and
`netbox_tags` (`--no-vars` leaves them out). Groups are named
`<attribute>_<value>` such as `tag_prod`, `site_fsn1`, `platform_junos`;
`--group-by` accepts `tag, site, location, rack, role, platform, tenant, kind,
instance, cluster, status` (default `tag,site,role,platform,kind`) or `none`.
`location` puts a host into a group for every level, e.g. `location_building_a`
and `location_room_2_04`.
```yaml
all:
hosts:
sw1:
ansible_host: 10.0.0.7
ansible_user: admin
ansible_ssh_common_args: -o ProxyJump=jump.example.com
netbox_site: FSN1
netbox_platform: Junos
children:
platform_junos:
hosts:
sw1: {}
```
```ini
[all]
sw1 ansible_host=10.0.0.7 ansible_user=admin ansible_ssh_common_args="-o ProxyJump=jump.example.com" netbox_site=FSN1
[platform_junos]
sw1
```
In INI, `netbox_tags` is a comma-separated string, since INI has no lists.
**ssh_config.** One `Host` block per host with `HostName`, `User`, `Port`,
`ProxyJump`, host key checking, `AddressFamily` and `ssh.options`; shortcut
aliases become extra Host names (`--no-aliases` to skip). Include the file once
from `~/.ssh/config` with `Include ~/.ssh/netssh.conf`. `extra_args`, forwards
and hooks have no ssh_config equivalent and are not exported.
### Keyring tokens
```sh
netssh token migrate # move all tokens from netssh.yaml into the keyring
netssh token set prod # store a token (asked without echo)
echo "$TOKEN" | netssh token set prod
netssh token status # where each instance's token comes from
netssh token delete prod
```
Tokens are stored in the system keyring — Secret Service (GNOME Keyring,
KWallet) on Linux, Keychain on macOS — under the service `netssh` with the
instance name as account (`default` for the unnamed `netbox:` instance). The
config then contains `token: keyring`:
```yaml
netboxes:
- name: prod
url: https://netbox.example.com
token: keyring
```
`netssh doctor` checks that every keyring token can be read. On machines without
a keyring (servers, containers) keep the token in the file or use
`NETSSH_NETBOX_TOKEN`.
## Recipes
**Everything through a bastion, except the bastion itself**
```yaml
ssh:
proxy_jump: admin@bastion.example.com
rules:
- match: {name: "bastion*"}
proxy_jump: none
```
**A different jump host per site (NetBox instance)**
```yaml
netboxes:
- name: fsn
url: https://netbox.fsn.example.com
token: nbt_…
ssh: {proxy_jump: jump.fsn.example.com}
- name: hel
url: https://netbox.hel.example.com
token: nbt_…
ssh: {proxy_jump: jump.hel.example.com}
```
**Lab machines that are reinstalled every day**
```yaml
ssh:
rules:
- match: {instance: lab}
host_key_checking: off # prints a notice on every connection
```
**Database and web tunnels by tag**
```yaml
ssh:
forwards:
socks: {dynamic: "1080"} # browser via SOCKS on localhost:1080
rules:
- match: {tag: postgres}
forwards: {db: {local: "5432:localhost:5432"}}
- match: {tag: grafana}
forwards: {web: {local: "3000:localhost:3000"}}
```
```sh
netssh tunnel db01 db # psql -h localhost then reaches db01
netssh tunnel grafana01 web socks
```
**Short names for a hosting naming scheme** (`fsn1-bx1.hoster.de` → `fsnbx1`)
```yaml
shortcuts:
domains: [.hoster.de]
rewrites:
- pattern: '^([a-z]+)[0-9]+-'
replace: '$1'
```
```sh
netssh cache refresh && netssh alias --test fsn1-bx1.hoster.de
netssh fsnbx1 # also works as shell alias: fsnbx1
```
**Maintenance on all nodes of a cluster at once**
```sh
netssh multi --sync cluster:pve-fsn1 # every node in one window, typing goes to all
# … run apt upgrade on all nodes; Ctrl+b e on a node that needs something
# different excludes just that one, Ctrl+b S turns broadcast off for all
```
**Deploy a file and restart a service**
```sh
netssh scp ./app.tar prod/app01:/tmp/ && netssh prod/app01 'sudo systemctl restart app'
```
**Use netssh in scripts**
```sh
for host in $(netssh search web-); do
netssh "$host" uptime
done
```
## IP Resolution Strategies
Strategies are tried in the configured order; the first to succeed wins.
Cache refresh uses the same strategies as a direct connection. To allow the primary IP as a fallback, include `primary_ip` in the strategy list. Hosts that cannot be resolved, or have ambiguous names in the refresh results, are removed from the cache and reported as warnings.
| Name | Description |
|------|-------------|
| `primary_ip` | Returns the `primary_ip4` (or `primary_ip6`) set in NetBox. No extra API call. |
| `management_subnet` | Fetches all IPs for the host and returns the first one matching a configured CIDR. |
| `interface_name` | Fetches IPs attached to a specific named interface (e.g. `mgmt0`). |
| `hostname` | Uses the NetBox name instead of an IP, with `resolver.hostname_domain` appended to names without a dot. DNS or `~/.ssh/config` resolves it when ssh connects. No extra API call. |
**`hostname` strategy.** Its position in the chain decides when it applies:
```yaml
resolver:
strategies: [primary_ip, hostname] # IP if NetBox has one, otherwise the hostname
hostname_domain: example.com # web01 → web01.example.com
```
```yaml
resolver:
strategies: [hostname] # always connect by name, never by IP
```
Names that are not valid DNS hostnames (spaces, underscores) are skipped, so the next strategy is tried. The cache then stores the name instead of an IP, and `--dry-run` shows `ssh web01.example.com`. Compared with `ssh.target: hostname`, the strategy works as a fallback for hosts without an IP in NetBox and can be combined with `target: name`.
## Shell Completion
Install completion for the current user (no sudo required):
```sh
netssh completion install # auto-detects $SHELL
netssh completion install --shell bash
netssh completion install --shell zsh
netssh completion install --shell fish
```
| Shell | Install path |
|-------|-------------|
| bash | `~/.local/share/bash-completion/completions/netssh` |
| zsh | `~/.zfunc/_netssh` |
| fish | `~/.config/fish/completions/netssh.fish` |
For zsh, the netssh block in `~/.zshrc` (written by the installer and by
`netssh hook install --shell zsh`) adds `~/.zfunc` to `fpath` and registers the
completion with `compdef`, also when `compinit` already ran earlier — for
example via oh-my-zsh. Without the block, add `fpath=(~/.zfunc $fpath)` before
`compinit`. If `<Tab>` still completes files, clear the completion cache:
```zsh
rm -f ~/.zcompdump* && exec zsh
```
Completions are served from the local cache — no network request on every `<Tab>`.
With several NetBox instances, a hostname that exists in only one instance is
completed without the instance prefix (`web01`); names that exist in several
instances are offered as `prod/web01`, `staging/web01`. In bash, type the
instance prefix for those; zsh and fish offer them for the hostname alone.
The zsh script that `netssh completion zsh` prints is built for large caches:
5000 hosts complete in well under a second. To limit the number of hostnames
offered, set `completion.max_results`.
## Shell Hook
`netssh hook install` sets up two things in your shell profile:
1. **`netssh shell-init`** — runs on every new shell session. It regenerates the alias file from the current cache so your aliases are always up to date, and starts a background cache refresh if the last full refresh was more than 24 hours ago.
2. **A `source` line** (bash/zsh only) — loads the generated alias file so shortcuts like `web01` work immediately in every new shell. Fish uses `conf.d/` auto-sourcing instead, so no explicit source line is needed.
The alias file is also generated immediately during `hook install`, so aliases are available as soon as you reload your profile — no `cache refresh` needed first (though the cache must not be empty).
### Install
```sh
netssh hook install # auto-detects $SHELL
netssh hook install --shell bash
netssh hook install --shell zsh
netssh hook install --shell fish
```
Example output:
```
Hook installed → /home/user/.bashrc
Reload with: source /home/user/.bashrc
42 aliases written to /home/user/.cache/netssh/aliases.sh
```
What gets written to the profile:
**bash** (`~/.bashrc`):
```bash
# >>> netssh >>>
netssh shell-init
[ ! -f '/home/user/.cache/netssh/aliases.sh' ] || . '/home/user/.cache/netssh/aliases.sh'
# <<< netssh <<<
```
**zsh** (`~/.zshrc`) additionally registers the completion:
```zsh
fpath=('/home/user/.zfunc' $fpath)
if (( $+functions[compdef] )); then autoload -Uz _netssh && compdef _netssh netssh; fi
```
**fish** (`~/.config/fish/config.fish`):
```fish
# >>> netssh >>>
netssh shell-init
# <<< netssh <<<
```
Fish alias file (`~/.config/fish/conf.d/netssh.fish`) is written automatically and sourced by fish on every shell start without any profile changes.
| Shell | Profile file | Alias file |
|-------|-------------|------------|
| bash | `~/.bashrc` | `~/.cache/netssh/aliases.sh` |
| zsh | `~/.zshrc` | `~/.cache/netssh/aliases.sh` |
| fish | `~/.config/fish/config.fish` | `~/.config/fish/conf.d/netssh.fish` |
The install is idempotent — running it again changes nothing if the block is already present. Unmarked lines written by older versions are replaced by the block.
Reload your profile after installation to activate immediately:
```sh
source ~/.bashrc # bash
source ~/.zshrc # zsh
source ~/.config/fish/config.fish # fish
```
### Alias file updates
The alias file is regenerated automatically — no manual action needed:
| Event | Aliases updated |
|-------|----------------|
| New shell session (`shell-init`) | Yes — from the current local cache |
| `netssh cache refresh` | Yes — after the full refresh completes |
| Background 24h auto-refresh | Yes — after the background refresh completes |
Aliases for newly added hosts appear in the next shell session after a `cache refresh` has run.
### Uninstall
```sh
netssh hook uninstall # auto-detects $SHELL
netssh hook uninstall --shell zsh
```
Removes the netssh block and unmarked entries of older versions from the profile. The alias files (`aliases.sh`, `netssh.fish`) are left on disk. To remove netssh completely, use `netssh uninstall`.
### Relation to the connect-time auto-refresh
The shell hook and the connect-time trigger (which fires on each `netssh` invocation) are independent but complementary:
| Trigger | When it fires |
|---------|--------------|
| SSH connect / TUI start | On the next `netssh` call after 24 h have elapsed |
| Shell hook (`shell-init`) | On the first new shell session after 24 h have elapsed |
Both are non-blocking — the refresh runs as a background process and never delays your prompt or SSH connection. They share `~/.cache/netssh/last_refresh`, so only one background refresh runs per 24-hour window regardless of how many shells or connections are opened.
## Troubleshooting
**See what netssh would run.** `--dry-run` works for ssh, `sftp`, `scp`, and `tunnel` and prints the final command with the resolved IP and all added options.
| Message / symptom | Cause and fix |
|---|---|
| `host not found` | The name is not in NetBox (devices and VMs are searched). Check the spelling, or configure `shortcuts.domains` if you type short names. |
| `host "x" is not in hosts: and no NetBox is configured` | Only static hosts are configured. Add the host with `netssh hosts add`, or a NetBox with `netssh configure`. |
| `no strategy resolved an IP` | No resolver strategy found an address. Add `primary_ip` or `hostname` as a fallback at the end of `resolver.strategies`. |
| `ambiguous shortcut "x"; use a full hostname` | Several cached hosts shorten to the same name. Use the full name, or check with `netssh alias --test`. |
| `found 2 exact matches` | The name exists in several NetBox instances, or as both device and VM. Prefix the instance (`prod/web01`); for notes and the TUI also `--kind`. |
| Shortcut works for one host but not another | Shortcuts (hyphen folding, rewrites) only match cached hosts. Run `netssh cache refresh`. |
| Connection fails although a NetBox instance is down | Without an instance prefix, every instance must answer to rule out duplicates. Use `instance/host`; a fresh cache entry then needs no NetBox at all. |
| Wrong or outdated IP | Lower `cache.ttl`, run `netssh cache refresh`, and check the [strategy order](#ip-resolution-strategies). |
| `REMOTE HOST IDENTIFICATION HAS CHANGED` | The host was reinstalled or the IP reused. Remove the old key (`ssh-keygen -R <ip>`), consider `target: name`, or for lab hosts `host_key_checking: off`. |
| `unknown forward "x"` | The name is not configured for this host (forwards can be per instance or rule). The message lists the available ones. |
| `bind [127.0.0.1]:8080: Address already in use` | The local port of a forward is taken; `netssh tunnel` then exits instead of hanging. Choose another port. |
| Saving notes with `--netbox` fails with a permission error | The API token is read-only. Local notes work without write permission. |
| `<Tab>` completes files instead of hosts | Run `netssh completion install` and open a new terminal; for zsh also `rm -f ~/.zcompdump*`. |
| Aliases missing in a new shell | `netssh hook install`, then a new terminal. The cache must not be empty. |
| A host is named `sftp`, `scp`, `tunnel`, `hosts`, `multi`, `sync`, or like another subcommand | Use `netssh -- sftp`. |
| `netssh multi needs tmux or zellij` | Install one of them (`apt install tmux`, `brew install tmux`). |
| zellij shows empty boxes in its tab and status bar | Those are Powerline arrows; use a Nerd Font in your terminal, or add `simplified_ui true` to `~/.config/zellij/config.kdl`. |
| `cluster:x matches no hosts` | Clusters select devices by default; VMs need `--kind vm` or `--kind all`. The name is matched case-insensitively. |
| `netssh multi` panes use another config | Inside an existing tmux/zellij session, panes get your `HOME` and `XDG_*` paths, but not `NETSSH_*` variables (they would be visible to other users in the process list). Put such settings in the config file. |
## Uninstall
```sh
netssh uninstall --dry-run # show what would be removed
netssh uninstall # asks for confirmation
netssh uninstall --keep-config # keep config and notes for a reinstall
```
`netssh uninstall` removes:
- netssh blocks and unmarked entries of older versions from `~/.bashrc`, `~/.bash_profile`, `~/.bash_login`, `~/.profile`, `~/.zshrc`, `~/.zprofile`, `~/.zshenv`, and `config.fish`
- completion files for bash, zsh (also the oh-my-zsh cache), fish, and the command alias
- the cache directory `~/.cache/netssh/` including per-instance caches and aliases
- `~/.config/netssh.yaml` (a private backup `netssh.yaml.backup-<timestamp>` is kept, because it contains API tokens) and local notes
- the netssh binary; if it is in a protected directory, netssh prints the `sudo rm` command to run
Afterwards open a new terminal; for zsh also run `rm -f ~/.zcompdump*`.
## Development
Renovate monitors the release workflow's actions, the Go version in `go.mod`, and
all direct and indirect Go module dependencies. Go dependency updates also run
`go mod tidy` to keep `go.mod` and `go.sum` consistent.
```sh
go test ./... # includes offline installer/update tests
go build ./... # build all packages
```
End-to-end tests run against real services in a local Docker environment — two NetBox instances, SSH targets on separate networks, a jump host, an IPv6 host, tmux, zellij, and bash/zsh/fish. See [testenv/README.md](testenv/README.md). It is not part of CI/CD.
```sh
testenv/up.sh # build and start (first start ~6 min)
testenv/test.sh # 185 checks: connect, strategies, instances, shortcuts, rules, sftp/scp, tunnels, notes, shells, TUI, configurator, multi with tmux and zellij, and what xterm renders (screenshots + OCR)
testenv/down.sh
```
The test suite covers the cache, NetBox client (via `httptest`), IP resolver chain, the argument parsers for ssh, sftp, and scp, SSH options and rules, port forwards, config loading, the setup wizard, shortcut normalization and rewrites, completion, the TUI keys, and shell hook install/uninstall. Wrapper tests run the real command (`sftp`, `scp`, `tunnel` with `--dry-run`) in a subprocess against a pre-filled cache, so no NetBox or ssh server is needed.
Project layout:
| Directory | Content |
|---|---|
| `cmd/netssh` | Commands, host resolution, completion. |
| `internal/config` | Config loading, validation, SSH option layering. |
| `internal/netbox` | NetBox API client, multiple instances. |
| `internal/resolver` | IP resolution strategies. |
| `internal/cache` | Host cache. |
| `internal/ssh` | Argument parsing and option injection for ssh, sftp, scp. |
| `internal/multiplex` | tmux and zellij layouts for `netssh multi`. |
| `internal/shortcuts` | Shortcut normalization. |
| `internal/tui` | Interactive search. |
| `internal/setup` | Setup wizard. |
| `internal/hook` | Shell hooks, aliases, completion files. |
| `internal/notes` | Local notes and NetBox comments. |
## Disclaimer
This is a **vibe-coded** project: the entire codebase — architecture, implementation, tests, and docs — was generated by an AI assistant (Claude by Anthropic). No human has reviewed or audited the code. It works for the author's personal use case, but correctness and security are not guaranteed. Read the source before running it in sensitive environments.
## How it works
1. `netssh` checks whether the first argument is a known subcommand (`configure`, `cache`, `sftp`, `scp`, `tunnel`, `multi`, `notes`, …). If not, it enters SSH wrapper mode; without arguments it starts the TUI.
2. On first run, or when neither a NetBox nor static hosts are configured, the interactive setup wizard starts automatically.
3. It removes its own long options (`--dry-run`, `--jump`, `--no-jump`, `--forward`) and parses the remaining arguments with the flag table of the program it will run (ssh, sftp, or scp differ, e.g. in `-l` and `-P`) to find the destination: `[user@]host` for ssh, `[user@]host[:path]` for sftp, and every `host:path` operand for scp.
4. It resolves the host: first the static hosts from `hosts:` (by name or shortcut), then an exact cache lookup, a shortcut match against the cache (domains, rewrites, hyphen folding), and finally NetBox (`/api/dcim/devices/` and `/api/virtualization/virtual-machines/`, all instances in parallel) with the resolver chain. A fresh cache entry needs no network request; new results are cached.
5. It adds the user and port (a static host's own, else the defaults) in the program's syntax unless you gave your own.
6. It merges the SSH options for the host (global, instance, matching rules), resolves named forwards, and inserts the options before the first operand: jump host, host key checking, `-o` options, forwards, and for `tunnel` `-N` with `ExitOnForwardFailure`.
7. It replaces the hostname with the resolved IP (or the name, with `ssh.target: name`; IPv6 in brackets for sftp/scp) and calls `syscall.Exec` to become `ssh`, `sftp`, or `scp` — or prints the command with `--dry-run`.