feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-18 10:41:36 +01:00
1 parent 8d4915543e
commit e5bde9c61f
32 files changed
+2083 -64

No files matched your search

+196 -2
View File
@@ -22,6 +22,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [Quick start](#quick-start)
- [Configuration](#configuration) — [wizard](#interactive-wizard), [manual config](#manual-config), [reference](#configuration-reference), [environment variables](#environment-variables), [files](#files-and-directories), [multiple instances](#multiple-netbox-instances)
- [Usage](#usage) — [command overview](#command-overview), [SSH options](#ssh-options), [pre-connect hook](#pre-connect-hook), [SFTP & SCP](#sftp-and-scp), [port forwarding](#port-forwarding), [static hosts](#static-hosts), [multiple servers](#multiple-servers-in-one-window), [shortcuts](#host-shortcuts), [TUI](#interactive-tui), [notes](#server-notes), [cache](#cache-management)
- [Operations](#operations) — post scripts, favorites, history, diagnostics, batch commands, configuration sharing
- [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)
@@ -36,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
@@ -229,6 +230,10 @@ 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. |
@@ -403,6 +408,10 @@ 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). |
@@ -927,7 +936,7 @@ 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.
See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys.
@@ -1038,6 +1047,9 @@ in the search, while tmux uses `Ctrl+b` as its default prefix.
| `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 |
@@ -1113,6 +1125,188 @@ 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**