2 Commits
Author SHA1 Message Date
Sebastian Unterschütz e5bde9c61f feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s
2026-11-18 10:41:36 +01:00
Sebastian Unterschütz 8d4915543e v1
Test / test (push) Successful in 3m36s
Release / release (push) Successful in 7m31s
2026-11-17 19:00:44 +01:00
59 changed files with 4040 additions and 147 deletions

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
name: Test
on:
pull_request:
push:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: Check formatting
run: |
unformatted=$(gofmt -l .)
if [ -n "$unformatted" ]; then
echo "gofmt needed for:"
echo "$unformatted"
exit 1
fi
- name: Vet
run: go vet ./...
- name: Run tests
run: go test -race ./...
+32
View File
@@ -1,5 +1,37 @@
# Changelog
## v1.1.0
- Add local post-disconnect/post-command scripts, execution timeouts, cancellation, per-command confirmation and host restrictions.
- Add configurable recent-host count, persistent favorites/pins, a TUI command menu and cache/live/stale indicators.
- Add doctor/explain diagnostics, parallel batch commands with failed-host retry, and optional bounded local action history.
- Add configuration export/import that excludes credentials and executable settings while preserving matching local credentials.
- Preserve terminal behavior and process exit status during supervised execution; test Bash/Python scripts, process cancellation, concurrency and batch retries.
## v1.0.0
- Consolidate the complete project into the initial v1 commit.
- Add configurable local host commands and automatically generated aliases, such as `mxg1` for `mtr` on host shortcut `xg1`. Commands resolve the destination at invocation using the configured resolver strategy.
- Support executable scripts and interpreter-based scripts, host/address placeholders, extra arguments, dry runs, and configuration through `netssh configure`.
- Include all previous SSH, SFTP/SCP, forwarding, multi-session, NetBox instance, shortcut, and security improvements.
## v0.0.29
- Add `ssh.pre_connect`: a shell command run locally before every connection (ssh, sftp, scp, tunnel), e.g. to check a VPN. A non-zero exit aborts the connection. Layered like `proxy_jump` (global → instance or static host → rules, `none` disables an inherited hook); the host is passed as `NETSSH_HOST`, `NETSSH_TARGET`, `NETSSH_INSTANCE`, `NETSSH_IP`, `NETSSH_KIND`, `NETSSH_TAGS`, `NETSSH_CLIENT`. Editable in `netssh configure`, also `NETSSH_SSH_PRE_CONNECT`. `--dry-run` shows it without running it.
- Add `shortcuts.show`: shows each host's shortcut alias (e.g. `fsnbx1` for `fsn1-bx1.hoster.de`) in the TUI and as an `ALIAS` column in `netssh cache list` and `netssh hosts list`, and offers shortcuts in Tab completion even when the full name matches. `--aliases` shows the column for a single call. Editable in `netssh configure`, also `NETSSH_SHORTCUTS_SHOW`.
## v0.0.25
- Security: `netssh.yaml` is read from the user config directory only. A file of that name in the working directory (e.g. of a cloned repository) was loaded when no user config existed, and could set ssh options such as `ProxyCommand` or a NetBox URL.
- Security: an address from NetBox or the cache that is neither an IP address nor a hostname is refused. A value such as `-oProxyCommand=…` was passed to ssh as an option.
- The resolver chain stops at an API failure instead of trying the next strategy. Before, a NetBox error in `management_subnet` or `interface_name` connected to the primary IP and cached it. A strategy that finds no address (including a missing interface) still falls through. Note: a token without permission to read IP addresses now gives an error instead of silently using `primary_ip`.
- `netssh --help` and `netssh -h` show netssh's help instead of `unknown option --help` and ssh's usage.
- Background cache refreshes are started at most every 5 minutes. While NetBox was unreachable, every command and every new shell started another one.
- `netbox.url` is validated like the URLs of named instances (HTTP or HTTPS, no query or fragment).
- Hosts with more than 100 IP addresses: all pages are read, so `management_subnet` no longer misses addresses.
- CI: tests, `go vet`, and a format check run on pull requests and pushes to `main`.
## v0.0.24
- Fix the `interface_name` resolver strategy: it sent filter names that NetBox ignores and therefore returned the host's first IP address instead of the named interface's. It now uses NetBox's `interface` and `vminterface` filters; a missing interface falls through to the next strategy.
+517 -27
View File
@@ -21,7 +21,10 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [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), [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)
- [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
- [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)
@@ -34,7 +37,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- **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 10 most-recently-connected hosts, no typing needed
- **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
@@ -147,12 +150,12 @@ A menu then gives access to every other setting; open only the sections you want
| 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) |
| 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), `shell.alias` |
| 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.
@@ -200,7 +203,7 @@ shortcuts:
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 and, if none exists there, from the current working directory. 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.
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
@@ -211,7 +214,7 @@ Every key, its default, and the section that explains it. Keys marked *layered*
| `netbox.url` | string | — | NetBox base URL (single instance). Use either `netbox` or `netboxes`. |
| `netbox.token` | string | — | API token; `nbt_…` is v2, anything else v1. |
| `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. |
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
| `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`. |
@@ -227,13 +230,20 @@ Every key, its default, and the section that explains it. Keys marked *layered*
| `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. |
| `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`) 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. |
| `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. |
@@ -249,8 +259,8 @@ These variables override the file. Lists are comma-separated (`NETSSH_SHORTCUTS_
| `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_PROXY_JUMP`, `NETSSH_SSH_HOST_KEY_CHECKING`, `NETSSH_SSH_TARGET`, `NETSSH_SSH_ADDRESS_FAMILY` | global `ssh.*` options |
| `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS` | `shortcuts.*` |
| `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` |
@@ -305,7 +315,41 @@ 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 and generated aliases retain the instance name (`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.
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.
@@ -364,6 +408,11 @@ A hint is shown during `netssh configure` if a legacy v1 token is entered.
| `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 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). |
@@ -473,7 +522,7 @@ Tags and kind are taken from the cache or the NetBox answer, so rules work offli
**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`) — the most specific non-empty value wins;
- 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.
@@ -484,6 +533,46 @@ $ 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`.
@@ -597,7 +686,9 @@ multi:
| 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.** `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`.
**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.
@@ -671,6 +762,27 @@ Domains may be configured with or without a leading dot. If several cached hosts
| `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:
@@ -704,6 +816,118 @@ 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:
@@ -712,23 +936,9 @@ Run without arguments to open the interactive search:
netssh
```
The TUI opens with your 10 most-recently-connected hosts. Start typing to search all cached hosts or query NetBox live.
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.
| Key | Action |
|-----|--------|
| type | filter hosts (300 ms debounce → NetBox query) |
| `Tab` | autocomplete top result into the search field |
| `↑` / `↓` | navigate results |
| `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+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 tag and kind filter (`tag:prod kind:vm`) |
| `Esc` / `Ctrl+C` | quit (or close filter/edit if open) |
See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys.
**Tag and kind filter** — press `Ctrl+F` to open a second input line:
@@ -785,6 +995,7 @@ See the [NetBox REST API documentation](https://netbox.readthedocs.io/en/stable/
```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
@@ -817,6 +1028,285 @@ The hook is a no-op when the cache is fresh — it adds no measurable delay to y
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 tag and kind filter (`tag:prod kind:vm`) |
| `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.
## Recipes
**Everything through a bastion, except the bastion itself**
+191
View File
@@ -0,0 +1,191 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
)
type batchRetry struct {
Command string
Hosts []string
Extra []string
}
type batchResult struct {
Host string
Code int
}
var batchExecutable = os.Executable
func batchPath() string {
return filepath.Join(filepath.Dir(config.Path()), "netssh", "last-failed.json")
}
func batchCmd() *cobra.Command {
var parallel int
var retry, yes, dry bool
cmd := &cobra.Command{Use: "batch COMMAND HOST... [-- EXTRA_ARGS...]", Short: "Run a configured command on hosts with bounded parallelism", RunE: func(cmd *cobra.Command, args []string) error {
if parallel < 1 || parallel > 64 {
return fmt.Errorf("parallel must be between 1 and 64")
}
cfg, err := config.Load()
if err != nil {
return err
}
work := batchRetry{}
if retry {
if len(args) > 0 {
return fmt.Errorf("--retry-failed takes no positional arguments")
}
data, err := os.ReadFile(batchPath())
if err != nil {
return err
}
if err = json.Unmarshal(data, &work); err != nil {
return err
}
} else {
split := cmd.ArgsLenAtDash()
if split >= 0 {
work.Extra = args[split:]
args = args[:split]
}
if len(args) < 2 {
return fmt.Errorf("specify COMMAND and at least one HOST")
}
work.Command, work.Hosts = args[0], args[1:]
}
command, ok := cfg.Commands[work.Command]
if !ok {
return fmt.Errorf("unknown command %q", work.Command)
}
if len(work.Hosts) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No failed hosts to retry.")
return nil
}
// Resolve and validate the entire list before launching any action.
var targets []string
seen := map[string]bool{}
for _, target := range work.Hosts {
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
if !command.Allowed(commandHost(h)) {
return fmt.Errorf("%s is not allowed on %s", work.Command, h.Name)
}
if !seen[h.Name] {
targets = append(targets, h.Name)
seen[h.Name] = true
}
}
if command.Confirm && !dry {
if err := confirmAction(fmt.Sprintf("Run %s on %d hosts", work.Command, len(targets)), yes); err != nil {
return err
}
}
executable, err := batchExecutable()
if err != nil {
return err
}
// Temporary output files bound memory even for very verbose commands.
dir, err := os.MkdirTemp("", "netssh-batch-")
if err != nil {
return err
}
defer os.RemoveAll(dir)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
jobs := make(chan int)
results := make(chan batchResult, len(targets))
var wg sync.WaitGroup
var output sync.Mutex
for n := 0; n < parallel; n++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
host := targets[i]
if ctx.Err() != nil {
results <- batchResult{host, 130}
continue
}
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] starting\n", host)
output.Unlock()
f, err := os.CreateTemp(dir, "output-")
if err != nil {
results <- batchResult{host, 1}
continue
}
argv := []string{executable, "run", "--yes"}
if dry {
argv = append(argv, "--dry-run")
}
argv = append(argv, work.Command, "--", host)
argv = append(argv, work.Extra...)
r := runner.Run(ctx, argv, runner.Options{Stdout: f, Stderr: f})
f.Close()
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] exit=%d duration=%s\n", host, r.Code, r.Duration.Round(time.Millisecond))
read, err := os.Open(f.Name())
if err == nil {
_, _ = io.Copy(cmd.OutOrStdout(), read)
read.Close()
}
output.Unlock()
results <- batchResult{host, r.Code}
}
}()
}
for i := range targets {
jobs <- i
}
close(jobs)
wg.Wait()
close(results)
failed := map[string]bool{}
for r := range results {
if r.Code != 0 {
failed[r.Host] = true
}
}
work.Hosts = nil
for _, host := range targets {
if failed[host] {
work.Hosts = append(work.Hosts, host)
}
}
if !dry {
data, _ := json.Marshal(work)
if err := os.MkdirAll(filepath.Dir(batchPath()), 0700); err != nil {
return err
}
if err := storage.WriteFile(batchPath(), data, 0600); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "%d succeeded, %d failed\n", len(targets)-len(failed), len(failed))
if len(failed) > 0 {
return fmt.Errorf("batch failed; retry with netssh batch --retry-failed")
}
return nil
}}
cmd.Flags().IntVar(&parallel, "parallel", 4, "Maximum simultaneous hosts (1-64)")
cmd.Flags().BoolVar(&retry, "retry-failed", false, "Repeat failed targets from the last batch")
cmd.Flags().BoolVar(&yes, "yes", false, "Confirm the batch action")
cmd.Flags().BoolVar(&dry, "dry-run", false, "Resolve and print commands without running")
return cmd
}
+26 -5
View File
@@ -14,27 +14,32 @@ import (
)
func hostsCmd() *cobra.Command {
var showAliases bool
cmd := &cobra.Command{
Use: "hosts",
Short: "Manage static hosts that are not in NetBox",
Long: `Static hosts are defined under hosts: in the config. They are found before
NetBox, work offline, and support shortcuts, rules (kind: static), aliases,
completion, sftp, scp, and tunnels like NetBox hosts.`,
RunE: func(cmd *cobra.Command, args []string) error { return listHosts() },
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
}
cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd())
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
func hostsListCmd() *cobra.Command {
return &cobra.Command{
var showAliases bool
cmd := &cobra.Command{
Use: "list",
Short: "List static hosts",
RunE: func(cmd *cobra.Command, args []string) error { return listHosts() },
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
}
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
func listHosts() error {
func listHosts(showAliases bool) error {
cfg, err := config.Load()
if err != nil {
return err
@@ -43,13 +48,29 @@ func listHosts() error {
fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS")
return nil
}
withAliases := showAliases || cfg.Shortcuts.Show
var aliases map[string]string
if withAliases {
// Aliases are unique across all hosts, so compute them with the cache.
c := newCache(cfg)
_ = c.Load()
aliases = shortcutAliases(c.All(), *cfg)
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
if withAliases {
fmt.Fprintln(w, "NAME\tALIAS\tADDRESS\tUSER\tPORT\tTAGS")
} else {
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
}
for _, host := range cfg.Hosts {
port := ""
if host.Port > 0 {
port = fmt.Sprint(host.Port)
}
if withAliases {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", host.Name, orDash(aliases[strings.ToLower(host.Name)]), host.Address, host.User, port, strings.Join(host.Tags, ","))
continue
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", host.Name, host.Address, host.User, port, strings.Join(host.Tags, ","))
}
return w.Flush()
+40 -1
View File
@@ -6,6 +6,7 @@ import (
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts"
)
@@ -29,6 +30,28 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion)
}
// shortcutAliases maps each target (lowercased) to the shell alias generated for
// it, but only where shortcuts actually shorten the displayed name: an alias that
// merely replaces dots with underscores ("web01_example_com") adds nothing.
// The aliases are the same ones netssh alias and the shell hook define.
func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string {
out := make(map[string]string)
if !cfg.Shortcuts.Enabled() {
return out
}
plain := strings.NewReplacer(".", "_", "/", "_")
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
if alias.Host == "" || alias.Command != "" {
continue // the command alias for netssh itself
}
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
continue
}
out[strings.ToLower(alias.Host)] = alias.Name
}
return out
}
func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) string {
return func(target string) string {
source, name := netbox.SplitTarget(target)
@@ -48,6 +71,9 @@ func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) st
// Names present in several instances stay qualified ("prod/web01").
// Hosts whose full name does not match are offered by their configured
// shortcut instead ("fsnb" → "fsnbx1" for fsn1-bx1.example.com).
//
// With shortcuts.show, shortcuts are also offered for hosts whose full name
// matches, so "fsn" lists both fsn1-bx1.example.com and fsnbx1.
func hostCompletions(entries []cache.Entry, toComplete string, sc config.ShortcutsConfig) []string {
prefix := strings.ToLower(toComplete)
qualifiedInput := strings.Contains(prefix, "/")
@@ -75,7 +101,20 @@ func hostCompletions(entries []cache.Entry, toComplete string, sc config.Shortcu
}
}
if sc.Enabled() {
names = append(names, shortcutCompletions(entries, unmatched, prefix, sc)...)
candidates := unmatched
if sc.Show {
candidates = entries
}
offered := make(map[string]bool, len(names))
for _, name := range names {
offered[strings.ToLower(name)] = true
}
for _, name := range shortcutCompletions(entries, candidates, prefix, sc) {
if !offered[name] {
offered[name] = true
names = append(names, name)
}
}
}
sort.Strings(names)
return names
+181 -32
View File
@@ -17,6 +17,7 @@ import (
tea "charm.land/bubbletea/v2"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
@@ -30,6 +31,7 @@ import (
// managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode.
var managedSubcommands = map[string]bool{
"doctor": true, "explain": true, "favorites": true, "history": true, "batch": true, "config": true,
"configure": true,
"notes": true,
"search": true,
@@ -48,6 +50,7 @@ var managedSubcommands = map[string]bool{
"hosts": true,
"multi": true,
"sync": true,
"run": true,
}
func main() {
@@ -62,8 +65,22 @@ func main() {
return
}
// ssh has neither option, so both can only mean netssh's own help.
if args[0] == "--help" || args[0] == "-h" {
root := rootCmd()
root.SetArgs([]string{"help"})
if err := root.Execute(); err != nil {
os.Exit(1)
}
return
}
if managedSubcommands[args[0]] {
if err := rootCmd().Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
os.Exit(1)
}
return
@@ -197,25 +214,43 @@ func prependArgs(extra, args []string, dests []int) []string {
// resolvedHost is a NetBox host with the address to connect to.
type resolvedHost struct {
Name string // cache/selector name, may carry an instance prefix
Kind string
IP string
Tags []string
Origin string
Resolver string
CachedAt time.Time
Name string // cache/selector name, may carry an instance prefix
Kind string
IP string
Tags []string
}
// resolveTarget finds host in the cache (also by shortcut) or NetBox and
// resolves its address. It exits on failure.
func resolveTarget(cfg *config.Config, host string) resolvedHost {
result, err := resolveTargetE(cfg, host, true)
if err != nil {
fatalf("%v", err)
}
return result
}
func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, error) {
c := newCache(cfg)
_ = c.Load()
maybeBackgroundRefresh(cfg, c)
if record {
maybeBackgroundRefresh(cfg, c)
}
source, _ := netbox.SplitTarget(host)
useCache := len(cfg.NetBoxes) == 0 || source != ""
used := func(entry cache.Entry) resolvedHost {
c.MarkUsed(entry.Name)
_ = c.Save()
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags}
if record {
c.MarkUsed(entry.Name)
_ = c.Save()
}
origin := "cache"
if entry.Static {
origin = "static"
}
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags, Origin: origin, Resolver: entry.Resolver, CachedAt: entry.CachedAt}
}
// Static hosts from the config win and need no NetBox.
@@ -226,16 +261,16 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
}
entry, found, err := c.GetStatic(host, normalize)
if err != nil {
fatalf("%v", err)
return resolvedHost{}, err
}
if found {
return used(entry)
return used(entry), nil
}
}
// Cache hit with a fresh TTL — connect directly without querying NetBox.
if entry, fresh := c.Get(host); fresh && useCache {
return used(entry)
return used(entry), nil
}
// Shortcut cache lookup: scan entries whose normalized name matches the input.
@@ -246,11 +281,11 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
normalize := normalizeTarget(cfg.Shortcuts, source != "")
entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize)
if err != nil {
fatalf("%v", err)
return resolvedHost{}, err
}
if found {
if fresh {
return used(entry)
return used(entry), nil
}
// Stale shortcut match — use canonical name for NetBox re-fetch.
lookupHost = entry.Name
@@ -258,7 +293,7 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
}
if !cfg.HasNetBox() {
fatalf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host)
return resolvedHost{}, fmt.Errorf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host)
}
nbClient := newNetBoxClient(cfg)
@@ -269,33 +304,35 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled {
entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false))
if cacheErr != nil {
fatalf("%v", cacheErr)
return resolvedHost{}, cacheErr
}
if found {
target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains)
}
}
if err != nil {
fatalf("NetBox: %v", err)
return resolvedHost{}, fmt.Errorf("NetBox: %w", err)
}
if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind {
return used(cached)
return used(cached), nil
}
chain, err := resolver.New(cfg.Resolver)
if err != nil {
fatalf("resolver: %v", err)
return resolvedHost{}, err
}
ip, err := chain.Resolve(ctx, &target, nbClient)
ip, strategy, err := chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil {
fatalf("IP resolution for %q: %v", host, err)
return resolvedHost{}, fmt.Errorf("IP resolution for %q: %w", host, err)
}
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster}
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy}
c.Upsert(entry)
return used(entry)
result := used(entry)
result.Origin = "live"
return result, nil
}
// findSSHHost uses the paginated, ambiguity-checking lookup for connection
@@ -320,6 +357,9 @@ func findSSHHost(ctx context.Context, client *netbox.Client, name string, domain
// connectHost applies the SSH options configured for the host and execs the client.
func connectHost(cfg *config.Config, client internalssh.Client, flags internalssh.WrapperFlags, host resolvedHost, dests []int, args []string) {
if !internalssh.ValidAddress(host.IP) {
fatalf("refusing address %q for %s: not an IP address or hostname (check NetBox, or run netssh cache clear)", host.IP, host.Name)
}
opts := hostOptions(cfg, host)
if len(flags.Forwards) > 0 {
forwardArgs, err := internalssh.ForwardArgs(flags.Forwards, opts.Forwards)
@@ -335,8 +375,28 @@ func connectHost(cfg *config.Config, client internalssh.Client, flags internalss
}
fatalf("name a forward or a spec such as 8080:localhost:80; forwards for %s: %s", host.Name, available)
}
if err := runPreConnect(opts.PreConnectCommand(), host, client.Name, flags.DryRun); err != nil {
fatalf("%v", err)
}
_, name := netbox.SplitTarget(host.Name)
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags)
result := client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags)
post := config.HookCommand(opts.PostDisconnect)
if flags.DryRun {
if post != "" {
fmt.Fprintf(os.Stderr, "# post_disconnect (skipped in --dry-run): %s\n", post)
}
}
if !flags.DryRun && (post != "" || cfg.Activity.Enabled) {
if result.Notice != "" {
fmt.Fprintln(os.Stderr, result.Notice)
}
code := supervise(cfg, host, client.Name, append([]string{client.Name}, result.Args...), post, 0, false, os.Stdin, os.Stdout, os.Stderr)
if code != 0 {
os.Exit(code)
}
return
}
execClient(client, result, flags)
}
// hostOptions merges the global, instance, and rule SSH options for host.
@@ -373,6 +433,54 @@ func runTUI() {
}
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
m.SetHostLabel(cfg.HostLabel)
m.SetHistoryLimit(cfg.TUI.HistoryLimit)
state, stateErr := activity.Read()
if stateErr != nil {
fmt.Fprintf(os.Stderr, "favorites: %v\n", stateErr)
}
m.SetPreferences(state.Favorites, state.Pinned, func(favorites, pinned map[string]bool) error {
err := activity.Update(func(s *activity.State) {
merge := func(dst, previous, next map[string]bool) {
for name, value := range next {
if previous[name] != value {
if value {
dst[name] = true
} else {
delete(dst, name)
}
}
}
for name, value := range previous {
if value && !next[name] {
delete(dst, name)
}
}
}
merge(s.Favorites, state.Favorites, favorites)
merge(s.Pinned, state.Pinned, pinned)
})
if err == nil {
state.Favorites = favorites
state.Pinned = pinned
}
return err
})
m.SetCommands(func(name, kind string, tags []string) []string {
var names []string
h := commandHost(resolvedHost{Name: name, Kind: kind, Tags: tags})
for name, c := range cfg.Commands {
if c.Allowed(h) {
names = append(names, name)
}
}
sort.Strings(names)
return names
})
if cfg.Shortcuts.Show {
aliases := shortcutAliases(c.All(), *cfg)
m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] })
}
m.SetNotes(notes.New(cfg.NetBox.URL, nbClient))
m.SetForwards(func(name, kind string, tags []string) []string {
return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags}))
@@ -391,6 +499,22 @@ func runTUI() {
if host == nil {
return
}
if host.Command != "" {
args := []string{"run", host.Command, "--", host.Name}
if len(host.Targets) > 0 {
args = append([]string{"batch", host.Command}, host.Targets...)
}
root := rootCmd()
root.SetArgs(args)
if err := root.Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
fatalf("%v", err)
}
return
}
if host.Action == tui.ActionMulti {
if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil {
fatalf("%v", err)
@@ -417,11 +541,12 @@ func runTUI() {
if err != nil {
fatalf("resolver: %v", err)
}
host.IP, err = chain.Resolve(ctx, &target, nbClient)
var strategy string
host.IP, strategy, err = chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil {
fatalf("IP resolution: %v", err)
}
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster})
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy})
tags = target.Tags
}
fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP)
@@ -507,7 +632,7 @@ func rootCmd() *cobra.Command {
},
}
root.AddCommand(notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd())
root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd())
// cobra builds the "completion" command lazily; force init so we can extend it.
root.InitDefaultCompletionCmd()
@@ -655,7 +780,8 @@ func cacheCmd() *cobra.Command {
}
func cacheListCmd() *cobra.Command {
return &cobra.Command{
var showAliases bool
cmd := &cobra.Command{
Use: "list",
Short: "Show all cached entries",
RunE: func(cmd *cobra.Command, args []string) error {
@@ -671,13 +797,31 @@ func cacheListCmd() *cobra.Command {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT")
if !showAliases && !cfg.Shortcuts.Show {
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT")
for _, e := range entries {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
}
return w.Flush()
}
aliases := shortcutAliases(entries, *cfg)
fmt.Fprintln(w, "NAME\tALIAS\tIP\tKIND\tCACHED AT")
for _, e := range entries {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", e.Name, orDash(aliases[strings.ToLower(e.Name)]), e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
}
return w.Flush()
},
}
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
// orDash keeps empty table cells visible.
func orDash(s string) string {
if s == "" {
return "-"
}
return s
}
func cacheClearCmd() *cobra.Command {
@@ -751,7 +895,7 @@ func cacheRefreshCmd() *cobra.Command {
continue
}
ip, err := chain.Resolve(ctx, e, nbClient)
ip, strategy, err := chain.ResolveWithStrategy(ctx, e, nbClient)
if err != nil {
// Do not turn a failed configured strategy into a fresh
// primary-IP cache hit that bypasses the resolver.
@@ -762,7 +906,7 @@ func cacheRefreshCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err)
continue
}
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster})
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Resolver: strategy})
written++
}
@@ -1000,6 +1144,9 @@ func hookUninstallCmd() *cobra.Command {
return cmd
}
// refreshRetryInterval is the pause between background refresh attempts.
const refreshRetryInterval = 5 * time.Minute
// maybeBackgroundRefresh starts a background `netssh cache refresh` if the cache
// has not been fully refreshed within the last 24 hours.
func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) {
@@ -1007,7 +1154,9 @@ func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) {
if !cfg.HasNetBox() || os.Getenv("NETSSH_NO_REFRESH") != "" {
return
}
if !c.NeedsRefresh(24 * time.Hour) {
// While NetBox is unreachable the cache stays stale; without the retry
// interval every command and every new shell would start another refresh.
if !c.ClaimRefresh(24*time.Hour, refreshRetryInterval) {
return
}
self, err := os.Executable()
+193
View File
@@ -0,0 +1,193 @@
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
"github.com/spf13/cobra"
)
func doctorCmd() *cobra.Command {
var online bool
cmd := &cobra.Command{Use: "doctor", Short: "Check configuration, programs, cache and optional NetBox connectivity", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
failed := false
report := func(label string, err error) {
if err != nil {
failed = true
fmt.Fprintf(cmd.OutOrStdout(), "FAIL %s: %v\n", label, err)
} else {
fmt.Fprintf(cmd.OutOrStdout(), "OK %s\n", label)
}
}
report("configuration", nil)
_, err = resolver.New(cfg.Resolver)
report("resolver", err)
programs := map[string]bool{"ssh": true, "sftp": true, "scp": true}
for name, c := range cfg.Commands {
programs[c.Args[0]] = true
if len(c.Args) > 1 && !strings.HasPrefix(c.Args[1], "-") {
switch c.Args[0] {
case "bash", "sh", "python", "python3":
f, err := os.Open(c.Args[1])
if err == nil {
f.Close()
}
report("script "+name, err)
}
}
}
var names []string
for p := range programs {
names = append(names, p)
}
sort.Strings(names)
for _, p := range names {
_, err := exec.LookPath(p)
report("program "+p, err)
}
report("cache", newCache(cfg).Load())
if online {
sources := cfg.NetBoxes
if len(sources) == 0 && cfg.NetBox.URL != "" {
sources = []config.NetBoxConfig{cfg.NetBox}
}
for _, s := range sources {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := netbox.NewClient(s.URL, s.Token, s.TokenVersion).Search(ctx, "", netbox.SearchOptions{})
cancel()
report("NetBox "+s.Name, err)
}
}
if failed {
return fmt.Errorf("doctor found problems")
}
return nil
}}
cmd.Flags().BoolVar(&online, "online", false, "Also query every NetBox instance")
return cmd
}
func explainCmd() *cobra.Command {
return &cobra.Command{Use: "explain HOST", Short: "Explain actual host resolution and effective SSH settings without connecting", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, args[0], false)
if err != nil {
return err
}
selectors := commandHost(h)
user, port := hostDefaults(cfg, h)
opts := hostOptions(cfg, h)
var rules []int
for i, r := range cfg.SSH.Rules {
if r.Match.Matches(selectors) {
rules = append(rules, i+1)
}
}
strategy := h.Resolver
if strategy == "" {
if h.Origin == "static" {
strategy = "static address"
} else {
strategy = "not recorded in this cache entry"
}
}
return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{
"target": h.Name, "instance": selectors.Instance, "address": h.IP, "source": h.Origin, "cached_at": h.CachedAt,
"resolver_order": cfg.Resolver.Strategies, "resolver_used": strategy, "matching_rules": rules, "user": user, "port": port, "ssh": opts,
})
}}
}
func favoritesCmd() *cobra.Command {
cmd := &cobra.Command{Use: "favorites", Short: "List or change favorite and pinned hosts", RunE: func(cmd *cobra.Command, _ []string) error {
s, err := activity.Read()
if err != nil {
return err
}
var names []string
for n := range s.Favorites {
if s.Favorites[n] {
names = append(names, n)
}
}
sort.Strings(names)
for _, n := range names {
marker := "favorite"
if s.Pinned[n] {
marker = "pinned"
}
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", n, marker)
}
return nil
}}
for _, action := range []string{"add", "remove", "pin", "unpin"} {
cmd.AddCommand(&cobra.Command{Use: action + " HOST", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
target := args[0]
if action == "add" || action == "pin" {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
target = h.Name
}
return activity.Update(func(s *activity.State) {
switch action {
case "add":
s.Favorites[target] = true
case "pin":
s.Favorites[target] = true
s.Pinned[target] = true
case "unpin":
delete(s.Pinned, target)
case "remove":
delete(s.Favorites, target)
delete(s.Pinned, target)
}
})
}})
}
return cmd
}
func historyCmd() *cobra.Command {
cmd := &cobra.Command{Use: "history", Short: "Show optional local action history", RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if err := activity.Update(func(s *activity.State) { activity.Prune(s, cfg.Activity) }); err != nil {
return err
}
s, err := activity.Read()
if err != nil {
return err
}
for i := len(s.Records) - 1; i >= 0; i-- {
r := s.Records[i]
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\texit=%d\t%s\n", r.Time.Format(time.RFC3339), r.Host, r.Command, r.Code, r.Duration.Round(time.Millisecond))
}
return nil
}}
cmd.AddCommand(&cobra.Command{Use: "clear", Short: "Delete recorded actions, preserving favorites", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error {
return activity.Update(func(s *activity.State) { s.Records = nil })
}})
return cmd
}
+258
View File
@@ -0,0 +1,258 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func writeOperationsConfig(t *testing.T, extra string) {
t.Helper()
prepareTransferTest(t)
data := `hosts:
- name: router
address: 192.0.2.1
tags: [router]
- name: fail
address: 192.0.2.2
- name: okay
address: 192.0.2.3
resolver:
strategies: [primary_ip]
` + extra
if err := os.WriteFile(config.Path(), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
func TestPostHooksFiltersAndConfirmation(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "post")
writeOperationsConfig(t, fmt.Sprintf(`
commands:
success:
args: [sh, -c, "exit 0", "{host}"]
post_run: 'printf "%%s:%%s" "$NETSSH_HOST" "$NETSSH_EXIT_CODE" > %s'
failure:
args: [sh, -c, "exit 7", "{host}"]
post_run: 'printf "%%s" "$NETSSH_EXIT_CODE" > %s; exit 9'
postfail:
args: [sh, -c, "exit 0", "{host}"]
post_run: exit 9
protected:
args: [sh, -c, "exit 0", "{host}"]
confirm: true
match: {tag: router, kind: static, name: "rou*"}
timeout:
args: [sh, -c, "sleep 20", "{host}"]
timeout: 50ms
activity:
enabled: true
retention_days: 30
max_entries: 50
`, marker, marker))
if out, err := runNetssh(t, "run", "--dry-run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("dry-run executed post hook")
}
if out, err := runNetssh(t, "run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(marker)
if string(data) != "router:0" {
t.Fatal(string(data))
}
for _, tc := range []struct {
name string
code int
}{{"failure", 7}, {"postfail", 9}, {"timeout", 124}} {
_, err := runNetssh(t, "run", tc.name, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != tc.code {
t.Fatalf("%s: %v", tc.name, err)
}
}
data, _ = os.ReadFile(marker)
if string(data) != "7" {
t.Fatal(string(data))
}
if out, err := runNetssh(t, "run", "protected", "router"); err == nil || !strings.Contains(out, "--yes") {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "router"); err != nil {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "okay"); err == nil || !strings.Contains(out, "not allowed") {
t.Fatalf("%q %v", out, err)
}
state, err := activity.Read()
if err != nil || len(state.Records) != 5 {
t.Fatalf("%+v %v", state, err)
}
}
func TestSSHPostDisconnect(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "after")
writeOperationsConfig(t, fmt.Sprintf("ssh:\n post_disconnect: 'printf \"%%s\" \"$NETSSH_EXIT_CODE\" > %s'\n", marker))
if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nexit 6\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
_, err := runNetssh(t, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 6 {
t.Fatal(err)
}
data, _ := os.ReadFile(marker)
if string(data) != "6" {
t.Fatalf("post: %s", data)
}
}
func TestExplainAndFavorites(t *testing.T) {
writeOperationsConfig(t, "tui:\n history_limit: 25\nssh:\n rules:\n - match: {tag: router}\n post_disconnect: echo done\n")
out, err := runNetssh(t, "explain", "router")
if err != nil {
t.Fatalf("%s %v", out, err)
}
var result map[string]any
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatal(err)
}
if result["source"] != "static" || result["address"] != "192.0.2.1" {
t.Fatal(result)
}
for _, args := range [][]string{{"favorites", "pin", "router"}, {"favorites", "add", "okay"}} {
if out, err := runNetssh(t, args...); err != nil {
t.Fatalf("%s %v", out, err)
}
}
state, err := activity.Read()
if err != nil || !state.Pinned["router"] || !state.Favorites["okay"] {
t.Fatalf("%+v %v", state, err)
}
if out, err := runNetssh(t, "favorites", "remove", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
state, _ = activity.Read()
if state.Pinned["router"] || state.Favorites["router"] {
t.Fatal(state)
}
}
func TestPortableConfigOmitsAllExecutableSecrets(t *testing.T) {
c := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://user:URLSECRET@netbox.example", Token: "TOKEN", SSH: config.SSHOptions{PreConnect: "HOOKSECRET"}}},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{Options: map[string]string{"ProxyCommand": "OPTIONSECRET"}, PostDisconnect: "POSTSECRET"}},
Commands: map[string]config.HostCommand{"check": {Args: []string{"echo", "COMMANDSECRET", "{host}"}}},
Hosts: []config.StaticHost{{Name: "router", Address: "192.0.2.1", SSH: config.SSHOptions{PreConnect: "STATICSECRET"}}},
TUI: config.TUIConfig{HistoryLimit: 25},
}
data, err := json.Marshal(portableConfig(c))
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"URLSECRET", "TOKEN", "HOOKSECRET", "OPTIONSECRET", "POSTSECRET", "COMMANDSECRET", "STATICSECRET"} {
if bytes.Contains(data, []byte(secret)) {
t.Fatalf("export leaked %s", secret)
}
}
parsed, err := decodePortable(data)
if err != nil {
t.Fatal(err)
}
if parsed.TUI.HistoryLimit != 25 || len(parsed.NetBoxes) != 1 || parsed.NetBoxes[0].URL != "https://netbox.example" {
t.Fatalf("%+v", parsed)
}
hostile := []byte("netbox:\n url: https://netbox.example\n token: bad\nssh:\n pre_connect: touch /tmp/never\ncommands:\n check:\n args: [sh, -c, evil]\n")
parsed, err = decodePortable(hostile)
if err != nil || parsed.NetBox.Token != "" || parsed.SSH.PreConnect != "" || len(parsed.Commands) != 0 {
t.Fatalf("%+v %v", parsed, err)
}
}
func TestBatchRetryFailedOnly(t *testing.T) {
bin := filepath.Join(t.TempDir(), "netssh")
build := exec.Command("go", "build", "-o", bin, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build: %s %v", out, err)
}
old := batchExecutable
batchExecutable = func() (string, error) { return bin, nil }
t.Cleanup(func() { batchExecutable = old })
dir := t.TempDir()
script := filepath.Join(dir, "check.sh")
ready := filepath.Join(dir, "ready")
if err := os.WriteFile(script, []byte(fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = fail ] && [ ! -f %q ]; then exit 3; fi\nprintf 'ran %%s\\n' \"$1\"\n", ready)), 0700); err != nil {
t.Fatal(err)
}
writeOperationsConfig(t, fmt.Sprintf("commands:\n check:\n args: [%q, \"{host}\"]\n", script))
run := func(args ...string) (string, error) {
cmd := batchCmd()
cmd.SetArgs(args)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
err := cmd.Execute()
return out.String(), err
}
out, err := run("--parallel", "2", "check", "router", "fail", "okay")
if err == nil || !strings.Contains(out, "2 succeeded, 1 failed") {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(batchPath())
var retry batchRetry
if err := json.Unmarshal(data, &retry); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(retry.Hosts, []string{"fail"}) {
t.Fatalf("%+v", retry)
}
if err := os.WriteFile(ready, nil, 0600); err != nil {
t.Fatal(err)
}
out, err = run("--retry-failed")
if err != nil || !strings.Contains(out, "1 succeeded, 0 failed") || strings.Contains(out, "ran router") {
t.Fatalf("%s %v", out, err)
}
}
func TestImportPreservesOnlyMatchingCredentials(t *testing.T) {
writeOperationsConfig(t, "")
original := []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: LOCALPROD\n - name: lab\n url: https://lab.example\n token: LOCALLAB\ncommands:\n local:\n args: [echo, \"{host}\"]\n")
if err := os.WriteFile(config.Path(), original, 0600); err != nil {
t.Fatal(err)
}
shared := filepath.Join(t.TempDir(), "shared.yaml")
if err := os.WriteFile(shared, []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: UNTRUSTED\n - name: lab\n url: https://other.example\ntui:\n history_limit: 25\nssh:\n pre_connect: evil\n"), 0600); err != nil {
t.Fatal(err)
}
if out, err := runNetssh(t, "config", "import", shared, "--dry-run"); err != nil {
t.Fatalf("%s %v", out, err)
}
after, _ := os.ReadFile(config.Path())
if !bytes.Equal(original, after) {
t.Fatal("preview changed config")
}
if out, err := runNetssh(t, "config", "import", shared, "--yes"); err != nil {
t.Fatalf("%s %v", out, err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
if cfg.NetBoxes[0].Token != "LOCALPROD" || cfg.NetBoxes[1].Token != "" || cfg.SSH.PreConnect != "" || len(cfg.Commands) != 1 || cfg.TUI.HistoryLimit != 25 {
t.Fatalf("incorrect imported settings: names=%d tui=%d", len(cfg.NetBoxes), cfg.TUI.HistoryLimit)
}
backup, _ := os.ReadFile(config.Path() + ".before-import")
if !bytes.Equal(backup, original) {
t.Fatal("backup differs")
}
}
+164
View File
@@ -0,0 +1,164 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Portable config deliberately omits arbitrary command/hook/SSH option strings:
// secrets may be embedded there, and cannot reliably be detected by key name.
func portableConfig(c config.Config) map[string]any {
cleanURL := func(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
u.User = nil
u.RawQuery = ""
u.Fragment = ""
return u.String()
}
sources := []map[string]any{}
for _, s := range c.NetBoxes {
sources = append(sources, map[string]any{"name": s.Name, "url": cleanURL(s.URL), "disable_prefix": s.DisablePrefix})
}
hosts := []map[string]any{}
for _, h := range c.Hosts {
hosts = append(hosts, map[string]any{"name": h.Name, "address": h.Address, "user": h.User, "port": h.Port, "tags": h.Tags})
}
rewrites := []map[string]string{}
for _, r := range c.Shortcuts.Rewrites {
rewrites = append(rewrites, map[string]string{"pattern": r.Pattern, "replace": r.Replace})
}
out := map[string]any{
"hosts": hosts, "groups": c.Groups,
"ssh": map[string]any{"default_user": c.SSH.DefaultUser, "default_port": c.SSH.DefaultPort},
"resolver": map[string]any{"strategies": c.Resolver.Strategies, "management_subnets": c.Resolver.ManagementSubnets, "interface_name": c.Resolver.InterfaceName, "hostname_domain": c.Resolver.HostnameDomain},
"shortcuts": map[string]any{"domains": c.Shortcuts.Domains, "rewrites": rewrites, "strip_hyphens": c.Shortcuts.StripHyphens, "show": c.Shortcuts.Show},
"completion": map[string]any{"max_results": c.Completion.MaxResults},
"tui": map[string]any{"history_limit": c.TUI.HistoryLimit},
}
if len(sources) > 0 {
out["netboxes"] = sources
} else if c.NetBox.URL != "" {
out["netbox"] = map[string]string{"url": cleanURL(c.NetBox.URL)}
}
return out
}
func decodePortable(data []byte) (config.Config, error) {
v := viper.New()
v.SetConfigType("yaml")
v.SetDefault("tui.history_limit", 10)
var c config.Config
if err := v.ReadConfig(bytes.NewReader(data)); err != nil {
return c, err
}
if err := v.Unmarshal(&c); err != nil {
return c, err
}
// Strip executable settings and credentials even from externally edited files.
safe, _ := json.Marshal(portableConfig(c))
v = viper.New()
v.SetConfigType("json")
if err := v.ReadConfig(bytes.NewReader(safe)); err != nil {
return c, err
}
c = config.Config{}
err := v.Unmarshal(&c)
return c, err
}
func configCmd() *cobra.Command {
cmd := &cobra.Command{Use: "config", Short: "Share configuration without credentials or executable settings"}
export := &cobra.Command{Use: "export [FILE]", Short: "Export a secret-free JSON configuration (also valid YAML)", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
data, err := json.MarshalIndent(portableConfig(*cfg), "", " ")
if err != nil {
return err
}
if len(args) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), string(data))
return nil
}
return storage.WriteFile(args[0], append(data, '\n'), 0600)
}}
var yes, dry bool
imp := &cobra.Command{Use: "import FILE", Short: "Import shared host settings; preserve matching local credentials and commands", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
data, err := os.ReadFile(args[0])
if err != nil {
return err
}
incoming, err := decodePortable(data)
if err != nil {
return err
}
current, err := config.Load()
if err != nil {
return err
}
same := func(a, b string) bool { return strings.TrimRight(a, "/") == strings.TrimRight(b, "/") }
for i := range incoming.NetBoxes {
for _, old := range current.NetBoxes {
s := &incoming.NetBoxes[i]
if strings.EqualFold(s.Name, old.Name) && same(s.URL, old.URL) {
s.Token = old.Token
s.TokenVersion = old.TokenVersion
s.SSH = old.SSH
}
}
}
if incoming.NetBox.URL != "" && same(incoming.NetBox.URL, current.NetBox.URL) {
incoming.NetBox.Token = current.NetBox.Token
incoming.NetBox.TokenVersion = current.NetBox.TokenVersion
incoming.NetBox.SSH = current.NetBox.SSH
}
incoming.Commands = current.Commands
incoming.Activity = current.Activity
incoming.Cache = current.Cache
incoming.Multi = current.Multi
incoming.Shell = current.Shell
incoming.SSH.SSHOptions = current.SSH.SSHOptions
incoming.SSH.Rules = current.SSH.Rules
for i := range incoming.Hosts {
for _, old := range current.Hosts {
if incoming.Hosts[i].Name == old.Name && incoming.Hosts[i].Address == old.Address {
incoming.Hosts[i].SSH = old.SSH
}
}
}
for _, validate := range []func() error{incoming.ValidateNetBoxes, incoming.ValidateHosts, incoming.ValidateSSH, incoming.ValidateCommands, incoming.ValidateOperations, incoming.Shortcuts.Validate, incoming.ValidateMulti} {
if err := validate(); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "Import: %d named instances, %d static hosts. Local commands and matching credentials are retained.\n", len(incoming.NetBoxes), len(incoming.Hosts))
if dry {
return nil
}
if err := confirmAction("Replace shared configuration settings", yes); err != nil {
return err
}
if existing, err := os.ReadFile(config.Path()); err == nil {
if err := storage.WriteFile(config.Path()+".before-import", existing, 0600); err != nil {
return err
}
}
return setup.Save(incoming)
}}
imp.Flags().BoolVar(&yes, "yes", false, "Approve replacing shared configuration settings")
imp.Flags().BoolVar(&dry, "dry-run", false, "Validate and preview without writing")
cmd.AddCommand(export, imp)
return cmd
}
+54
View File
@@ -0,0 +1,54 @@
package main
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// preConnectRunner runs the hook; tests replace it to avoid spawning a shell.
var preConnectRunner = runPreConnectCommand
// preConnectEnv describes the host to the hook through environment variables.
func preConnectEnv(host resolvedHost, clientName string) []string {
instance, name := netbox.SplitTarget(host.Name)
return []string{
"NETSSH_HOST=" + name,
"NETSSH_TARGET=" + host.Name,
"NETSSH_INSTANCE=" + instance,
"NETSSH_IP=" + host.IP,
"NETSSH_KIND=" + host.Kind,
"NETSSH_TAGS=" + strings.Join(host.Tags, ","),
"NETSSH_CLIENT=" + clientName,
}
}
// runPreConnect runs the configured pre_connect hook for host. Its output goes
// to stderr so it never mixes with the output of a remote command or scp.
// A failing hook returns an error and the connection must not be opened.
func runPreConnect(command string, host resolvedHost, clientName string, dryRun bool) error {
if command == "" {
return nil
}
if dryRun {
fmt.Fprintf(os.Stderr, "# pre_connect (skipped in --dry-run): %s\n", command)
return nil
}
if err := preConnectRunner(command, preConnectEnv(host, clientName), os.Stdin, os.Stderr); err != nil {
return fmt.Errorf("pre_connect hook for %s failed: %w", host.Name, err)
}
return nil
}
func runPreConnectCommand(command string, env []string, stdin io.Reader, out io.Writer) error {
cmd := exec.Command("sh", "-c", command)
cmd.Env = append(os.Environ(), env...)
cmd.Stdin = stdin
cmd.Stdout = out
cmd.Stderr = out
return cmd.Run()
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"bytes"
"errors"
"io"
"os"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
func TestRunPreConnectPassesHostAndStopsOnFailure(t *testing.T) {
host := resolvedHost{Name: "prod/web01", Kind: "vm", IP: "10.0.0.5", Tags: []string{"dmz", "web"}}
var gotCommand string
var gotEnv []string
fail := false
preConnectRunner = func(command string, env []string, _ io.Reader, _ io.Writer) error {
gotCommand, gotEnv = command, env
if fail {
return errors.New("exit status 1")
}
return nil
}
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
if err := runPreConnect("vpn-check", host, "sftp", false); err != nil {
t.Fatal(err)
}
want := []string{"NETSSH_HOST=web01", "NETSSH_TARGET=prod/web01", "NETSSH_INSTANCE=prod", "NETSSH_IP=10.0.0.5", "NETSSH_KIND=vm", "NETSSH_TAGS=dmz,web", "NETSSH_CLIENT=sftp"}
if gotCommand != "vpn-check" || !reflect.DeepEqual(gotEnv, want) {
t.Fatalf("got %q %v", gotCommand, gotEnv)
}
fail = true
if err := runPreConnect("vpn-check", host, "ssh", false); err == nil || !strings.Contains(err.Error(), "prod/web01") {
t.Fatalf("failure not reported: %v", err)
}
gotCommand = ""
if err := runPreConnect("vpn-check", host, "ssh", true); err != nil || gotCommand != "" {
t.Fatalf("dry-run ran the hook: %v %q", err, gotCommand)
}
if err := runPreConnect("", host, "ssh", false); err != nil || gotCommand != "" {
t.Fatalf("empty hook ran: %v %q", err, gotCommand)
}
}
func TestRunPreConnectCommandUsesShell(t *testing.T) {
var out bytes.Buffer
err := runPreConnectCommand(`echo "$NETSSH_HOST via $NETSSH_CLIENT"`, []string{"NETSSH_HOST=web01", "NETSSH_CLIENT=ssh"}, strings.NewReader(""), &out)
if err != nil || out.String() != "web01 via ssh\n" {
t.Fatalf("got %q, %v", out.String(), err)
}
if err := runPreConnectCommand("exit 3", nil, strings.NewReader(""), io.Discard); err == nil {
t.Fatal("non-zero exit not reported")
}
}
// --dry-run only prints the ssh command: it must not run the hook, which may
// have side effects (bringing up a VPN, logging).
func TestConnectHostDryRunSkipsPreConnect(t *testing.T) {
ran := 0
preConnectRunner = func(string, []string, io.Reader, io.Writer) error { ran++; return nil }
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
cfg := &config.Config{SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PreConnect: "hook"}}}
stdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
connectHost(cfg, internalssh.SSH, internalssh.WrapperFlags{DryRun: true}, resolvedHost{Name: "web01", IP: "10.0.0.1"}, []int{0}, []string{"web01"})
w.Close()
os.Stdout = stdout
printed, _ := io.ReadAll(r)
if ran != 0 || !strings.Contains(string(printed), "10.0.0.1") {
t.Fatalf("dry-run: ran=%d printed=%q", ran, printed)
}
}
func TestShortcutAliasesOnlyWhenShortened(t *testing.T) {
cfg := config.Config{Shell: config.ShellConfig{Alias: "j"}, Shortcuts: fsnRewrite}
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "web01.other.de"}, {Name: "db01.hoster.de"}}
got := shortcutAliases(entries, cfg)
want := map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "db01.hoster.de": "db01"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
if got := shortcutAliases(entries, config.Config{}); len(got) != 0 {
t.Fatalf("aliases without shortcuts: %v", got)
}
}
func TestHostCompletionsShowShortcutsForMatchingNames(t *testing.T) {
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "fsn1-db1.hoster.de"}}
if got := hostCompletions(entries, "fsn", fsnRewrite); !reflect.DeepEqual(got, []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de"}) {
t.Fatalf("without show: %v", got)
}
show := fsnRewrite
show.Show = true
want := []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de", "fsnbx1", "fsndb1"}
if got := hostCompletions(entries, "fsn", show); !reflect.DeepEqual(got, want) {
t.Fatalf("with show: got %v, want %v", got, want)
}
// A shortcut equal to an offered name is not repeated.
plain := []cache.Entry{{Name: "web01"}}
if got := hostCompletions(plain, "web", show); !reflect.DeepEqual(got, []string{"web01"}) {
t.Fatalf("duplicate: %v", got)
}
}
+106
View File
@@ -0,0 +1,106 @@
package main
import (
"fmt"
"os"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra"
)
// expandHostCommand substitutes each argument once, without shell evaluation.
func expandHostCommand(command config.HostCommand, host resolvedHost, extra []string) []string {
_, name := netbox.SplitTarget(host.Name)
replace := strings.NewReplacer("{host}", name, "{address}", host.IP, "{target}", host.Name)
argv := make([]string, 0, len(command.Args)+len(extra))
for _, arg := range command.Args {
argv = append(argv, replace.Replace(arg))
}
return append(argv, extra...)
}
func runCmd() *cobra.Command {
var dryRun, yes, status bool
cmd := &cobra.Command{
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
Short: "Run a configured local command for a NetBox or static host",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
command, ok := cfg.Commands[args[0]]
if !ok {
return fmt.Errorf("unknown configured command %q", args[0])
}
host, err := resolveTargetE(cfg, args[1], !dryRun)
if err != nil {
return err
}
if !command.Allowed(commandHost(host)) {
return fmt.Errorf("command %q is not allowed for %s", args[0], host.Name)
}
argv := expandHostCommand(command, host, args[2:])
if dryRun {
if post := config.HookCommand(command.PostRun); post != "" {
fmt.Fprintf(cmd.ErrOrStderr(), "# post_run (skipped in --dry-run): %s\n", post)
}
for i, arg := range argv {
if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ")
}
fmt.Fprintf(cmd.OutOrStdout(), "%q", arg)
}
fmt.Fprintln(cmd.OutOrStdout())
return nil
}
if command.Confirm {
if err := confirmAction("Run "+args[0]+" on "+host.Name, yes); err != nil {
return err
}
}
timeout, _ := time.ParseDuration(command.Timeout)
code := supervise(cfg, host, args[0], argv, command.PostRun, timeout, status || term.IsTerminal(os.Stderr.Fd()), os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr())
if code != 0 {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
return &commandExit{code}
}
return nil
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var names []string
for name := range cfg.Commands {
if strings.HasPrefix(name, prefix) {
names = append(names, name)
}
}
sort.Strings(names)
return names, cobra.ShellCompDirectiveNoFileComp
}
if len(args) == 1 {
return completeHosts(prefix), cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
}
cmd.Flags().BoolVar(&yes, "yes", false, "Approve an action requiring confirmation")
cmd.Flags().BoolVar(&status, "status", false, "Show elapsed runtime")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
return cmd
}
type commandExit struct{ code int }
func (e *commandExit) Error() string { return fmt.Sprintf("command exited with status %d", e.code) }
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestExpandHostCommand(t *testing.T) {
command := config.HostCommand{Args: []string{"mtr", "--target={address}", "{host}", "{target}", "$(literal)"}}
host := resolvedHost{Name: "office/xzi-groß1", IP: "2001:db8::1"}
got := expandHostCommand(command, host, []string{"--report", "two words"})
want := []string{"mtr", "--target=2001:db8::1", "xzi-groß1", "office/xzi-groß1", "$(literal)", "--report", "two words"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("%q, want %q", got, want)
}
}
func TestRunConfiguredHostCommand(t *testing.T) {
prepareTransferTest(t)
f, err := os.OpenFile(config.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(`
commands:
trace:
alias_prefix: m
args: [mtr, "{address}", "{host}", "{target}"]
literal:
args: [printf, "%s|%s|%s", "{address}", "{host}", "$(touch should-not-exist)"]
`)
if closeErr := f.Close(); err != nil || closeErr != nil {
t.Fatalf("write config: %v %v", err, closeErr)
}
for _, tc := range []struct {
args []string
want string
}{
{[]string{"run", "--dry-run", "trace", "fsnbx1", "--", "--report"}, `"mtr" "10.0.0.9" "fsn1-bx1.hoster.de" "fsn1-bx1.hoster.de" "--report"`},
{[]string{"run", "--dry-run", "trace", "--", "fsnbx1", "--help"}, `"mtr" "10.0.0.9" "fsn1-bx1.hoster.de" "fsn1-bx1.hoster.de" "--help"`},
{[]string{"run", "literal", "fsnbx1"}, "10.0.0.9|fsn1-bx1.hoster.de|$(touch should-not-exist)"},
} {
out, err := runNetssh(t, tc.args...)
if err != nil || out != tc.want {
t.Fatalf("%v: %q (%v), want %q", tc.args, out, err, tc.want)
}
}
out, err := runNetssh(t, "run", "missing", "fsnbx1")
if err == nil || !strings.Contains(out, "unknown configured command") {
t.Fatalf("%q %v", out, err)
}
}
func TestRunCommandAcceptsResolvedHostname(t *testing.T) {
prepareTransferTest(t)
data := `netbox:
url: http://127.0.0.1:1
token: t
hosts:
- name: router
address: router.example.com
commands:
trace:
args: [mtr, "{address}"]
`
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte(data), 0600); err != nil {
t.Fatal(err)
}
out, err := runNetssh(t, "run", "--dry-run", "trace", "router")
if err != nil || out != `"mtr" "router.example.com"` {
t.Fatalf("%q %v", out, err)
}
}
func TestRunOwnScripts(t *testing.T) {
for _, mode := range []string{"executable", "bash", "python3"} {
t.Run(mode, func(t *testing.T) {
if mode != "executable" {
if _, err := exec.LookPath(mode); err != nil {
t.Skip("interpreter not installed")
}
}
prepareTransferTest(t)
script := filepath.Join(t.TempDir(), "my host check")
body := "#!/bin/sh\nprintf '<%s>\\n' \"$@\"\nexit 7\n"
permissions := os.FileMode(0700)
argv := []string{script}
if mode != "executable" {
permissions = 0600
argv = []string{mode, script}
}
if mode == "python3" {
body = "import sys\nfor arg in sys.argv[1:]:\n print('<' + arg + '>')\nsys.exit(7)\n"
}
if err := os.WriteFile(script, []byte(body), permissions); err != nil {
t.Fatal(err)
}
argv = append(argv, "{address}", "{host}", "{target}")
var yaml strings.Builder
yaml.WriteString("\ncommands:\n check:\n alias_prefix: c\n args:\n")
for _, arg := range argv {
fmt.Fprintf(&yaml, " - %q\n", arg)
}
f, err := os.OpenFile(config.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(yaml.String())
if closeErr := f.Close(); err != nil || closeErr != nil {
t.Fatalf("config write: %v %v", err, closeErr)
}
out, err := runNetssh(t, "run", "check", "fsnbx1", "--", "--report", "two words", "$(literal)")
want := "<10.0.0.9>\n<fsn1-bx1.hoster.de>\n<fsn1-bx1.hoster.de>\n<--report>\n<two words>\n<$(literal)>"
if out != want {
t.Fatalf("script args: %q, want %q", out, want)
}
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 7 {
t.Fatalf("script exit status lost: %v", err)
}
})
}
}
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"github.com/charmbracelet/x/term"
)
func commandHost(h resolvedHost) config.SSHHost {
instance, name := netbox.SplitTarget(h.Name)
return config.SSHHost{Instance: instance, Name: name, Kind: h.Kind, Tags: h.Tags}
}
func confirmAction(message string, yes bool) error {
if yes {
return nil
}
if !term.IsTerminal(os.Stdin.Fd()) {
return fmt.Errorf("%s requires confirmation; use --yes for unattended execution", message)
}
fmt.Fprintf(os.Stderr, "%s? [y/N] ", message)
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return err
}
if strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes") {
return nil
}
return fmt.Errorf("cancelled")
}
func supervise(cfg *config.Config, h resolvedHost, name string, argv []string, post string, timeout time.Duration, status bool, stdin io.Reader, stdout, stderr io.Writer) int {
start := time.Now()
env := append(preConnectEnv(h, name), "NETSSH_COMMAND="+name)
result := runner.Run(context.Background(), argv, runner.Options{Stdin: stdin, Stdout: stdout, Stderr: stderr, Env: env, Timeout: timeout, Status: status, Label: name + " " + h.Name})
code := result.Code
if result.Started && config.HookCommand(post) != "" {
hook := runner.Run(context.Background(), []string{"sh", "-c", post}, runner.Options{Stdin: nil, Stdout: stderr, Stderr: stderr, Env: append(env, "NETSSH_EXIT_CODE="+strconv.Itoa(code)), Timeout: 30 * time.Second})
if hook.Code != 0 {
fmt.Fprintf(stderr, "post hook failed (exit %d)\n", hook.Code)
if code == 0 {
code = hook.Code
}
}
}
if err := activity.Append(cfg.Activity, activity.Record{Time: start, Host: h.Name, Command: name, Code: code, Duration: time.Since(start)}); err != nil {
fmt.Fprintf(stderr, "activity: %v\n", err)
}
return code
}
+14
View File
@@ -0,0 +1,14 @@
package main
import (
"os"
"testing"
)
// Integration helpers run this test binary as netssh. An automatic refresh
// would otherwise launch the test binary again with "cache refresh", rerunning
// the entire suite. Explicit cache-refresh tests still exercise the real command.
func TestMain(m *testing.M) {
_ = os.Setenv("NETSSH_NO_REFRESH", "1")
os.Exit(m.Run())
}
+4 -3
View File
@@ -71,6 +71,7 @@ func buildUninstallPlan(cfg *config.Config, keepConfig bool) uninstallPlan {
addPath(path)
addPath(path + ".lock")
addPath(filepath.Join(filepath.Dir(path), "last_refresh"))
addPath(filepath.Join(filepath.Dir(path), "refresh_attempt"))
if strings.HasPrefix(filepath.Base(filepath.Dir(path)), "instances-") {
addPath(filepath.Dir(path))
}
@@ -203,10 +204,10 @@ func uninstallCmd() *cobra.Command {
- netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles
- shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias)
- the cache directory with hosts, aliases, and per-instance caches
- the config file (a private backup is kept) and local server notes
- the config file (a private backup is kept) and local notes, favorites, action history and batch retry state
- the netssh binary
Use --keep-config to keep the config file and notes for a reinstall.`,
Use --keep-config to keep the config file and local state for a reinstall.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
@@ -243,7 +244,7 @@ Use --keep-config to keep the config file and notes for a reinstall.`,
return err
},
}
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local notes")
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local state")
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed")
return cmd
+1 -1
View File
@@ -6,7 +6,7 @@ require (
charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.1
charm.land/huh/v2 v2.0.3
charm.land/lipgloss/v2 v2.1.0
charm.land/lipgloss/v2 v2.1.1
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
golang.org/x/sys v0.50.0
+2 -2
View File
@@ -4,8 +4,8 @@ charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU=
charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI=
charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc=
charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
+94
View File
@@ -0,0 +1,94 @@
// Package activity stores local preferences and optional execution metadata.
// No command arguments, environment variables, tokens or command output are logged.
package activity
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"golang.org/x/sys/unix"
)
type Record struct {
Time time.Time `json:"time"`
Host string `json:"host"`
Command string `json:"command"`
Code int `json:"exit_code"`
Duration time.Duration `json:"duration_ns"`
}
type State struct {
Favorites map[string]bool `json:"favorites,omitempty"`
Pinned map[string]bool `json:"pinned,omitempty"`
Records []Record `json:"records,omitempty"`
}
func Path() string { return filepath.Join(filepath.Dir(config.Path()), "netssh", "activity.json") }
func Read() (State, error) {
var s State
data, err := os.ReadFile(Path())
if os.IsNotExist(err) {
err = nil
} else if err == nil {
err = json.Unmarshal(data, &s)
}
if s.Favorites == nil {
s.Favorites = map[string]bool{}
}
if s.Pinned == nil {
s.Pinned = map[string]bool{}
}
return s, err
}
func Update(change func(*State)) error {
p := Path()
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
return err
}
f, err := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
defer f.Close()
if err = unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
s, err := Read()
if err != nil {
return fmt.Errorf("local state: %w", err)
}
change(&s)
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return storage.WriteFile(p, data, 0600)
}
func Prune(s *State, c config.ActivityConfig) {
if c.RetentionDays > 0 {
cutoff := time.Now().Add(-time.Duration(c.RetentionDays) * 24 * time.Hour)
keep := s.Records[:0]
for _, r := range s.Records {
if !r.Time.Before(cutoff) {
keep = append(keep, r)
}
}
s.Records = keep
}
sort.SliceStable(s.Records, func(i, j int) bool { return s.Records[i].Time.Before(s.Records[j].Time) })
if c.MaxEntries > 0 && len(s.Records) > c.MaxEntries {
s.Records = s.Records[len(s.Records)-c.MaxEntries:]
}
}
func Append(c config.ActivityConfig, r Record) error {
if !c.Enabled {
return nil
}
return Update(func(s *State) { s.Records = append(s.Records, r); Prune(s, c) })
}
+59
View File
@@ -0,0 +1,59 @@
package activity
import (
"fmt"
"os"
"sync"
"testing"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestConcurrentActivityAndRetention(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.ActivityConfig{Enabled: true, RetentionDays: 1, MaxEntries: 10}
if err := Update(func(s *State) {
s.Favorites["prod/web"] = true
s.Pinned["prod/web"] = true
s.Records = []Record{{Time: time.Now().Add(-48 * time.Hour), Host: "old"}}
}); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := Append(cfg, Record{Time: time.Now(), Host: fmt.Sprint(i), Command: "test"}); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
s, err := Read()
if err != nil {
t.Fatal(err)
}
if len(s.Records) != 10 || !s.Favorites["prod/web"] || !s.Pinned["prod/web"] {
t.Fatalf("%+v", s)
}
for _, r := range s.Records {
if r.Host == "old" {
t.Fatal("expired record retained")
}
}
info, _ := os.Stat(Path())
if info.Mode().Perm() != 0600 {
t.Fatal(info.Mode())
}
}
func TestDisabledHistoryDoesNotWrite(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := Append(config.ActivityConfig{}, Record{}); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(Path()); !os.IsNotExist(err) {
t.Fatal("disabled history wrote data")
}
}
+21
View File
@@ -17,6 +17,7 @@ import (
)
type Entry struct {
Resolver string `json:"resolver,omitempty"`
Name string `json:"name"`
IP string `json:"ip"`
Kind string `json:"kind"`
@@ -83,6 +84,26 @@ func (c *Cache) NeedsRefresh(d time.Duration) bool {
return time.Since(t) >= d
}
// ClaimRefresh reports whether a background refresh should start now: the last
// full refresh is older than d and no attempt was claimed within retry. It
// records the attempt, so parallel shells and repeated commands start one
// refresh per retry interval instead of one each.
func (c *Cache) ClaimRefresh(d, retry time.Duration) bool {
if !c.NeedsRefresh(d) {
return false
}
attempt := filepath.Join(filepath.Dir(c.refreshStamp), "refresh_attempt")
if info, err := os.Stat(attempt); err == nil && time.Since(info.ModTime()) < retry {
return false
}
if err := os.MkdirAll(filepath.Dir(attempt), 0o755); err != nil {
return true // cannot record the attempt; refreshing is still right
}
// Best effort: two processes racing here may both refresh once.
_ = os.WriteFile(attempt, nil, 0o600)
return true
}
// SetRefreshed records the current time as the last successful full refresh.
func (c *Cache) SetRefreshed() error {
if c.refreshStamp == "" {
+20
View File
@@ -557,3 +557,23 @@ func TestStaticHosts(t *testing.T) {
t.Fatalf("removed static host still on disk:\n%s", data)
}
}
func TestClaimRefreshThrottlesAttempts(t *testing.T) {
c := New(filepath.Join(t.TempDir(), "netssh", "hosts.json"), 60)
if !c.ClaimRefresh(24*time.Hour, time.Minute) {
t.Fatal("a never refreshed cache must claim a refresh")
}
// NetBox is down: the stamp stays stale, but the attempt is remembered.
if c.ClaimRefresh(24*time.Hour, time.Minute) {
t.Error("a second refresh within the retry interval must not start")
}
if !c.ClaimRefresh(24*time.Hour, 0) {
t.Error("after the retry interval a refresh must start again")
}
if err := c.SetRefreshed(); err != nil {
t.Fatal(err)
}
if c.ClaimRefresh(24*time.Hour, 0) {
t.Error("a freshly refreshed cache must not claim a refresh")
}
}
+73
View File
@@ -0,0 +1,73 @@
package config
import (
"fmt"
"regexp"
"strings"
"time"
)
// HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct {
PostRun string `mapstructure:"post_run"`
Match SSHMatch `mapstructure:"match"`
Confirm bool `mapstructure:"confirm"`
Timeout string `mapstructure:"timeout"`
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
Args []string `mapstructure:"args" yaml:"args"`
}
func (c *Config) ValidateCommands() error {
prefixes := make(map[string]bool)
for name, command := range c.Commands {
if strings.ContainsRune(command.PostRun, 0) {
return fmt.Errorf("commands.%s.post_run contains NUL", name)
}
if command.Match != (SSHMatch{}) {
if err := command.Match.Validate("commands." + name); err != nil {
return err
}
}
if command.Timeout != "" {
d, err := time.ParseDuration(command.Timeout)
if err != nil || d <= 0 {
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
}
}
if name == "" || ValidateCommandAlias(name) != nil {
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
}
if command.AliasPrefix != "" {
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(command.AliasPrefix) {
return fmt.Errorf("commands.%s.alias_prefix must be a shell identifier", name)
}
if prefixes[command.AliasPrefix] {
return fmt.Errorf("commands.%s: duplicate alias_prefix %q", name, command.AliasPrefix)
}
prefixes[command.AliasPrefix] = true
}
if len(command.Args) == 0 || strings.TrimSpace(command.Args[0]) == "" {
return fmt.Errorf("commands.%s.args requires an executable", name)
}
target := false
for i, arg := range command.Args {
if strings.ContainsRune(arg, 0) {
return fmt.Errorf("commands.%s.args cannot contain NUL", name)
}
if i == 0 && strings.ContainsAny(arg, "{}") {
return fmt.Errorf("commands.%s: executable cannot contain placeholders", name)
}
if strings.Contains(arg, "{host}") || strings.Contains(arg, "{address}") || strings.Contains(arg, "{target}") {
target = true
}
rest := strings.NewReplacer("{host}", "", "{address}", "", "{target}", "").Replace(arg)
if strings.ContainsAny(rest, "{}") {
return fmt.Errorf("commands.%s: supported placeholders are {host}, {address}, {target}", name)
}
}
if !target {
return fmt.Errorf("commands.%s.args requires {host}, {address}, or {target}", name)
}
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package config
import "testing"
func TestValidateCommands(t *testing.T) {
for _, tc := range []struct {
name string
command HostCommand
valid bool
}{
{"mtr", HostCommand{AliasPrefix: "m", Args: []string{"mtr", "{address}"}}, true},
{"ping", HostCommand{Args: []string{"ping", "-c", "3", "{host}"}}, true},
{"inspect", HostCommand{Args: []string{"echo", "{target}"}}, true},
{"", HostCommand{Args: []string{"echo", "{host}"}}, false},
{"bad name", HostCommand{Args: []string{"echo", "{host}"}}, false},
{"netssh", HostCommand{Args: []string{"echo", "{host}"}}, false},
{"bad", HostCommand{AliasPrefix: "m;", Args: []string{"mtr", "{address}"}}, false},
{"bad", HostCommand{}, false},
{"bad", HostCommand{Args: []string{"", "{host}"}}, false},
{"bad", HostCommand{Args: []string{"{host}", "{address}"}}, false},
{"bad", HostCommand{Args: []string{"mtr", "{adress}"}}, false},
{"bad", HostCommand{Args: []string{"mtr"}}, false},
{"bad", HostCommand{Args: []string{"mtr", "{host}\x00"}}, false},
} {
cfg := Config{Commands: map[string]HostCommand{tc.name: tc.command}}
if err := cfg.ValidateCommands(); (err == nil) != tc.valid {
t.Errorf("%+v: %v", tc, err)
}
}
cfg := Config{Commands: map[string]HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
"ping": {AliasPrefix: "m", Args: []string{"ping", "{address}"}},
}}
if cfg.ValidateCommands() == nil {
t.Fatal("duplicate prefixes accepted")
}
}
+34 -17
View File
@@ -11,15 +11,18 @@ import (
)
type Config struct {
Shell ShellConfig `mapstructure:"shell"`
NetBox NetBoxConfig `mapstructure:"netbox"`
NetBoxes []NetBoxConfig `mapstructure:"netboxes"`
Resolver ResolverConfig `mapstructure:"resolver"`
Cache CacheConfig `mapstructure:"cache"`
SSH SSHConfig `mapstructure:"ssh"`
Shortcuts ShortcutsConfig `mapstructure:"shortcuts"`
Completion CompletionConfig `mapstructure:"completion"`
Hosts []StaticHost `mapstructure:"hosts"`
TUI TUIConfig `mapstructure:"tui"`
Activity ActivityConfig `mapstructure:"activity"`
Commands map[string]HostCommand `mapstructure:"commands"`
Shell ShellConfig `mapstructure:"shell"`
NetBox NetBoxConfig `mapstructure:"netbox"`
NetBoxes []NetBoxConfig `mapstructure:"netboxes"`
Resolver ResolverConfig `mapstructure:"resolver"`
Cache CacheConfig `mapstructure:"cache"`
SSH SSHConfig `mapstructure:"ssh"`
Shortcuts ShortcutsConfig `mapstructure:"shortcuts"`
Completion CompletionConfig `mapstructure:"completion"`
Hosts []StaticHost `mapstructure:"hosts"`
// Groups name lists of hosts and selectors for netssh multi (@name).
Groups map[string][]string `mapstructure:"groups"`
Multi MultiConfig `mapstructure:"multi"`
@@ -30,11 +33,12 @@ type ShellConfig struct {
}
type NetBoxConfig struct {
Name string `mapstructure:"name"`
URL string `mapstructure:"url"`
Token string `mapstructure:"token"`
TokenVersion int `mapstructure:"token_version"`
SSH SSHOptions `mapstructure:"ssh"`
DisablePrefix bool `mapstructure:"disable_prefix"`
Name string `mapstructure:"name"`
URL string `mapstructure:"url"`
Token string `mapstructure:"token"`
TokenVersion int `mapstructure:"token_version"`
SSH SSHOptions `mapstructure:"ssh"`
}
type ResolverConfig struct {
@@ -66,6 +70,9 @@ type ShortcutsConfig struct {
Domains []string `mapstructure:"domains"`
StripHyphens bool `mapstructure:"strip_hyphens"`
Rewrites []ShortcutRewrite `mapstructure:"rewrites"`
// Show displays each host's shortcut alias in the TUI and in host lists, and
// offers shortcuts in Tab completion even when the full name matches.
Show bool `mapstructure:"show"`
}
// ShortcutRewrite replaces every match of Pattern (Go regexp syntax) with
@@ -108,19 +115,23 @@ func Load() (*Config, error) {
v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"})
v.SetDefault("resolver.management_subnets", []string{})
v.SetDefault("cache.ttl", 3600)
v.SetDefault("tui.history_limit", 10)
v.SetDefault("activity.retention_days", 30)
v.SetDefault("activity.max_entries", 1000)
configDir, err := os.UserConfigDir()
if err == nil {
v.SetConfigName("netssh")
v.SetConfigType("yaml")
v.AddConfigPath(filepath.Join(configDir))
v.AddConfigPath(".")
// Only the user's own directory: a netssh.yaml in the working directory
// (e.g. of a cloned repository) could inject ssh options and a NetBox URL.
v.AddConfigPath(configDir)
}
v.SetEnvPrefix("NETSSH")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shell.alias", "ssh.proxy_jump", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
if err := v.BindEnv(key); err != nil {
return nil, err
}
@@ -166,6 +177,12 @@ func Load() (*Config, error) {
if err := cfg.ValidateHosts(); err != nil {
return nil, err
}
if err := cfg.ValidateOperations(); err != nil {
return nil, err
}
if err := cfg.ValidateCommands(); err != nil {
return nil, err
}
if err := cfg.ValidateMulti(); err != nil {
return nil, err
}
+24
View File
@@ -196,3 +196,27 @@ func TestLoad_InvalidShortcutRewrite(t *testing.T) {
}
}
}
// A netssh.yaml in the working directory (e.g. of a cloned repository) must
// not be loaded: it could inject ssh options such as ProxyCommand.
func TestLoad_IgnoresConfigInWorkingDirectory(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("NETSSH_NETBOX_URL", "")
t.Chdir(writeConfig(t, "hosts:\n - name: evil\n address: 10.0.0.1\nssh:\n options:\n ProxyCommand: touch /tmp/pwned\n"))
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if len(cfg.Hosts) != 0 || len(cfg.SSH.Options) != 0 {
t.Errorf("config from the working directory was loaded: %+v", cfg)
}
}
func TestLoad_RejectsInvalidLegacyNetBoxURL(t *testing.T) {
for _, bad := range []string{"netbox.example.com", "ftp://netbox.example.com", "https://netbox.example.com/?x=1"} {
t.Setenv("XDG_CONFIG_HOME", writeConfig(t, "netbox:\n url: \""+bad+"\"\n token: t\n"))
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "netbox.url") {
t.Errorf("%s: got %v, want a netbox.url error", bad, err)
}
}
}
+24 -2
View File
@@ -17,6 +17,9 @@ func (c *Config) ValidateNetBoxes() error {
if len(c.NetBoxes) > 0 && c.NetBox.URL != "" {
return fmt.Errorf("configure either netbox or netboxes, not both")
}
if c.NetBox.URL != "" && !validNetBoxURL(c.NetBox.URL) {
return fmt.Errorf("netbox.url %q must be an HTTP(S) URL without query or fragment", c.NetBox.URL)
}
seen := make(map[string]bool)
for _, source := range c.NetBoxes {
if !instanceName.MatchString(source.Name) {
@@ -27,8 +30,7 @@ func (c *Config) ValidateNetBoxes() error {
return fmt.Errorf("duplicate NetBox instance name %q", source.Name)
}
seen[name] = true
u, err := url.Parse(source.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" {
if !validNetBoxURL(source.URL) {
return fmt.Errorf("NetBox %q requires an HTTP(S) URL without query or fragment", source.Name)
}
if source.TokenVersion < 0 || source.TokenVersion > 2 {
@@ -38,6 +40,12 @@ func (c *Config) ValidateNetBoxes() error {
return nil
}
// validNetBoxURL accepts base URLs that API paths can be appended to.
func validNetBoxURL(raw string) bool {
u, err := url.Parse(raw)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" && u.RawQuery == "" && u.Fragment == ""
}
func (c *Config) HasNetBox() bool { return c.NetBox.URL != "" || len(c.NetBoxes) > 0 }
// HasHosts reports whether netssh has anything to connect to: NetBox or static hosts.
@@ -57,3 +65,17 @@ func (c *Config) CachePath() string {
sum := sha256.Sum256([]byte(strings.Join(identities, "\x00")))
return filepath.Join(filepath.Dir(c.Cache.Path), fmt.Sprintf("instances-%x", sum[:8]), filepath.Base(c.Cache.Path))
}
// HostLabel omits the configured instance prefix for display only. Callers
// must retain the canonical target for connections and handle label collisions.
func (c *Config) HostLabel(target string) string {
source, host, qualified := strings.Cut(target, "/")
if qualified {
for _, instance := range c.NetBoxes {
if instance.DisablePrefix && strings.EqualFold(instance.Name, source) {
return host
}
}
}
return target
}
+8
View File
@@ -15,6 +15,7 @@ func TestLoadNamedNetBoxes(t *testing.T) {
- name: Office
url: https://office.example/netbox
token: nbt_office
disable_prefix: true
- name: lab
url: https://lab.example
token: legacy-token
@@ -34,7 +35,14 @@ cache:
if cfg.NetBox.URL != "" {
t.Fatal("legacy environment variables added an unnamed instance")
}
if !cfg.NetBoxes[0].DisablePrefix || cfg.NetBoxes[1].DisablePrefix {
t.Fatal("per-instance alias prefix setting was not loaded")
}
first := cfg.CachePath()
cfg.NetBoxes[0].DisablePrefix = false
if cfg.CachePath() != first {
t.Fatal("alias prefix setting discarded cache")
}
if first == cfg.Cache.Path {
t.Fatal("named sources reuse legacy cache")
}
+34
View File
@@ -0,0 +1,34 @@
package config
import (
"fmt"
"strings"
)
type TUIConfig struct {
HistoryLimit int `mapstructure:"history_limit"`
}
type ActivityConfig struct {
Enabled bool `mapstructure:"enabled"`
RetentionDays int `mapstructure:"retention_days"`
MaxEntries int `mapstructure:"max_entries"`
}
func (c *Config) ValidateOperations() error {
if c.TUI.HistoryLimit < 0 {
return fmt.Errorf("tui.history_limit must be >= 0 (0 = all)")
}
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
}
return nil
}
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
func (c HostCommand) Allowed(host SSHHost) bool { return c.Match.Matches(host) }
func HookCommand(s string) string {
s = strings.TrimSpace(s)
if strings.EqualFold(s, "none") {
return ""
}
return s
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"os"
"path/filepath"
"testing"
)
func TestOperationsDefaultsEnvironmentAndValidation(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte("hosts:\n - name: router\n address: 192.0.2.1\n"), 0600); err != nil {
t.Fatal(err)
}
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.TUI.HistoryLimit != 10 || cfg.Activity.Enabled || cfg.Activity.RetentionDays != 30 || cfg.Activity.MaxEntries != 1000 {
t.Fatalf("%+v %+v", cfg.TUI, cfg.Activity)
}
t.Setenv("NETSSH_TUI_HISTORY_LIMIT", "25")
t.Setenv("NETSSH_SSH_POST_DISCONNECT", "echo done")
cfg, err = Load()
if err != nil || cfg.TUI.HistoryLimit != 25 || cfg.SSH.PostDisconnect != "echo done" {
t.Fatalf("%+v %v", cfg, err)
}
cfg.TUI.HistoryLimit = -1
if cfg.ValidateOperations() == nil {
t.Fatal("negative history accepted")
}
for _, timeout := range []string{"-1s", "0s", "invalid"} {
cfg.Commands = map[string]HostCommand{"check": {Args: []string{"echo", "{host}"}, Timeout: timeout}}
if cfg.ValidateCommands() == nil {
t.Fatalf("accepted %q", timeout)
}
}
}
func TestPostDisconnectLayering(t *testing.T) {
cfg := Config{
SSH: SSHConfig{SSHOptions: SSHOptions{PostDisconnect: "global"}, Rules: []SSHRule{{Match: SSHMatch{Tag: "lab"}, SSHOptions: SSHOptions{PostDisconnect: "none"}}}},
NetBoxes: []NetBoxConfig{{Name: "prod", SSH: SSHOptions{PostDisconnect: "instance"}}},
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Name: "web"}, "global"},
{SSHHost{Name: "web", Instance: "prod"}, "instance"},
{SSHHost{Name: "web", Instance: "prod", Tags: []string{"lab"}}, ""},
} {
if got := HookCommand(cfg.SSHOptionsFor(tc.host).PostDisconnect); got != tc.want {
t.Fatalf("%q want %q", got, tc.want)
}
}
}
+28
View File
@@ -24,6 +24,22 @@ type SSHOptions struct {
Options map[string]string `mapstructure:"options"`
// Forwards are named port forwards, selected with --forward or netssh tunnel.
Forwards map[string]Forward `mapstructure:"forwards"`
// PreConnect is a shell command run locally before connecting; a non-zero
// exit aborts the connection. "none" disables a hook set by a broader layer.
PreConnect string `mapstructure:"pre_connect"`
PostDisconnect string `mapstructure:"post_disconnect"`
}
// PreConnectNone disables an inherited pre_connect hook.
const PreConnectNone = "none"
// PreConnectCommand returns the hook to run, or "" when none is configured.
func (o SSHOptions) PreConnectCommand() string {
command := strings.TrimSpace(o.PreConnect)
if strings.EqualFold(command, PreConnectNone) {
return ""
}
return command
}
// Forward is one port forward; exactly one of the fields is set.
@@ -155,6 +171,12 @@ func (o SSHOptions) Validate(scope string) error {
return fmt.Errorf("%s.options: invalid option %q", scope, key)
}
}
if strings.ContainsRune(o.PostDisconnect, 0) {
return fmt.Errorf("%s.post_disconnect must not contain NUL bytes", scope)
}
if strings.ContainsRune(o.PreConnect, 0) {
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
}
for name, forward := range o.Forwards {
if !instanceName.MatchString(name) {
return fmt.Errorf("%s.forwards: name %q must contain only letters, digits, underscores, or hyphens", scope, name)
@@ -221,6 +243,12 @@ func (o SSHOptions) merge(override SSHOptions) SSHOptions {
if override.AddressFamily != "" {
out.AddressFamily = override.AddressFamily
}
if strings.TrimSpace(override.PostDisconnect) != "" {
out.PostDisconnect = override.PostDisconnect
}
if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect
}
return out
}
+47
View File
@@ -210,3 +210,50 @@ func TestMultiConfig(t *testing.T) {
}
}
}
func TestPreConnectLayeringAndNone(t *testing.T) {
cfg, err := loadYAML(t, `
netboxes:
- name: prod
url: https://prod.example.com
ssh:
pre_connect: vpn-up prod
- name: lab
url: https://lab.example.com
ssh:
pre_connect: check-vpn
rules:
- match: {tag: dmz}
pre_connect: none
`)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Instance: "lab", Name: "web01"}, "check-vpn"},
{SSHHost{Instance: "prod", Name: "web01"}, "vpn-up prod"},
{SSHHost{Instance: "prod", Name: "gw", Tags: []string{"dmz"}}, ""},
} {
if got := cfg.SSHOptionsFor(tc.host).PreConnectCommand(); got != tc.want {
t.Errorf("%+v: got %q, want %q", tc.host, got, tc.want)
}
}
if err := (SSHOptions{PreConnect: "a\x00b"}).Validate("ssh"); err == nil {
t.Error("NUL byte in pre_connect accepted")
}
}
func TestPreConnectFromEnvironment(t *testing.T) {
t.Setenv("NETSSH_SSH_PRE_CONNECT", "true")
t.Setenv("NETSSH_SHORTCUTS_SHOW", "true")
cfg, err := loadYAML(t, "")
if err != nil {
t.Fatal(err)
}
if cfg.SSH.PreConnect != "true" || !cfg.Shortcuts.Show {
t.Fatalf("env not applied: pre_connect=%q show=%v", cfg.SSH.PreConnect, cfg.Shortcuts.Show)
}
}
+78 -5
View File
@@ -16,8 +16,9 @@ import (
// AliasEntry holds a single shell alias mapping.
type AliasEntry struct {
Name string // short alias name (e.g. "web01")
Host string // canonical NetBox hostname (e.g. "web01.example.com")
Command string // configured host command; empty means the default SSH alias
Name string // short alias name (e.g. "web01")
Host string // canonical NetBox hostname (e.g. "web01.example.com")
}
// AliasesPath returns the path for the bash/zsh aliases file.
@@ -51,7 +52,7 @@ func WriteAliasFiles(entries []AliasEntry) error {
writeFishAliasFile(entries) // best-effort — never blocks the caller on failure
alias := ""
for _, entry := range entries {
if entry.Host == "" {
if entry.Host == "" && entry.Command == "" {
alias = entry.Name
break
}
@@ -94,6 +95,9 @@ func writeFishAliasFile(entries []AliasEntry) {
// Empty Host represents an alias for the netssh command itself.
func (e AliasEntry) Definition(shell string) string {
command := "netssh"
if e.Command != "" {
command += " run " + shellQuote(e.Command, shell) + " --"
}
if e.Host != "" {
host := e.Host
if !regexp.MustCompile(`^[a-zA-Z0-9_.:-]+$`).MatchString(host) {
@@ -124,14 +128,83 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
seen[cfg.Shell.Alias] = true
out = append(out, AliasEntry{Name: cfg.Shell.Alias})
}
for _, e := range entries {
withoutPrefix := make(map[string]bool, len(cfg.NetBoxes))
for _, source := range cfg.NetBoxes {
withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix
}
// Reserve canonical aliases as well as requested bare aliases before
// generating any output, so cache ordering cannot redirect a collision.
canonical := make(map[string]bool, len(entries))
counts := make(map[string]int, len(entries))
candidates := make([]string, len(entries))
for i, e := range entries {
name := shortcuts.AliasName(e.Name, cfg.Shortcuts)
if seen[name] || name == "" || !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`).MatchString(name) {
canonical[name] = true
source, host, qualified := strings.Cut(e.Name, "/")
if qualified && withoutPrefix[strings.ToLower(source)] {
name = shortcuts.AliasName(host, cfg.Shortcuts)
}
candidates[i] = name
counts[name]++
}
validAlias := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
for i, e := range entries {
name := candidates[i]
full := shortcuts.AliasName(e.Name, cfg.Shortcuts)
if name != full && (counts[name] > 1 || canonical[name] || seen[name] || !validAlias.MatchString(name)) {
name = full
}
if seen[name] || name == "" || !validAlias.MatchString(name) {
continue
}
seen[name] = true
out = append(out, AliasEntry{Name: name, Host: e.Name})
}
// Build from the final SSH aliases, preserving per-instance prefix and
// collision handling. Never replace an existing SSH or command alias.
hostAliases := append([]AliasEntry(nil), out...)
hostMetadata := map[string]config.SSHHost{}
for _, e := range entries {
instance, hostname, ok := strings.Cut(e.Name, "/")
if !ok {
hostname = instance
instance = ""
}
hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags}
}
var commands []string
for name := range cfg.Commands {
commands = append(commands, name)
}
sort.Strings(commands)
var candidatesForCommands []AliasEntry
commandCounts := make(map[string]int)
for _, name := range commands {
prefix := cfg.Commands[name].AliasPrefix
if prefix == "" {
continue
}
for _, host := range hostAliases {
if host.Host == "" {
continue
}
if !cfg.Commands[name].Allowed(hostMetadata[host.Host]) {
continue
}
alias := prefix + host.Name
commandCounts[alias]++
candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name})
}
}
for _, c := range candidatesForCommands {
if seen[c.Name] || commandCounts[c.Name] != 1 {
continue
}
seen[c.Name] = true
out = append(out, c)
}
return out
}
+163
View File
@@ -2,6 +2,7 @@ package hook_test
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -253,3 +254,165 @@ func TestAliasesUseRewriteRules(t *testing.T) {
t.Fatalf("entries: %+v", entries)
}
}
func TestAliasesOptionalInstancePrefix(t *testing.T) {
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{
{Name: "OFFICE", DisablePrefix: true},
{Name: "lab"},
},
Shortcuts: config.ShortcutsConfig{
Domains: []string{".example.com"},
Rewrites: []config.ShortcutRewrite{{Pattern: "^web-", Replace: "app"}},
},
}
entries := hook.BuildAliasEntries([]cache.Entry{
{Name: "office/web-01.example.com"},
{Name: "lab/web-01.example.com"},
}, cfg)
got := map[string]string{}
for _, e := range entries {
got[e.Name] = e.Host
// Both output formats must keep the fully qualified destination.
for _, shell := range []string{"bash", "zsh", "fish"} {
if !strings.Contains(e.Definition(shell), e.Host) {
t.Fatalf("%s alias lost its target: %s", shell, e.Definition(shell))
}
}
}
if len(got) != 2 || got["app01"] != "office/web-01.example.com" || got["lab_app01"] != "lab/web-01.example.com" {
t.Fatalf("unexpected aliases: %+v", entries)
}
}
func TestAliasesWithoutPrefixCollisions(t *testing.T) {
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{
{Name: "office", DisablePrefix: true},
{Name: "lab", DisablePrefix: true},
},
Shell: config.ShellConfig{Alias: "j"},
Shortcuts: config.ShortcutsConfig{Domains: []string{".example.com"}},
}
for _, tc := range []struct {
name string
hosts []string
want map[string]string
}{
{"two instances", []string{"office/web.example.com", "lab/web.example.com"},
map[string]string{"j": "", "office_web": "office/web.example.com", "lab_web": "lab/web.example.com"}},
{"static host", []string{"office/web.example.com", "web"},
map[string]string{"j": "", "office_web": "office/web.example.com", "web": "web"}},
{"command aliases", []string{"office/j", "office/netssh"},
map[string]string{"j": "", "office_j": "office/j", "office_netssh": "office/netssh"}},
{"reserved qualified alias", []string{"office/lab_web", "lab/web"},
map[string]string{"j": "", "office_lab_web": "office/lab_web", "web": "lab/web"}},
{"invalid bare alias", []string{"office/123.example.com"},
map[string]string{"j": "", "office_123": "office/123.example.com"}},
{"normalized names", []string{"office/web.example.com", "office/web"},
map[string]string{"j": "", "office_web": "office/web"}},
} {
t.Run(tc.name, func(t *testing.T) {
var input []cache.Entry
for _, host := range tc.hosts {
input = append(input, cache.Entry{Name: host})
}
entries := hook.BuildAliasEntries(input, cfg)
if len(entries) != len(tc.want) {
t.Fatalf("aliases: %+v, want %+v", entries, tc.want)
}
for _, e := range entries {
if host, ok := tc.want[e.Name]; !ok || host != e.Host {
t.Fatalf("unexpected alias: %+v", e)
}
}
})
}
}
func TestCustomCommandAliases(t *testing.T) {
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "office", DisablePrefix: true}},
Shortcuts: config.ShortcutsConfig{Rewrites: []config.ShortcutRewrite{{Pattern: "^xzi-groß", Replace: "xg"}}},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
"ping": {AliasPrefix: "p", Args: []string{"ping", "{address}"}},
"manual": {Args: []string{"echo", "{host}"}},
},
}
entries := hook.BuildAliasEntries([]cache.Entry{{Name: "office/xzi-groß1", IP: "10.0.0.1"}}, cfg)
got := map[string]hook.AliasEntry{}
for _, e := range entries {
got[e.Name] = e
}
if len(entries) != 3 || got["mxg1"].Command != "mtr" || got["pxg1"].Command != "ping" {
t.Fatalf("unexpected aliases: %+v", entries)
}
if got["mxg1"].Host != "office/xzi-groß1" {
t.Fatal("instance lost")
}
for _, shell := range []string{"bash", "zsh", "fish"} {
def := got["mxg1"].Definition(shell)
if !strings.Contains(def, "netssh run") || !strings.Contains(def, "office/xzi-groß1") || strings.Contains(def, "10.0.0.1") {
t.Fatalf("%s alias must resolve at invocation: %s", shell, def)
}
}
}
func TestCustomCommandAliasesPreserveExistingNames(t *testing.T) {
cfg := config.Config{
Shell: config.ShellConfig{Alias: "mfoo"},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
"ping": {AliasPrefix: "mp", Args: []string{"ping", "{address}"}},
},
}
entries := hook.BuildAliasEntries([]cache.Entry{
{Name: "foo"}, {Name: "web"}, {Name: "mweb"}, {Name: "x"}, {Name: "px"},
}, cfg)
for _, e := range entries {
if e.Name == "mfoo" && (e.Host != "" || e.Command != "") {
t.Fatal("command alias overwritten")
}
if e.Name == "mweb" && (e.Host != "mweb" || e.Command != "") {
t.Fatal("SSH alias overwritten")
}
if e.Name == "mpx" {
t.Fatal("ambiguous custom alias generated")
}
}
}
func TestCustomAliasShellArgumentQuoting(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "netssh"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
entry := hook.AliasEntry{Name: "mxg1", Host: "office/xzi-groß1'$(oops)", Command: "mtr"}
for _, shell := range []string{"bash", "zsh", "fish"} {
t.Run(shell, func(t *testing.T) {
path, err := exec.LookPath(shell)
if err != nil {
t.Skip("shell not installed")
}
// A separate parse models invoking an alias after sourcing the file.
script := entry.Definition(shell) + "\neval 'mxg1 --report'\n"
args := []string{"-c", script}
if shell == "bash" {
args = []string{"--noprofile", "--norc", "-O", "expand_aliases", "-c", script}
}
if shell == "zsh" {
args = []string{"-f", "-c", script}
}
if shell == "fish" {
args = []string{"--no-config", "-c", script}
}
out, err := exec.Command(path, args...).CombinedOutput()
want := "run\nmtr\n--\n" + entry.Host + "\n--report\n"
if err != nil || string(out) != want {
t.Fatalf("%q (%v), want %q", out, err, want)
}
})
}
}
+37 -1
View File
@@ -18,6 +18,7 @@ type fake struct {
syncState string
keys map[string]string // existing prefix bindings by key
solo string
prefix string
n int
}
@@ -33,6 +34,8 @@ func (f *fake) Output(argv ...string) (string, error) {
f.calls = append(f.calls, strings.Join(argv, " "))
f.n++
switch argv[1] {
case "show-options":
return f.prefix, nil
case "new-window", "new-session":
return fmt.Sprintf("@%d %%%d", f.n, f.n), nil
case "split-window":
@@ -121,6 +124,8 @@ func TestTmuxInside(t *testing.T) {
"tmux list-keys -T prefix S",
"tmux list-keys -T prefix e",
"tmux source-file /tmp/l/netssh-multi.tmux.conf",
"tmux set-window-option -t @1 @netssh_keys keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off",
"tmux set-window-option -t @1 pane-border-format #{@netssh_host}#{?pane_synchronized, [SYNC],#{?@netssh_solo, [SOLO],}} #{?pane_active, | #{@netssh_keys},} ",
"tmux select-window -t @1",
}
if strings.Join(f.calls, "\n") != strings.Join(want, "\n") {
@@ -234,7 +239,7 @@ func TestTmuxKeyBindings(t *testing.T) {
t.Errorf("conf lacks %q:\n%s", want, conf)
}
}
if hint != "keys: C-b S broadcast to all panes, C-b e exclude/include this pane" {
if hint != "keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off" {
t.Errorf("hint %q", hint)
}
@@ -279,3 +284,34 @@ func TestToggleSyncPane(t *testing.T) {
t.Fatalf("zellij: %v", err)
}
}
func TestTmuxPersistentHints(t *testing.T) {
for _, tc := range []struct {
name string
keys map[string]string
want string
}{
{"custom prefix", nil, "keys: Ctrl+a then Ctrl+s: sync on/off | Ctrl+a then e: solo on/off"},
{"occupied key", map[string]string{"C-s": "bind-key -T prefix C-s display-time"}, "keys: Ctrl+a then e: solo on/off; C-a C-s kept your own binding (use netssh sync)"},
} {
t.Run(tc.name, func(t *testing.T) {
f := newFake(nil, "tmux")
f.prefix, f.keys = "C-a", tc.keys
if err := Open(Tmux, panes("a", "b"), Options{PerWindow: 1, SyncKey: "C-s", SoloKey: "e"}, f); err != nil {
t.Fatal(err)
}
n := 0
for _, call := range f.calls {
if strings.Contains(call, " @netssh_keys ") {
n++
if !strings.HasSuffix(call, " @netssh_keys "+tc.want) {
t.Fatalf("wrong persistent hint: %s", call)
}
}
}
if n != 2 {
t.Fatalf("hints installed in %d windows, want 2", n)
}
})
}
}
+23 -4
View File
@@ -27,6 +27,7 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
}
groups := chunks(panes, opts.PerWindow)
first := ""
var windows []string
for i, group := range groups {
name := windowLabel(opts.Label, i, len(groups))
format := []string{"-P", "-F", "#{window_id} #{pane_id}", "-n", name}
@@ -52,6 +53,7 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
}
}
window, pane, _ := strings.Cut(out, " ")
windows = append(windows, window)
if first == "" {
first = window
}
@@ -91,6 +93,17 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
}
if keys != "" {
opts.Hint(keys)
// Window-local hints remain visible after attaching, including in an
// existing session. Keep other windows and the user's status bar intact.
for _, window := range windows {
if _, err := r.Output("tmux", "set-window-option", "-t", window, "@netssh_keys", keys); err != nil {
return err
}
if _, err := r.Output("tmux", "set-window-option", "-t", window, "pane-border-format",
" #{@netssh_host}#{?pane_synchronized, [SYNC],#{?@netssh_solo, [SOLO],}} #{?pane_active, | #{@netssh_keys},} "); err != nil {
return err
}
}
}
if inside {
_, err := r.Output("tmux", "select-window", "-t", first)
@@ -149,8 +162,8 @@ func bindKeys(r Runner, opts Options) (string, error) {
var conf strings.Builder
var hints, taken []string
for _, key := range []struct{ key, binding, what string }{
{opts.SyncKey, syncBinding, "broadcast to all panes"},
{opts.SoloKey, soloBinding, "exclude/include this pane"},
{opts.SyncKey, syncBinding, "sync on/off"},
{opts.SoloKey, soloBinding, "solo on/off"},
} {
if key.key == "" {
continue
@@ -161,7 +174,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
continue
}
fmt.Fprintf(&conf, key.binding, key.key)
hints = append(hints, prefix+" "+key.key+" "+key.what)
hints = append(hints, displayKey(prefix)+" then "+displayKey(key.key)+": "+key.what)
}
if conf.Len() > 0 {
path := filepath.Join(opts.LayoutDir, "netssh-multi.tmux.conf")
@@ -172,7 +185,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
return "", err
}
}
hint := "keys: " + strings.Join(hints, ", ")
hint := "keys: " + strings.Join(hints, " | ")
if len(hints) == 0 {
hint = "toggle broadcast with: netssh sync, netssh sync --pane"
}
@@ -192,3 +205,9 @@ func freeSession(r Runner, name string) string {
candidate = name + "-" + strconv.Itoa(n)
}
}
// displayKey expands tmux's modifier notation for the on-screen legend.
func displayKey(key string) string {
key = strings.ReplaceAll(key, "C-", "Ctrl+")
return strings.ReplaceAll(key, "M-", "Alt+")
}
+33 -24
View File
@@ -176,24 +176,32 @@ func (c *Client) GetIPs(ctx context.Context, entry HostEntry) ([]string, error)
}
return source.GetIPs(ctx, host)
}
var apiURL string
switch entry.Kind {
case "device":
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?device_id=%d&limit=100", c.baseURL, entry.ID)
return c.fetchAllIPs(ctx, fmt.Sprintf("device_id=%d", entry.ID))
case "vm":
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?virtual_machine_id=%d&limit=100", c.baseURL, entry.ID)
default:
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
return c.fetchAllIPs(ctx, fmt.Sprintf("virtual_machine_id=%d", entry.ID))
}
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
}
var resp netboxIPListResponse
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
ips := make([]string, 0, len(resp.Results))
for _, r := range resp.Results {
ips = append(ips, stripPrefix(r.Address))
// fetchAllIPs pages through the IP addresses matching filterParams, so hosts
// with more addresses than one page do not lose their management address.
func (c *Client) fetchAllIPs(ctx context.Context, filterParams string) ([]string, error) {
const pageSize = 100
var ips []string
for offset := 0; ; offset += pageSize {
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filterParams, pageSize, offset)
var resp netboxIPListResponse
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
for _, r := range resp.Results {
ips = append(ips, stripPrefix(r.Address))
}
if len(resp.Results) < pageSize || len(ips) >= resp.Count {
break
}
}
return ips, nil
}
@@ -203,16 +211,7 @@ func (c *Client) GetIPsWithFilter(ctx context.Context, filterParams string) ([]s
if c.sources != nil {
return nil, fmt.Errorf("IP filters require a host instance; use GetIPsWithFilterForHost")
}
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=100", c.baseURL, filterParams)
var resp netboxIPListResponse
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
ips := make([]string, 0, len(resp.Results))
for _, r := range resp.Results {
ips = append(ips, stripPrefix(r.Address))
}
return ips, nil
return c.fetchAllIPs(ctx, filterParams)
}
func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEntry, error) {
@@ -348,7 +347,7 @@ func (c *Client) request(ctx context.Context, method, apiURL string, body io.Rea
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("netbox returned %d for %s", resp.StatusCode, apiURL)
return "", &StatusError{Code: resp.StatusCode, URL: apiURL}
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
@@ -399,6 +398,16 @@ func stripPrefix(cidr string) string {
return cidr
}
// StatusError is an unexpected HTTP status from NetBox.
type StatusError struct {
Code int
URL string
}
func (e *StatusError) Error() string {
return fmt.Sprintf("netbox returned %d for %s", e.Code, e.URL)
}
// ErrHostNotFound distinguishes a missing exact match from API failures or ambiguity.
var ErrHostNotFound = errors.New("host not found")
+45
View File
@@ -3,8 +3,11 @@ package netbox
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
@@ -499,3 +502,45 @@ func TestCommentConflictIsReported(t *testing.T) {
t.Fatal("conflict ignored")
}
}
// Hosts with more addresses than one page must not lose the later ones.
func TestGetIPs_Paginates(t *testing.T) {
const total = 230
var offsets []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
offsets = append(offsets, r.URL.Query().Get("offset"))
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
var addrs []string
for i := offset; i < offset+limit && i < total; i++ {
addrs = append(addrs, fmt.Sprintf("10.0.%d.%d/24", i/250, i%250+1))
}
resp := ipListResponse(addrs...)
resp.Count = total
json.NewEncoder(w).Encode(resp)
}))
defer srv.Close()
ips, err := NewClient(srv.URL, "token", 0).GetIPs(context.Background(), HostEntry{ID: 1, Kind: "device"})
if err != nil {
t.Fatalf("GetIPs: %v", err)
}
if len(ips) != total || ips[total-1] != "10.0.0.230" {
t.Errorf("got %d IPs (last %q), want %d", len(ips), ips[len(ips)-1], total)
}
if strings.Join(offsets, ",") != "0,100,200" {
t.Errorf("offsets %v, want 0,100,200", offsets)
}
}
func TestRequest_StatusErrorCarriesCode(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
defer srv.Close()
_, err := NewClient(srv.URL, "token", 0).GetIPsWithFilter(context.Background(), "device_id=1&interface=nope")
var status *StatusError
if !errors.As(err, &status) || status.Code != http.StatusBadRequest {
t.Fatalf("got %v, want a StatusError with code 400", err)
}
}
+7 -1
View File
@@ -1,6 +1,9 @@
package netbox
import "strings"
import (
"strings"
"time"
)
// SearchOptions filters a Search or SearchAll query.
// Zero value means no filtering (return all kinds, no tag filter).
@@ -13,6 +16,9 @@ type SearchOptions struct {
// HostEntry is a unified model for both devices and virtual machines from NetBox.
type HostEntry struct {
Cached bool
CachedAt time.Time
Static bool
Source string // named NetBox instance; empty for the legacy single-instance config
ID int
Name string
+14 -2
View File
@@ -2,6 +2,7 @@ package resolver
import (
"context"
"errors"
"fmt"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
@@ -27,13 +28,24 @@ func New(cfg config.ResolverConfig) (*Chain, error) {
}
func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) {
address, _, err := c.ResolveWithStrategy(ctx, entry, client)
return address, err
}
func (c *Chain) ResolveWithStrategy(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, string, error) {
for _, s := range c.strategies {
ip, err := s.Resolve(ctx, entry, client)
if err == nil {
return ip, nil
return ip, s.Name(), nil
}
// Only "this strategy has no address" moves on. After an API failure
// the next strategy would connect to (and cache) a different address
// than the configured order asks for.
if !errors.Is(err, ErrNoIP) {
return "", "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err)
}
}
return "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
return "", "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
}
func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
+14
View File
@@ -153,3 +153,17 @@ func TestNew_MultipleStrategies(t *testing.T) {
t.Errorf("got %d strategies, want 2", len(c.strategies))
}
}
// An API failure must not fall through: the next strategy would connect to
// and cache a different address than the configured order asks for.
func TestChain_APIErrorStopsTheChain(t *testing.T) {
apiErr := errors.New("connection refused")
c := &Chain{strategies: []Strategy{
&stubStrategy{name: "management_subnet", err: apiErr},
&stubStrategy{name: "primary_ip", ip: "10.0.0.2"},
}}
ip, err := c.Resolve(context.Background(), &netbox.HostEntry{Name: "host"}, nil)
if !errors.Is(err, apiErr) || ip != "" {
t.Fatalf("got %q, %v; want the API error and no address", ip, err)
}
}
+6
View File
@@ -2,7 +2,9 @@ package resolver
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
@@ -31,6 +33,10 @@ func (s *InterfaceNameStrategy) Resolve(ctx context.Context, entry *netbox.HostE
}
ips, err := client.GetIPsWithFilterForHost(ctx, *entry, filterParam)
var status *netbox.StatusError
if errors.As(err, &status) && status.Code == http.StatusBadRequest {
return "", ErrNoIP // the host has no interface of this name
}
if err != nil {
return "", fmt.Errorf("fetching IPs for interface %q: %w", s.name, err)
}
+14
View File
@@ -2,6 +2,7 @@ package resolver
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
@@ -54,3 +55,16 @@ func urlQuery(s string) (string, error) {
q, err := url.ParseQuery(s)
return q.Encode(), err
}
// Only the HTTP 400 of a missing interface means "no address here"; a server
// error must stop the chain instead of silently using the next strategy.
func TestInterfaceNameStrategyServerErrorIsNotNoIP(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadGateway)
}))
defer srv.Close()
_, err := (&InterfaceNameStrategy{name: "mgmt0"}).Resolve(context.Background(), &netbox.HostEntry{ID: 7, Kind: "device"}, netbox.NewClient(srv.URL, "t", 1))
if err == nil || errors.Is(err, ErrNoIP) {
t.Fatalf("got %v, want an API error", err)
}
}
+146
View File
@@ -0,0 +1,146 @@
// Package runner supervises local commands while retaining terminal I/O.
package runner
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/charmbracelet/x/term"
)
type Options struct {
Stdin io.Reader
Stdout, Stderr io.Writer
Env []string
Timeout time.Duration
Status bool
Label string
}
type Result struct {
Code int
Started bool
Duration time.Duration
}
func Run(ctx context.Context, argv []string, o Options) Result {
if o.Stderr == nil {
o.Stderr = io.Discard
}
if o.Stdout == nil {
o.Stdout = io.Discard
}
start := time.Now()
result := Result{Code: 1}
if ctx.Err() != nil {
result.Code = 130
return result
}
if len(argv) == 0 {
return result
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr
cmd.Env = append(os.Environ(), o.Env...)
interactive := false
if f, ok := o.Stdin.(*os.File); ok {
interactive = term.IsTerminal(f.Fd())
}
// Interactive SSH must share the foreground terminal process group.
// Background jobs get an isolated group so cancellation reaches descendants.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: !interactive}
if err := cmd.Start(); err != nil {
fmt.Fprintf(o.Stderr, "%s: %v\n", argv[0], err)
return result
}
result.Started = true
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
sigs := make(chan os.Signal, 4)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
defer signal.Stop(sigs)
var timeout <-chan time.Time
if o.Timeout > 0 {
timer := time.NewTimer(o.Timeout)
defer timer.Stop()
timeout = timer.C
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var killTimer *time.Timer
var kill <-chan time.Time
defer func() {
if killTimer != nil {
killTimer.Stop()
}
}()
send := func(sig syscall.Signal) {
if interactive {
_ = cmd.Process.Signal(sig)
} else {
_ = syscall.Kill(-cmd.Process.Pid, sig)
}
}
forced := 0
cancelCh := ctx.Done()
stop := func(code int, sig syscall.Signal) {
if forced != 0 {
return
}
forced = code
send(sig)
killTimer = time.NewTimer(2 * time.Second)
kill = killTimer.C
}
for {
select {
case err := <-done:
result.Duration = time.Since(start)
result.Code = 0
if err != nil {
result.Code = 1
if e, ok := err.(*exec.ExitError); ok {
result.Code = e.ExitCode()
if s, ok := e.Sys().(syscall.WaitStatus); ok && s.Signaled() {
result.Code = 128 + int(s.Signal())
}
}
}
if forced != 0 {
result.Code = forced
}
// Kill descendants left behind after cancellation even if the parent exited.
if forced != 0 && !interactive {
send(syscall.SIGKILL)
}
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] finished in %s (exit %d)\n", o.Label, result.Duration.Round(time.Millisecond), result.Code)
}
return result
case sig := <-sigs:
s := sig.(syscall.Signal)
if interactive && (s == syscall.SIGINT || s == syscall.SIGQUIT) {
continue
} // terminal delivered it to child too
stop(128+int(s), s)
case <-cancelCh:
cancelCh = nil
stop(130, syscall.SIGTERM)
case <-timeout:
timeout = nil
stop(124, syscall.SIGTERM)
case <-kill:
kill = nil
send(syscall.SIGKILL)
case <-ticker.C:
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] running %s (Ctrl+C cancels)\n", o.Label, time.Since(start).Round(time.Second))
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package runner
import (
"bytes"
"context"
"io"
"strings"
"testing"
"time"
)
func TestExitAndTimeout(t *testing.T) {
var out bytes.Buffer
r := Run(context.Background(), []string{"sh", "-c", "printf result; exit 7"}, Options{Stdout: &out, Stderr: io.Discard})
if !r.Started || r.Code != 7 || out.String() != "result" {
t.Fatalf("%+v %q", r, out.String())
}
start := time.Now()
r = Run(context.Background(), []string{"sh", "-c", "trap '' TERM; sleep 30 & wait"}, Options{Stdout: io.Discard, Stderr: io.Discard, Timeout: 50 * time.Millisecond})
if r.Code != 124 || time.Since(start) > 4*time.Second {
t.Fatalf("timeout: %+v", r)
}
}
func TestCancellationAndNoStart(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
r := Run(ctx, []string{"sh", "-c", "exit 0"}, Options{Stderr: io.Discard})
if r.Started || r.Code != 130 {
t.Fatalf("%+v", r)
}
var errOut bytes.Buffer
r = Run(context.Background(), []string{"/no/such/netssh-test-executable"}, Options{Stderr: &errOut})
if r.Started || r.Code == 0 || !strings.Contains(errOut.String(), "no such") {
t.Fatalf("%+v %s", r, errOut.String())
}
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
time.AfterFunc(50*time.Millisecond, cancel)
r = Run(ctx, []string{"sh", "-c", "sleep 30"}, Options{Stdout: io.Discard, Stderr: io.Discard})
if r.Code != 130 {
t.Fatalf("%+v", r)
}
}
+94
View File
@@ -0,0 +1,94 @@
package setup
import (
"fmt"
"sort"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editCommands(cfg *config.Config) error {
for {
var names []string
for name := range cfg.Commands {
names = append(names, name)
}
sort.Strings(names)
var options []huh.Option[string]
for _, name := range names {
options = append(options, huh.NewOption("Edit "+name, "edit:"+name), huh.NewOption("Remove "+name, "remove:"+name))
}
options = append(options, huh.NewOption("Add command", "add"), huh.NewOption("Done", "done"))
action := "done"
if err := huh.NewSelect[string]().Title("Custom host commands").Options(options...).Value(&action).Run(); err != nil {
return err
}
if action == "done" {
return nil
}
if name, ok := strings.CutPrefix(action, "remove:"); ok {
remove := false
if err := huh.NewConfirm().Title("Remove " + name + "?").Value(&remove).Run(); err != nil {
return err
}
if remove {
delete(cfg.Commands, name)
}
continue
}
original, _ := strings.CutPrefix(action, "edit:")
if action == "add" {
original = ""
}
name := original
command := cfg.Commands[original]
binary, arguments := "", ""
if len(command.Args) > 0 {
binary = command.Args[0]
arguments = strings.Join(command.Args[1:], "\n")
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Command name").Placeholder("mtr").Value(&name).Validate(func(s string) error {
if s == "" {
return fmt.Errorf("required")
}
if s != original {
if _, exists := cfg.Commands[s]; exists {
return fmt.Errorf("name already exists")
}
}
return config.ValidateCommandAlias(s)
}),
huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix),
huh.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary),
huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments),
huh.NewConfirm().Title("Confirm before running?").Value(&command.Confirm),
huh.NewInput().Title("Timeout").Description("Optional positive duration, e.g. 30s or 5m.").Value(&command.Timeout),
huh.NewInput().Title("Post-run script").Description("Local command after completion; receives NETSSH_EXIT_CODE.").Value(&command.PostRun),
huh.NewInput().Title("Only for tag").Value(&command.Match.Tag),
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
).Title("Local command")).Run()
if err != nil {
return err
}
command.Args = []string{binary}
if arguments != "" {
command.Args = append(command.Args, strings.Split(arguments, "\n")...)
}
candidate := config.Config{Commands: make(map[string]config.HostCommand)}
for k, v := range cfg.Commands {
if k != original {
candidate.Commands[k] = v
}
}
candidate.Commands[name] = command
if err := candidate.ValidateCommands(); err != nil {
return err
}
cfg.Commands = candidate.Commands
}
}
+3
View File
@@ -108,6 +108,9 @@ func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, ori
}
return nil
}),
huh.NewConfirm().Title("Hide instance prefix in aliases and TUI?").
Description("Shorter shell aliases and TUI host names. Conflicting names keep their prefix.").
Value(&source.DisablePrefix),
huh.NewInput().Title("NetBox URL").Placeholder("https://netbox.example.com").Value(&source.URL).Validate(func(value string) error {
return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes()
}),
+35
View File
@@ -0,0 +1,35 @@
package setup
import (
"fmt"
"strconv"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editOperations(cfg *config.Config) error {
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
enabled := cfg.Activity.Enabled
valid := func(s string) error {
n, err := strconv.Atoi(s)
if err != nil || n < 0 {
return fmt.Errorf("enter a non-negative number")
}
return nil
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Recent hosts shown").Description("10 by default; 0 shows all. Favorites are additional.").Value(&history).Validate(valid),
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
).Title("History & activity")).Run()
if err != nil {
return err
}
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
cfg.Activity.Enabled = enabled
return nil
}
+13
View File
@@ -23,6 +23,8 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
extraArgs := strings.Join(o.ExtraArgs, "\n")
options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect
postDisconnect := o.PostDisconnect
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
@@ -69,6 +71,15 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s)
return err
}),
huh.NewInput().Title("Post-disconnect script").Description("Local command after the client exits; none disables inheritance.").Value(&postDisconnect),
huh.NewInput().
Title("Pre-connect hook").
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
"A non-zero exit aborts. Leave empty to inherit; 'none' disables a hook set elsewhere.").
Value(&preConnect).
Validate(func(s string) error {
return config.SSHOptions{PreConnect: s}.Validate("ssh")
}),
).Title(title)).Run()
if err != nil {
return o, err
@@ -84,6 +95,8 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
AddressFamily: addressFamily,
ExtraArgs: parseLines(extraArgs),
Options: parsed,
PreConnect: strings.TrimSpace(preConnect),
PostDisconnect: strings.TrimSpace(postDisconnect),
}, nil
}
+54 -3
View File
@@ -94,6 +94,8 @@ func runMenu(cfg *config.Config) error {
huh.NewOption(fmt.Sprintf("Multi-session — groups, tmux/zellij (%d groups)", len(cfg.Groups)), "multi"),
huh.NewOption("Resolver & cache", "resolver"),
huh.NewOption("Shortcuts & command alias", "shortcuts"),
huh.NewOption("Custom commands — mtr, ping, scripts", "commands"),
huh.NewOption("History & activity logging", "operations"),
huh.NewOption("Completion", "completion"),
huh.NewOption("Save and exit", "save"),
).
@@ -122,6 +124,10 @@ func runMenu(cfg *config.Config) error {
err = editResolverCache(cfg)
case "shortcuts":
err = editShortcuts(cfg)
case "commands":
err = editCommands(cfg)
case "operations":
err = editOperations(cfg)
case "completion":
err = editCompletion(cfg)
case "save":
@@ -226,6 +232,7 @@ func editShortcuts(cfg *config.Config) error {
stripHyphens := cfg.Shortcuts.StripHyphens
rewrites := formatRewrites(cfg.Shortcuts.Rewrites)
commandAlias := cfg.Shell.Alias
showShortcuts := cfg.Shortcuts.Show
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Domain suffixes").
@@ -247,6 +254,11 @@ func editShortcuts(cfg *config.Config) error {
_, err := parseRewrites(s)
return err
}),
huh.NewConfirm().
Title("Show shortcuts").
Description("Show each host's shortcut alias in the TUI, netssh cache list and netssh hosts list,\n"+
"and offer shortcuts in Tab completion even when the full name matches.").
Value(&showShortcuts),
huh.NewInput().
Title("Command alias").
Description("Optional alias for netssh itself, e.g. j. Leave empty to disable.").
@@ -266,6 +278,7 @@ func editShortcuts(cfg *config.Config) error {
}
cfg.Shortcuts.StripHyphens = stripHyphens
cfg.Shortcuts.Rewrites, _ = parseRewrites(rewrites)
cfg.Shortcuts.Show = showShortcuts
cfg.Shell.Alias = strings.TrimSpace(commandAlias)
return nil
}
@@ -372,6 +385,12 @@ func save(cfg config.Config) error {
if err := cfg.ValidateHosts(); err != nil {
return err
}
if err := cfg.ValidateOperations(); err != nil {
return err
}
if err := cfg.ValidateCommands(); err != nil {
return err
}
if err := cfg.ValidateMulti(); err != nil {
return err
}
@@ -385,6 +404,9 @@ func save(cfg config.Config) error {
b.WriteString("netboxes:\n")
for _, source := range cfg.NetBoxes {
fmt.Fprintf(&b, " - name: %q\n url: %q\n token: %q\n token_version: %d\n", source.Name, source.URL, source.Token, source.TokenVersion)
if source.DisablePrefix {
b.WriteString(" disable_prefix: true\n")
}
if !sshOptionsEmpty(source.SSH) {
b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", source.SSH)
@@ -501,7 +523,7 @@ func save(cfg config.Config) error {
fmt.Fprintf(&b, "\ncompletion:\n max_results: %d\n", cfg.Completion.MaxResults)
}
if cfg.Shortcuts.Enabled() {
if cfg.Shortcuts.Enabled() || cfg.Shortcuts.Show {
b.WriteString("\nshortcuts:\n")
if len(cfg.Shortcuts.Domains) > 0 {
b.WriteString(" domains:\n")
@@ -518,8 +540,37 @@ func save(cfg config.Config) error {
fmt.Fprintf(&b, " - pattern: %q\n replace: %q\n", r.Pattern, r.Replace)
}
}
if cfg.Shortcuts.Show {
b.WriteString(" show: true\n")
}
}
if len(cfg.Commands) > 0 {
b.WriteString("\ncommands:\n")
var names []string
for name := range cfg.Commands {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
command := cfg.Commands[name]
fmt.Fprintf(&b, " %s:\n alias_prefix: %q\n args:\n", name, command.AliasPrefix)
for _, arg := range command.Args {
fmt.Fprintf(&b, " - %q\n", arg)
}
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
if command.Match != (config.SSHMatch{}) {
b.WriteString(" match:\n")
for _, pair := range [][2]string{{"tag", command.Match.Tag}, {"instance", command.Match.Instance}, {"kind", command.Match.Kind}, {"name", command.Match.Name}} {
if pair[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
}
}
}
}
}
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\nactivity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.TUI.HistoryLimit, cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
if cfg.Shell.Alias != "" {
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
}
@@ -533,12 +584,12 @@ func save(cfg config.Config) error {
}
func sshOptionsEmpty(o config.SSHOptions) bool {
return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0
return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 && o.PreConnect == "" && o.PostDisconnect == ""
}
// writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config.
func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}} {
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}, {"post_disconnect", o.PostDisconnect}} {
if field[1] != "" {
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
}
+70 -2
View File
@@ -398,7 +398,7 @@ func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2},
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2, DisablePrefix: true},
{Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1},
},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
@@ -438,9 +438,10 @@ func TestSaveKeepsSSHOptions(t *testing.T) {
AddressFamily: "inet",
ExtraArgs: []string{"-A"},
Options: map[string]string{"serveraliveinterval": "60"},
PreConnect: `vpn-check "$NETSSH_HOST" && echo 'ok'`,
}
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off"}}},
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off", PreConnect: "none"}}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600},
SSH: config.SSHConfig{
@@ -651,3 +652,70 @@ func TestParseGroupsAndSaveMulti(t *testing.T) {
t.Fatalf("got %v %+v", loaded.Groups, loaded.Multi)
}
}
func TestSaveKeepsShortcutsShow(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
for _, sc := range []config.ShortcutsConfig{
{Domains: []string{".example.com"}, Show: true},
{Show: true}, // no shortcut rules yet: the switch alone must survive
} {
cfg := config.Config{
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600},
Shortcuts: sc,
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !loaded.Shortcuts.Show || !reflect.DeepEqual(loaded.Shortcuts.Domains, sc.Domains) {
t.Fatalf("shortcuts lost: %+v", loaded.Shortcuts)
}
}
}
func TestSaveCommandsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "test"},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "--report", "{address}"}},
"ping": {AliasPrefix: "p", Args: []string{"ping", "-c", "3", "{address}"}},
},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got.Commands, cfg.Commands) {
t.Fatalf("commands lost: %+v", got.Commands)
}
}
func TestOperationsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "token"},
TUI: config.TUIConfig{HistoryLimit: 25},
Activity: config.ActivityConfig{Enabled: true, RetentionDays: 7, MaxEntries: 50},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PostDisconnect: "echo done"}, Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "lab"}, SSHOptions: config.SSHOptions{PostDisconnect: "none"}}}},
Commands: map[string]config.HostCommand{"mtr": {Args: []string{"mtr", "{address}"}, AliasPrefix: "m", Timeout: "10s", Confirm: true, PostRun: "echo done", Match: config.SSHMatch{Tag: "router", Instance: "prod"}}},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if got.TUI != cfg.TUI || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
t.Fatalf("round trip lost operations: %+v", got)
}
}
+13
View File
@@ -2,6 +2,7 @@ package ssh
import (
"fmt"
"net/netip"
"regexp"
"sort"
"strings"
@@ -142,6 +143,18 @@ type Result struct {
Notice string
}
var destinationName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
// ValidAddress reports whether addr is an IP address or a hostname. Addresses
// come from NetBox and the cache file; one such as "-oProxyCommand=…" would be
// read by ssh as an option and run a command.
func ValidAddress(addr string) bool {
if _, err := netip.ParseAddr(addr); err == nil {
return !strings.ContainsAny(addr, " \t\r\n")
}
return destinationName.MatchString(addr)
}
var plainHostname = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`)
// Apply replaces the destination at destIdx and inserts the configured -o
+14
View File
@@ -128,3 +128,17 @@ func TestQuote(t *testing.T) {
t.Fatalf("got %s", got)
}
}
func TestValidAddress(t *testing.T) {
for _, addr := range []string{"10.0.0.1", "fd00:30::60", "fe80::1%eth0", "web01", "web01.example.com", "db_1.lan"} {
if !ValidAddress(addr) {
t.Errorf("ValidAddress(%q) = false, want true", addr)
}
}
// ssh would read the first as an option and run the command.
for _, addr := range []string{"-oProxyCommand=touch /tmp/pwned", "-J", "", "a b", "host;id", "user@host", "host/path", "fe80::1%eth0 x", "$(id)"} {
if ValidAddress(addr) {
t.Errorf("ValidAddress(%q) = true, want false", addr)
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package storage
import (
"os"
"path/filepath"
"testing"
)
func TestWriteFileReplacesAtomically(t *testing.T) {
dir := filepath.Join(t.TempDir(), "new", "dir")
path := filepath.Join(dir, "file")
for _, content := range []string{"first", "second"} {
if err := WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(path)
if err != nil || string(got) != content {
t.Fatalf("got %q, %v; want %q", got, err, content)
}
}
info, err := os.Stat(path)
if err != nil || info.Mode().Perm() != 0o600 {
t.Errorf("mode %v, %v; want 0600", info.Mode().Perm(), err)
}
entries, _ := os.ReadDir(dir)
if len(entries) != 1 {
t.Errorf("temporary files left behind: %v", entries)
}
}
+114
View File
@@ -9,6 +9,7 @@ import (
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
@@ -79,3 +80,116 @@ func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) {
t.Fatalf("outage warning overflowed view: %d", rows)
}
}
func TestHiddenPrefixKeepsCanonicalTargets(t *testing.T) {
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
{Name: "OFFICE", DisablePrefix: true}, {Name: "lab"},
}}
for _, cached := range []bool{false, true} {
for _, action := range []string{"ssh", "sftp", "multi", "autocomplete", "edit", "tunnel"} {
t.Run(fmt.Sprintf("cached=%v/%s", cached, action), func(t *testing.T) {
m := New(nil, nil, "")
m.SetHostLabel(cfg.HostLabel)
m.Update(tea.WindowSizeMsg{Width: 100, Height: 24})
entries := []netbox.HostEntry{
{Source: "office", Name: "web01", PrimaryIP4: "10.0.0.1"},
{Source: "lab", Name: "web01", PrimaryIP4: "10.0.0.2"},
}
if cached {
for i := range entries {
entries[i].Name = entries[i].Target()
entries[i].Source = ""
}
}
m.updateListItems(entries)
item := m.list.Items()[0].(hostItem)
if item.Title() != "web01" || item.name != "office/web01" {
t.Fatalf("display changed identity: %+v", item)
}
view := m.View().Content
if strings.Contains(view, "office/web01") || !strings.Contains(view, "lab/web01") {
t.Fatalf("wrong rendered prefixes: %s", view)
}
switch action {
case "ssh", "sftp":
key := tea.KeyPressMsg{Code: tea.KeyEnter}
if action == "sftp" {
key = tea.KeyPressMsg{Code: 'o', Mod: tea.ModCtrl}
}
m.Update(key)
if m.selected == nil || m.selected.Name != "office/web01" {
t.Fatalf("lost instance: %+v", m.selected)
}
case "multi":
m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.selected == nil || len(m.selected.Targets) != 1 || m.selected.Targets[0] != "office/web01" {
t.Fatalf("multi lost instance: %+v", m.selected)
}
case "autocomplete":
m.Update(tea.KeyPressMsg{Code: tea.KeyTab})
if m.input.Value() != "office/web01" {
t.Fatal("autocomplete lost instance")
}
case "edit":
m.Update(tea.KeyPressMsg{Code: 'e', Mod: tea.ModCtrl})
if m.editHost == nil || m.editHost.name != "office/web01" {
t.Fatal("editor lost instance")
}
case "tunnel":
m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl})
if m.forwardHost == nil || m.forwardHost.name != "office/web01" {
t.Fatal("tunnel lost instance")
}
}
})
}
}
}
func TestHiddenPrefixDuplicateLabels(t *testing.T) {
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
{Name: "office", DisablePrefix: true}, {Name: "lab", DisablePrefix: true},
}}
for _, other := range []netbox.HostEntry{
{Source: "lab", Name: "WEB"},
{Name: "web", Kind: "static"},
} {
m := New(nil, nil, "")
m.SetHostLabel(cfg.HostLabel)
m.updateListItems([]netbox.HostEntry{{Source: "office", Name: "web"}, other})
for _, entry := range m.list.Items() {
item := entry.(hostItem)
if item.Title() != item.name {
t.Fatalf("ambiguous label: %+v", item)
}
}
}
}
func TestAliasesShownNextToHostName(t *testing.T) {
m := New(nil, cache.New("", 3600), "")
m.SetAliases(func(target string) string {
return map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "web01": "web01"}[target]
})
m.updateListItems([]netbox.HostEntry{{Name: "fsn1-bx1.hoster.de", PrimaryIP4: "10.0.0.1"}, {Name: "web01", PrimaryIP4: "10.0.0.2"}})
items := m.list.Items()
if got := items[0].(hostItem).alias; got != "fsnbx1" {
t.Fatalf("alias = %q", got)
}
// An alias equal to the shown name is not repeated.
if got := items[1].(hostItem).alias; got != "" {
t.Fatalf("redundant alias %q", got)
}
var b strings.Builder
compactDelegate{marked: map[string]bool{}}.Render(&b, m.list, 1, items[0])
if !strings.Contains(b.String(), "fsn1-bx1.hoster.de") || !strings.Contains(b.String(), "→ fsnbx1") {
t.Fatalf("row %q", b.String())
}
// Without SetAliases nothing changes.
plain := New(nil, cache.New("", 3600), "")
plain.updateListItems([]netbox.HostEntry{{Name: "fsn1-bx1.hoster.de"}})
if got := plain.list.Items()[0].(hostItem).alias; got != "" {
t.Fatalf("alias without SetAliases: %q", got)
}
}
+235 -14
View File
@@ -22,6 +22,7 @@ import (
// SelectedHost is returned when the user confirms a host in the TUI.
type SelectedHost struct {
Command string
Kind string
Name string
IP string
@@ -63,14 +64,23 @@ type searchResultMsg struct {
// --- list item ---
type hostItem struct {
name string
id int
ip string
kind string
tags []string
provenance string
favorite, pinned bool
label string // display only; name remains the canonical target
alias string // shortcut alias shown next to the name (shortcuts.show)
name string
id int
ip string
kind string
tags []string
}
func (h hostItem) Title() string { return h.name }
func (h hostItem) Title() string {
if h.label != "" {
return h.label
}
return h.name
}
func (h hostItem) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) }
func (h hostItem) FilterValue() string { return h.name }
@@ -91,7 +101,20 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
if d.marked[h.key()] {
mark = "● "
}
line := fmt.Sprintf(" %s%s %s", mark, h.name, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
title := h.Title()
if h.alias != "" {
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+h.alias)
}
badge := ""
if h.pinned {
badge = "◆ "
} else if h.favorite {
badge = "★ "
}
line := fmt.Sprintf(" %s%s %s", mark+badge, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
if h.provenance != "" {
line += " [" + h.provenance + "]"
}
if index == m.Index() {
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
}
@@ -150,6 +173,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
// --- Model ---
type Model struct {
historyLimit int
favorites, pinned map[string]bool
savePreferences func(map[string]bool, map[string]bool) error
commandsFor func(string, string, []string) []string
actionHost *hostItem
actionNames []string
actionIndex int
noteErr error
editHost *hostItem
noteInput textarea.Model
@@ -181,7 +212,9 @@ type Model struct {
editMode bool // Ctrl+E on the selected item
forwardMode bool // Ctrl+T on the selected item
marked map[string]bool // hostItem.key() of hosts marked with space
markOrder []string // targets in the order they were marked
hostLabel func(string) string
aliasFor func(string) string // shortcut alias per target, "" for none
markOrder []string // targets in the order they were marked
}
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
@@ -216,6 +249,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ni.CharLimit = 0
ni.SetHeight(10)
return &Model{
historyLimit: 10, favorites: map[string]bool{}, pinned: map[string]bool{},
noteInput: ni,
defaultPort: port,
input: ti,
@@ -237,14 +271,40 @@ func (m *Model) Init() tea.Cmd {
// loadRecent returns a Cmd that immediately resolves to the recently-used host list.
func (m *Model) loadRecent() tea.Cmd {
favoriteNames, pinned, limit := copyBools(m.favorites), copyBools(m.pinned), m.historyLimit
return func() tea.Msg {
if m.cache == nil {
return searchResultMsg{query: "", entries: nil, recent: true}
}
recent := m.cache.RecentlyUsed(10)
recent := m.cache.RecentlyUsed(limit)
seen := map[string]bool{}
var favorites []cache.Entry
for name, enabled := range favoriteNames {
if !enabled {
continue
}
e, _ := m.cache.Get(name)
if e.Name == "" {
e.Name = name
}
favorites = append(favorites, e)
seen[name] = true
}
sort.Slice(favorites, func(i, j int) bool {
if pinned[favorites[i].Name] != pinned[favorites[j].Name] {
return pinned[favorites[i].Name]
}
return favorites[i].Name < favorites[j].Name
})
for _, e := range recent {
if !seen[e.Name] {
favorites = append(favorites, e)
}
}
recent = favorites
entries := make([]netbox.HostEntry, len(recent))
for i, e := range recent {
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags}
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cached: true, CachedAt: e.CachedAt, Static: e.Static}
}
return searchResultMsg{query: "", entries: entries, recent: true}
}
@@ -281,6 +341,34 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.String() == "ctrl+c" {
return m, tea.Quit
}
if m.actionHost != nil {
switch msg.String() {
case "esc":
m.actionHost = nil
case "up":
if m.actionIndex > 0 {
m.actionIndex--
}
case "down":
if m.actionIndex+1 < len(m.actionNames) {
m.actionIndex++
}
case "enter":
h := m.actionHost
if m.actionIndex == 0 {
if len(m.markOrder) > 0 {
m.selected = &SelectedHost{Action: ActionMulti, Targets: append([]string(nil), m.markOrder...)}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip}
}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip, Command: m.actionNames[m.actionIndex], Targets: append([]string(nil), m.markOrder...)}
}
return m, tea.Quit
}
return m, nil
}
if m.noteMode {
if m.noteBusy {
return m, nil
@@ -390,6 +478,43 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "ctrl+c", "esc":
return m, tea.Quit
case "ctrl+r":
if h, ok := m.list.SelectedItem().(hostItem); ok {
m.actionHost = &h
m.actionIndex = 0
m.actionNames = []string{"SSH"}
if m.commandsFor != nil {
m.actionNames = append(m.actionNames, m.commandsFor(h.name, h.kind, h.tags)...)
}
}
return m, nil
case "ctrl+d", "ctrl+p":
if h, ok := m.list.SelectedItem().(hostItem); ok {
favorites, pinned := copyBools(m.favorites), copyBools(m.pinned)
if msg.String() == "ctrl+p" {
pinned[h.name] = !pinned[h.name]
if pinned[h.name] {
favorites[h.name] = true
}
} else {
favorites[h.name] = !favorites[h.name]
if !favorites[h.name] {
delete(pinned, h.name)
}
}
if m.savePreferences != nil {
if err := m.savePreferences(favorites, pinned); err != nil {
m.err = err
return m, nil
}
}
m.favorites, m.pinned = favorites, pinned
m.updateListItems(m.lastResults)
if m.recentMode && m.input.Value() == "" {
return m, m.loadRecent()
}
}
return m, nil
case "ctrl+f":
m.filterOpen = true
m.input.Blur()
@@ -550,6 +675,24 @@ func (m *Model) View() tea.View {
}
func (m *Model) viewContent() string {
if m.actionHost != nil {
var out strings.Builder
fmt.Fprintf(&out, "Action for %s", m.actionHost.Title())
if len(m.markOrder) > 0 {
fmt.Fprintf(&out, " (%d marked hosts)", len(m.markOrder))
}
out.WriteString("\n\n")
for i, n := range m.actionNames {
marker := " "
if i == m.actionIndex {
marker = "> "
}
fmt.Fprintf(&out, "%s%s\n", marker, n)
}
out.WriteString("\n↑/↓ select enter run esc cancel\n")
return out.String()
}
if m.noteMode {
target := "local"
if m.noteRemote {
@@ -610,7 +753,7 @@ func (m *Model) viewContent() string {
sb.WriteString(m.editInput.View() + "\n")
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n")
} else {
hint := "ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox"
hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox"
if n := len(m.markOrder); n > 0 {
hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n)
}
@@ -639,7 +782,7 @@ func (m *Model) doSearch(query string, seq int) tea.Cmd {
if m.cache != nil {
for _, entry := range m.cache.Search(query) {
source, name := netbox.SplitTarget(entry.Name)
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags})
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags, Cached: true, CachedAt: entry.CachedAt, Static: entry.Static})
}
}
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
@@ -676,14 +819,64 @@ func (m *Model) netboxSearchOpts() netbox.SearchOptions {
// updateListItems applies the active filter and sets the list items.
func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value())
filtered := applyFilter(entries, f)
filtered := append([]netbox.HostEntry(nil), applyFilter(entries, f)...)
sort.SliceStable(filtered, func(i, j int) bool {
rank := func(e netbox.HostEntry) int {
if m.pinned[e.Target()] {
return 2
}
if m.favorites[e.Target()] {
return 1
}
return 0
}
return rank(filtered[i]) > rank(filtered[j])
})
items := make([]list.Item, len(filtered))
labels := make([]string, len(filtered))
counts := make(map[string]int, len(filtered))
canonical := make(map[string]bool, len(filtered))
for i, e := range filtered {
labels[i] = e.Target()
canonical[strings.ToLower(e.Target())] = true
if m.hostLabel != nil {
labels[i] = m.hostLabel(e.Target())
}
counts[strings.ToLower(labels[i])]++
}
for i, e := range filtered {
ip := e.PrimaryIP4
if ip == "" {
ip = e.PrimaryIP6
}
items[i] = hostItem{id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
label := labels[i]
if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) {
label = e.Target()
}
alias := ""
if m.aliasFor != nil {
alias = m.aliasFor(e.Target())
if strings.EqualFold(alias, label) {
alias = ""
}
}
provenance := "live"
if e.Static {
provenance = "static"
} else if e.Cached {
if e.CachedAt.IsZero() {
provenance = "saved host; resolve on connect"
} else {
age := max(time.Duration(0), time.Since(e.CachedAt)).Round(time.Second)
provenance = "cache " + age.String()
if m.cache != nil {
if _, fresh := m.cache.Get(e.Target()); !fresh {
provenance += ", stale"
}
}
}
}
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
}
m.list.SetItems(items)
m.resizeList()
@@ -819,3 +1012,31 @@ func parseForwards(input string, available []string) ([]string, error) {
}
return fields, nil
}
// SetHostLabel sets the display name formatter without changing host identity.
// Configure it before the program starts, just like SetNotes and SetForwards.
func (m *Model) SetHostLabel(format func(string) string) {
m.hostLabel = format
}
// SetAliases shows the shortcut alias returned for each target next to its
// name; return "" for hosts without one. Configure it before the program starts.
func (m *Model) SetAliases(aliasFor func(target string) string) {
m.aliasFor = aliasFor
}
func copyBools(in map[string]bool) map[string]bool {
out := map[string]bool{}
for k, v := range in {
out[k] = v
}
return out
}
func (m *Model) SetHistoryLimit(limit int) { m.historyLimit = limit }
func (m *Model) SetPreferences(favorites, pinned map[string]bool, save func(map[string]bool, map[string]bool) error) {
m.favorites, m.pinned = copyBools(favorites), copyBools(pinned)
m.savePreferences = save
}
func (m *Model) SetCommands(commands func(string, string, []string) []string) {
m.commandsFor = commands
}
+67
View File
@@ -0,0 +1,67 @@
package tui
import (
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestFavoritesHistoryAndActions(t *testing.T) {
c := cache.New("", 3600)
for _, name := range []string{"a", "b", "pinned"} {
c.Upsert(cache.Entry{Name: name, IP: "10.0.0.1", Kind: "device"})
c.MarkUsed(name)
}
m := New(nil, c, "")
m.SetHistoryLimit(1)
m.SetPreferences(map[string]bool{"pinned": true, "offline/missing": true}, map[string]bool{"pinned": true}, nil)
msg := m.loadRecent()().(searchResultMsg)
if len(msg.entries) < 2 || msg.entries[0].Target() != "pinned" {
t.Fatalf("%+v", msg.entries)
}
m.Update(msg)
m.Update(tea.WindowSizeMsg{Width: 160, Height: 30})
if !strings.Contains(m.View().Content, "◆") || !strings.Contains(m.View().Content, "cache") {
t.Fatal(m.View().Content)
}
m.SetCommands(func(name, kind string, tags []string) []string { return []string{"mtr"} })
m.Update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl})
m.Update(tea.KeyPressMsg{Code: tea.KeyDown})
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.Selected() == nil || m.Selected().Command != "mtr" || m.Selected().Name != "pinned" {
t.Fatalf("%+v", m.Selected())
}
}
func TestHistoryLimitAndPreferencePersistence(t *testing.T) {
c := cache.New("", 3600)
for _, n := range []string{"a", "b", "c"} {
c.Upsert(cache.Entry{Name: n})
c.MarkUsed(n)
}
m := New(nil, c, "")
m.SetHistoryLimit(2)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 2 {
t.Fatal(got)
}
m.SetHistoryLimit(0)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 3 {
t.Fatal(got)
}
saved := false
m.SetPreferences(nil, nil, func(f, p map[string]bool) error { saved = f["prod/web"] && p["prod/web"]; return nil })
entries := []netbox.HostEntry{{Name: "web", Source: "prod", Cached: true, CachedAt: time.Now().Add(-2 * time.Hour)}}
m.lastResults = entries
m.updateListItems(entries)
m.Update(tea.KeyPressMsg{Code: 'p', Mod: tea.ModCtrl})
if !saved {
t.Fatal("pin not persisted")
}
item := m.list.Items()[0].(hostItem)
if !strings.Contains(item.provenance, "stale") {
t.Fatal(item.provenance)
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
name: netssh-test
x-netbox: &netbox
image: netboxcommunity/netbox:v4.7.4-5.1.1
image: netboxcommunity/netbox:v4.7.5-5.1.1
depends_on:
postgres: {condition: service_healthy}
redis: {condition: service_healthy}