Compare commits

..
86 Commits
Author SHA1 Message Date
Sebastian UnterschützandClaude Fable 5.2 4287b7b650 fix: harden config loading and ssh addresses, stop resolver on API errors
Release / release (push) Successful in 5m59s
- read netssh.yaml from the user config directory only, not from the
  working directory
- refuse addresses from NetBox or the cache that are neither an IP
  address nor a hostname (ssh read "-oProxyCommand=…" as an option)
- resolver chain stops at an API failure; only "no address" falls
  through to the next strategy
- netssh --help and -h show netssh's help
- start at most one background cache refresh per 5 minutes
- validate the legacy netbox.url
- page through all IP addresses of a host
- CI: run format check, vet, and tests on pull requests and main
- changelog for v0.0.25

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 23:25:28 +01:00
Sebi 6e80b733dc Merge pull request 'v0.0.24' (#40) from release/v0.0.24 into main
Release / release (push) Successful in 6m20s
2026-11-14 12:56:51 +00:00
Sebastian UnterschützandClaude Opus 5.5 d3e7f137c3 docs: changelog for v0.0.24
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:56:13 +01:00
Sebi 6493e7c41e Merge pull request 'netssh multi: mehrere Server in einem Fenster (tmux/zellij)' (#37) from feat/multi into main 2026-11-14 12:36:50 +00:00
Sebi a8bf2b4141 Merge pull request 'Docker-Testumgebung + 3 Bugfixes' (#36) from test/docker-env into main 2026-11-14 12:35:36 +00:00
Sebastian UnterschützandClaude Opus 5.5 396d489187 feat(multi): tmux keys to toggle broadcast and exclude single panes
In windows opened by netssh multi, prefix S toggles broadcast for all
panes and prefix e excludes the current pane (a pane-level
synchronize-panes off, shown as [SOLO] in the border) or includes it
again. netssh sync --pane does the same from a shell.

S and e are unbound in a default tmux (E would be "spread evenly").
netssh writes the bindings to a small tmux config and sources it, binds
a key only if the user's tmux.conf does not use it (netssh's own earlier
binding is refreshed), and the bindings act only in windows marked
@netssh. multi.sync_key and multi.solo_key change the keys or turn them
off (none); also in the configurator. zellij syncs whole tabs only, so
excluding a pane is tmux-only.

testenv: the render test presses the keys through the xterm client
(send-keys -K) and checks [SOLO], that broadcast skips the excluded
pane, that S toggles, and that other windows are unaffected. The client
gets GNU grep: BusyBox grep -oF counted only one match per line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:32:32 +01:00
Sebastian UnterschützandClaude Opus 5.5 699b9469b6 test: check what a real terminal renders for multi, zellij, and the TUI
tests/16-render.sh runs tmux, zellij, and the TUI in xterm on Xvfb,
takes screenshots, and reads them back with tesseract: remote prompts
in all panes, borders and titles with the hosts, [SYNC] appearing and
disappearing, panes side by side, broadcast output in every pane and
input in one pane only without it, windows split by panes_per_window,
the status bar, and TUI marks. Screenshots stay in testenv/.artifacts.

OCR reads three preprocessing variants (plain, stretched for dim gray,
brightest channel for colored text) and normalizes characters that
DejaVu Sans Mono makes ambiguous (1/l, C/().

The screenshots showed tmux cutting the session name in the status bar
to "[netssh-pv"; netssh multi now widens status-left-length for its
own session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:14:34 +01:00
Sebastian UnterschützandClaude Opus 5.5 a31aab4110 feat: netssh multi — several hosts side by side in tmux or zellij
netssh multi opens one pane per host in a tmux window or zellij tab.
Hosts come from names, tag:TAG (NetBox and static hosts), cluster:NAME
(NetBox virtualization clusters; devices by default, --kind vm|all),
and groups from the config (@name, nested, with cycle detection).
Every pane runs netssh HOST, so lookup, rules, and jump hosts apply.

- tmux: a new window inside tmux, else a new session that is attached;
  tiled layout, pane borders with the host and a [SYNC] marker.
- zellij: a generated grid layout; a new tab inside zellij, else a new
  session.
- --sync broadcasts typing to all panes; netssh sync toggles it in the
  current tmux window or zellij tab.
- TUI: Space marks hosts, Ctrl+A marks all, Enter opens them together.
- Configurator: multiplexer, panes per window, groups.

NetBox SearchAll gains a cluster filter (name to cluster IDs per
instance), and cache entries keep the host's cluster for completion
and an offline fallback. Panes skip the 24-hour background refresh
(checked once by multi) and get HOME/XDG paths but no NETSSH_* values,
which would expose tokens in the process list.

testenv/tests/15-multi.sh checks real tmux and zellij sessions,
including a broadcast command arriving on all three cluster nodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:45:05 +01:00
Sebastian UnterschützandClaude Opus 5.5 dbb99bdded test: add a local Docker test environment for all features
testenv/ starts two real NetBox 4.7 instances (v2 and v1 token), SSH
targets on public, mgmt, and prod networks, a jump host, an IPv6-only
host, a static host, and a client with ssh, sftp, scp, tmux, zellij,
bash, zsh, and fish. A seed script fills NetBox through the REST API.

141 end-to-end checks cover cache and refresh filters, connecting,
all resolver strategies, multiple instances, shortcuts and rewrites,
SSH options and rules, static hosts, sftp/scp incl. IPv6 and jump
hosts, tunnels, local notes and NetBox comments, completion and shell
hooks, the TUI (driven through tmux), the configurator, and uninstall.

Local only: testenv/up.sh, test.sh, shell.sh, down.sh. Not part of
CI/CD.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:30:24 +01:00
Sebastian UnterschützandClaude Opus 5.5 55e7a5106b fix: interface_name strategy, instance hosts in sftp/scp, alias rewrites
Found by the new Docker test environment against a real NetBox 4.7:

- The interface_name strategy filtered IP addresses with interface_name
  and vminterface_name, which NetBox ignores, so it returned the first
  address of the host instead of the named interface's. Use the real
  filters interface and vminterface; a missing interface (HTTP 400)
  falls through to the next strategy.
- sftp and scp took instance-qualified hosts (prod/web01:/path) for
  local paths, because a "/" comes before the ":". Such arguments are
  remote when the prefix is a configured NetBox instance.
- Shell aliases of instance-qualified hosts ran the shortcut rules on
  "instance/host", so anchored rewrite rules never matched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:30:24 +01:00
Sebi 3c9e54b254 Merge pull request 'Hostname-Strategie und statische Hosts' (#35) from feat/hostname-static-hosts into main
Release / release (push) Successful in 4m31s
2026-11-13 22:49:14 +00:00
Sebastian UnterschützandClaude Opus 5.5 a950a82552 feat: hostname resolver strategy and static hosts
Add the hostname resolver strategy. It connects by the NetBox name
instead of an IP, with resolver.hostname_domain appended to names
without a dot. Its position in the chain decides whether it is always
used or only as a fallback (e.g. [primary_ip, hostname]); names that
are not valid DNS hostnames fall through to the next strategy.

Add static hosts under hosts: for machines that are not in NetBox,
with address, user, port, tags, and their own SSH options. They are
checked before NetBox (by name or shortcut), never expire, survive
cache refresh and clear, and work without any NetBox configured. The
cache overlays them after every load and stores only their last use,
so they appear in completion, aliases, the TUI and its recent list.
SSH options merge global, static host, then rules; rules can match
kind: static. Manage them with netssh hosts list|add|remove and in
netssh configure, which can now also continue without NetBox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:46:13 +01:00
Sebi 5821dfbebd Merge pull request 'docs: README ausführlicher' (#34) from docs/readme-details into main 2026-11-13 22:31:12 +00:00
Sebastian UnterschützandClaude Opus 5.5 2be9f19cc2 docs: expand README with reference, recipes, and troubleshooting
Add a table of contents, a quick start, a full configuration reference
with defaults, the environment variables, a table of files and
directories, a command overview, details on rule matching and how
option layers combine (with real --dry-run output), recipes, a
troubleshooting table, and the project layout. Update How it works for
sftp, scp, tunnel, and forwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:30:23 +01:00
Sebi c71cc0ae3b Merge pull request 'chore(renovate): keine Major-Updates indirekter Go-Module' (#33) from chore/renovate-no-indirect-major into main 2026-11-13 22:25:28 +00:00
Sebastian UnterschützandClaude Opus 5.5 2cadea30c7 chore(renovate): skip major updates of indirect Go modules
A new major version of a Go module is a separate module path. For an
indirect dependency nothing imports it, so Renovate only adds an unused
requirement, as in #24 (go.yaml.in/yaml/v3 to v4). Minor and patch
updates of indirect modules stay enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:24:31 +01:00
Sebi 25c03fff9d Merge pull request 'chore(deps): update module go.yaml.in/yaml/v3 to v3.0.6' (#23) from renovate/go.yaml.in-yaml-v3-3.x into main 2026-11-13 22:22:23 +00:00
Sebastian Unterschütz 8e4417a6ea Merge remote-tracking branch 'origin/main' into work-23
# Conflicts:
#	go.mod
#	go.sum
2026-11-13 23:21:53 +01:00
Sebi 2fafa0b119 Merge pull request 'chore(deps): update module github.com/xo/terminfo to v1.3.1' (#22) from renovate/github.com-xo-terminfo-1.x into main 2026-11-13 22:21:34 +00:00
Sebastian Unterschütz b009863c37 Merge remote-tracking branch 'origin/main' into work-22 2026-11-13 23:21:03 +01:00
Sebi a1c9210f3c Merge pull request 'chore(deps): update module github.com/spf13/pflag to v1.1.0' (#25) from renovate/github.com-spf13-pflag-1.x into main 2026-11-13 22:20:26 +00:00
Sebastian Unterschütz 15fb57c0ea Merge remote-tracking branch 'origin/main' into work-25 2026-11-13 23:19:44 +01:00
Sebi c55aae520f Merge pull request 'chore(deps): update module golang.org/x/text to v0.44.0' (#29) from renovate/golang.org-x-text-0.x into main 2026-11-13 22:18:52 +00:00
Sebastian Unterschütz 88af34a64b Merge remote-tracking branch 'origin/main' into work-29
# Conflicts:
#	go.sum
2026-11-13 23:18:04 +01:00
Sebi 314905c538 Merge pull request 'fix(deps): update module golang.org/x/sys to v0.50.0' (#27) from renovate/golang.org-x-sys-0.x into main 2026-11-13 22:17:44 +00:00
Sebastian Unterschütz ad3f14186d Merge remote-tracking branch 'origin/main' into work-27 2026-11-13 23:17:15 +01:00
Sebi 4f08a1c92a Merge pull request 'fix(deps): update module charm.land/lipgloss/v2 to v2.1.0' (#28) from renovate/charm.land-lipgloss-v2-2.x into main 2026-11-13 22:16:38 +00:00
Sebastian Unterschütz 45a2abce90 Merge remote-tracking branch 'origin/main' into work-28 2026-11-13 23:16:05 +01:00
Sebi f7fc1b2a37 Merge pull request 'fix(deps): update module charm.land/bubbletea/v2 to v2.1.1' (#21) from renovate/charm.land-bubbletea-v2-2.x into main 2026-11-13 22:15:25 +00:00
Sebastian Unterschütz c45ad9f0d1 Merge remote-tracking branch 'origin/main' into work-21 2026-11-13 23:14:56 +01:00
Sebi 97fc8f5458 Merge pull request 'chore(deps): update go module directive to v1.27.4' (#30) from renovate/go-1.x into main 2026-11-13 22:13:41 +00:00
Sebastian Unterschütz d24870e4c0 Merge remote-tracking branch 'origin/main' into work-30 2026-11-13 23:13:04 +01:00
Sebi 053db984be Merge pull request 'SFTP, SCP und benannte Port-Forwards' (#32) from feat/sftp-forwarding into main 2026-11-13 22:08:48 +00:00
Sebi 6419fbb00d Merge pull request 'v0.0.23: Configurator für alle Optionen, Regex-Kurznamen' (#31) from feat/configure-all-options into main 2026-11-13 22:07:45 +00:00
Sebastian UnterschützandClaude Opus 5.5 b7fa71fe45 feat: sftp, scp, and named port forwards
Add netssh sftp and netssh scp. Both resolve the host like a connection
does (cache, shortcuts and rewrites, instance/host, default user and
port, SSH options and rules, --jump/--no-jump, --dry-run) and get shell
completion. The per-client flag tables handle the differences from ssh:
the port is -P, -l is a bandwidth limit (the default user goes in as
-o User=), and IPv6 addresses are bracketed in host:path. All remote
scp operands must name the same host.

Add named port forwards under ssh.forwards (global, per instance, per
rule; a more specific layer replaces a forward of the same name),
netssh tunnel HOST NAME|SPEC... (ssh -N with ExitOnForwardFailure) and
netssh --forward NAME. Specs such as 8080:localhost:80 work without
configuration. Forwards are editable in netssh configure and completed
in the shell; the TUI opens SFTP with ctrl+o and a tunnel with ctrl+t.

Host resolution moves out of runSSHWrapper into resolveTarget, shared
by ssh, sftp, scp, tunnel, and the TUI.

Options added by netssh are now inserted before the first operand or
"--": after "--", ssh read them as the destination, and scp stops
reading options at the first operand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:05:07 +01:00
Sebastian UnterschützandClaude Opus 5.5 878701aba7 feat(shortcuts): regex rewrite rules for host shortcuts
shortcuts.rewrites applies regex replacements after the domain suffix
is stripped, e.g. ^([a-z]+)[0-9]+- -> $1 turns fsn1-bx1.hoster.de into
fsnbx1. The shortcut works for connecting (cached hosts), shell
aliases, and Tab completion, where it is offered when the full name
does not match the typed text. Rules are editable in netssh configure,
and netssh alias --test HOSTNAME shows a name's shortcut and the cached
hosts it matches.

The shortcut lookup only ran when domains or strip_hyphens were set;
it now also runs for rewrite-only configurations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:42:13 +01:00
Sebastian UnterschützandClaude Opus 5.5 d51c040d9f feat(configure): edit every config option in the configurator
After the NetBox instances, netssh configure now opens a menu with all
sections: SSH defaults, global SSH options (jump host, host key
checking, target, address family, extra args, -o options), SSH rules,
resolver & cache (including the cache file), shortcuts & command alias,
and completion.max_results. SSH options can also be set per instance.

The wizard rebuilt the config from its own fields, so re-running it
dropped global SSH options, ssh.rules and completion.max_results from
the file. It now edits a copy of the loaded config, and save validates
SSH options and rules before writing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:42:13 +01:00
Sebi bbc04723b4 chore(deps): update go module directive to v1.27.4 2026-11-10 17:45:15 +00:00
Sebi 22c9a3c32b chore(deps): update module golang.org/x/text to v0.44.0 2026-11-09 17:46:12 +00:00
Sebi b3f40ac3ad fix(deps): update module charm.land/lipgloss/v2 to v2.1.0 2026-11-09 13:44:02 +00:00
Sebi a80049a7c3 fix(deps): update module golang.org/x/sys to v0.50.0 2026-11-09 12:45:57 +00:00
Sebi 238e3a7798 chore(deps): update module github.com/spf13/pflag to v1.1.0 2026-11-06 08:45:37 +00:00
Sebi 0ce7753a9b chore(deps): update module github.com/xo/terminfo to v1.3.1 2026-11-04 23:43:38 +00:00
Sebi 76e27393dd chore(deps): update module go.yaml.in/yaml/v3 to v3.0.6 2026-10-31 19:51:04 +00:00
Sebi a26e96cd32 fix(deps): update module charm.land/bubbletea/v2 to v2.1.1 2026-10-28 10:54:26 +00:00
Sebi ac713ac97b Merge pull request 'Fix/instance prefix completion' (#20) from fix/instance-prefix-completion into main
Release / release (push) Successful in 5m43s
Reviewed-on: #20
2026-10-28 10:46:29 +00:00
Sebastian UnterschützandClaude Opus 5.5 091f5cc518 fix(completion): offer unique hostnames without instance prefix
bash (and zsh without a matcher) only accept candidates that start with
the typed text, so "fsn1-bx1<Tab>" found nothing when every candidate
was qualified as "prod/…". Hostnames that exist in only one instance
are now offered bare; names present in several instances stay
qualified. Connecting to a bare name still checks every instance for
ambiguity, so the connection behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:44:54 +01:00
Sebastian UnterschützandClaude Opus 5.5 6243514def fix(completion): accept instance-qualified hosts for a bare name in zsh
With several NetBox instances, netssh offers "prod/fsn1-bx1…" for the
typed text "fsn1". compadd discarded these matches because they do not
start with the typed word, so <Tab> found nothing. The matcher
'l:|=*' lets zsh accept text before the typed word; netssh has already
filtered the candidates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:44:54 +01:00
Sebi 6f00d69b6f Merge pull request 'v0.0.21' (#19) from feat/ssh-options-completion-uninstall into main
Release / release (push) Successful in 5m45s
Reviewed-on: #19
2026-10-28 10:25:20 +00:00
Sebastian UnterschützandClaude Opus 5.5 6711b610f1 docs: document SSH options, uninstall, and zsh completion for v0.0.21
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:23:31 +01:00
Sebastian UnterschützandClaude Opus 5.5 c2e590bf52 feat: add netssh uninstall
Remove everything netssh and install.sh set up, also leftovers of
older versions:

- netssh blocks and unmarked legacy lines in bash, zsh, and fish
  profiles
- completion files for bash, zsh (incl. the oh-my-zsh cache), fish,
  and the command alias; files not generated by netssh are kept
- the cache directory with hosts, aliases, and per-instance caches
- the config file and local notes; the config is first copied to a
  private netssh.yaml.backup-<timestamp> because it holds API tokens
- the netssh binary; for protected paths the sudo command is printed

--keep-config keeps config and notes, --dry-run only lists the plan,
and --yes skips the confirmation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:23:28 +01:00
Sebastian UnterschützandClaude Opus 5.5 786768ec53 feat: add netssh version and --version
`netssh --version` used to be passed to ssh and failed with
"unknown option -- -". Release builds now embed the tag via
-X main.version; other builds fall back to the module build info.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:23:19 +01:00
Sebastian UnterschützandClaude Opus 5.5 2b46c4f74d feat(ssh): jump hosts, host key checking, and configurable ssh options
Add SSH settings that apply only to netssh connections, so
~/.ssh/config does not need global changes:

- proxy_jump (passed as -J; "none" disables an inherited jump host)
- host_key_checking: strict | accept-new | off (off prints a notice)
- target: ip (default) | name | hostname; "name" connects to the
  NetBox name with -o HostName=<ip> and -o HostKeyAlias=<name>, so
  `Host *.example.com` rules apply and known_hosts entries follow the
  device instead of a reused IP
- address_family: any | inet | inet6
- options (-o Key=Value) and extra_args

Settings layer global -> netboxes[].ssh -> ssh.rules (match by tag,
instance, kind, or name glob). Options given on the command line
always win: -o values are inserted after the user's own, and
extra_args before them.

New wrapper flags: --jump HOST, --no-jump, and --dry-run, which prints
the final ssh command instead of connecting. The TUI uses the same
options. The setup wizard keeps all new settings when it saves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:23:09 +01:00
Sebastian UnterschützandClaude Opus 5.5 129a7201bc feat(hook): write marked profile blocks and register zsh completion
`netssh hook install` and the setup wizard now write the same marked
`# >>> netssh >>>` block as install.sh and replace unmarked entries of
older versions instead of appending duplicates. Uninstall shares the
legacy patterns with the installer (eval/alias/source variants).

For zsh the block adds ~/.zfunc to fpath and calls compdef, so
completion also works when compinit already ran earlier in .zshrc,
e.g. with oh-my-zsh. The installer reports which completion it set up
per shell and how to reset ~/.zcompdump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:22:53 +01:00
Sebastian UnterschützandClaude Opus 5.5 8fb7633783 feat(completion): fast zsh completion for large host caches
Cobra's generated zsh script spawns a subshell per candidate and sends
every host through _describe, so <Tab> hangs for seconds with thousands
of cached hosts. netssh now ships its own script: subcommands and flags
go through _describe, plain hostnames through compadd. 5000 hosts
complete in ~0.08 s instead of ~4 s.

Add completion.max_results to cap the number of offered hostnames and
sort host candidates for a stable order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:22:18 +01:00
Sebastian Unterschütz 7f53b90266 feat: search multiple NetBox instances with isolated host identities
Release / release (push) Successful in 5m16s
2026-10-27 23:14:42 +01:00
Sebastian Unterschütz a2a6dd7591 chore(deps): update github.com/charmbracelet/ultraviolet digest to a45b7c8
Release / release (push) Successful in 5m7s
2026-10-27 22:44:00 +01:00
Sebastian Unterschütz 79c0027833 fix(deps): migrate Charm to v2 and require Go 1.27.3
Release / release (push) Successful in 6m16s
2026-10-27 22:29:54 +01:00
Sebastian Unterschütz fa7446e5f7 Fix host resolution and concurrent cache updates 2026-10-27 22:23:59 +01:00
Sebastian Unterschütz 92b1c40cb8 Update Go module dependencies
Release / release (push) Successful in 4m46s
2026-10-27 19:25:37 +01:00
Sebastian Unterschütz 34503de68e Enable shell completion for configured command aliases
Release / release (push) Successful in 5m8s
2026-10-27 19:19:42 +01:00
Sebastian Unterschütz 14d519d010 Use public Gitea URL for releases and download links
Release / release (push) Successful in 5m37s
2026-10-27 18:46:38 +01:00
Sebastian Unterschütz fa4509038b Package installer in releases and expand Renovate dependency updates
Release / release (push) Successful in 4m41s
2026-10-27 18:38:54 +01:00
Sebastian Unterschütz 66a49786c9 Translate remaining German text to English
Release / release (push) Successful in 5m32s
2026-10-27 18:27:21 +01:00
Sebastian Unterschütz 4b28d441b0 Improve installer updates and dependency checks and add command aliases
Release / release (push) Successful in 7m57s
2026-10-27 18:10:44 +01:00
Sebastian Unterschütz 12cc64fdd9 Add local and NetBox server notes and improve reliability
Release / release (push) Successful in 6m52s
2026-10-27 17:51:59 +01:00
Sebi 2852dff2c4 Merge pull request 'chore(deps): update actions/setup-go action to v7' (#3) from renovate/actions-setup-go-7.x into main 2026-10-11 17:15:15 +00:00
Sebi 2d11303014 Merge pull request 'chore(deps): update actions/checkout action to v7' (#2) from renovate/actions-checkout-7.x into main 2026-10-11 17:13:57 +00:00
Sebi 5c6cc7dbbf chore(deps): update actions/setup-go action to v7 2026-10-11 16:30:19 +00:00
Sebi b17ace7fc5 chore(deps): update actions/checkout action to v7 2026-10-11 16:29:56 +00:00
Sebi 8241a064f4 Merge pull request 'chore: Configure Renovate' (#1) from renovate/configure into main 2026-10-11 16:12:43 +00:00
Sebi 86fc2f19eb Add renovate.json 2026-10-11 15:45:13 +00:00
Sebastian Unterschütz fa646f25a6 feat: add alias file generation and management for shell hooks
Release / release (push) Successful in 49s
- **Aliases**: Generate shell alias files (`aliases.sh` for bash/zsh, `netssh.fish` for fish) from cached hosts. Regenerate on each shell startup and cache refresh to keep aliases updated.
- **Hooks**: Extend shell hook functionality to include alias file support. Install and uninstall commands updated for bash, zsh, and fish.
- **Tests**: Add unit tests to verify alias file generation, path resolution, and idempotent hook installation.
- **Docs**: Update README with instructions for alias file usage, installation, and relation to hooks.
2026-05-27 23:08:30 +02:00
Sebastian Unterschütz 7c902cab3a feat: introduce shortcuts and shell hook support
Release / release (push) Successful in 50s
- **Shortcuts**: Add hostname normalization with domain stripping and hyphen folding. Include alias generation for cached hosts.
- **Shell Hook**: Automate 24h cache refresh trigger with shell startup hook. Add install/uninstall commands for bash, zsh, and fish.
- **Wizard**: Extend setup wizard to configure shortcuts (domains, hyphen stripping) and default SSH port.
- **Cache**: Add `GetByShortcut` for resolving hosts via normalized shortcuts. Implement `NeedsRefresh` / `SetRefreshed` logic for refresh timestamps.
- **Tests**: Comprehensive unit tests for shortcuts, hook installation, cache refresh, and alias generation.
- **Docs**: Update README with shortcuts, shell hook, and default SSH port configuration.
2026-05-27 22:53:24 +02:00
Sebastian Unterschütz d127a3b957 feat: enhance host resolution, filtering, and cache management
Release / release (push) Successful in 49s
- **Strategies**: Add resolver strategy input validation and parsing in setup wizard. Support comma-separated input with known strategy mapping.
- **Client**: Extend Search and SearchAll to include kind and tag filters. Add pagination for full cache refresh handling large datasets.
- **Cache**: Introduce `RecentlyUsed` and `MarkUsed`. Persist `LastUsed` timestamps for entries.
- **TUI**: Add recent hosts view, tag/kind filters, and inline editor for user/port override.
- **Tests**: Comprehensive unit tests for new features, including strategy validation, cache behavior, and client filtering.
- **Docs**: Update README with new TUI features and cache subcommands.
2026-05-23 17:06:24 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 cdf750081e feat: show subcommands after hostnames in shell completion
Release / release (push) Successful in 48s
Use ShellCompDirectiveKeepOrder so fish/zsh/bash preserve the returned
order instead of sorting alphabetically. ValidArgsFunction now appends
subcommand names (with their short descriptions) after all hostname
entries, so hosts always appear first in the completion list.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 14:42:41 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 574c4dbf58 fix: completion install writes non-empty scripts
Release / release (push) Successful in 47s
GenBashCompletionV2/GenZshCompletion/GenFishCompletion write into the
buffer as a side effect; capturing buf.String() in the return statement
before the Gen* call runs means the buffer is always empty. Separate
the call from the return to fix evaluation order.

Also call InitDefaultCompletionCmd() before iterating root.Commands()
so the lazily-initialized completion subtree is visible before Execute().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 13:50:53 +02:00
Sebastian Unterschütz 8fc7896b35 docs: update README for wizard, token versions, completion install
Release / release (push) Successful in 46s
2026-05-23 13:31:08 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 da3a280a43 feat: netssh completion install — user-space shell completion setup
Adds `netssh completion install` subcommand:
- Auto-detects shell from $SHELL, override with --shell bash|zsh|fish
- bash  → ~/.local/share/bash-completion/completions/netssh
- zsh   → ~/.zfunc/_netssh  (prints fpath hint)
- fish  → ~/.config/fish/completions/netssh.fish
- No sudo required

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 13:28:43 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 a4fa33d224 feat: v2 token support in client + comprehensive tests
Release / release (push) Successful in 51s
API client:
- NewClient now accepts tokenVersion (0 = auto-detect from token prefix)
- tokenVersion stored on Client, used for 403 error hints
- All callers pass cfg.NetBox.TokenVersion

Tests added:
- netbox: TokenVersion, NewClient auto-detect, explicit version,
  403 v1 hint, 403 v2 no-hint, Authorization header verification
- config: token_version preserved/auto-detected, defaults, missing
  file, invalid YAML, Path()
- setup: save roundtrip, file permissions (0600), empty fields
  omitted, dir creation, full save→load roundtrip

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 13:17:34 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 8ae28b3474 feat: persist token_version in config, auto-detect on load
- NetBoxConfig.TokenVersion saved to netssh.yaml by the wizard
- config.Load() auto-detects the version from the token prefix if the
  field is missing (backwards-compatible with existing configs)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 13:12:35 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 9334003c9e feat: detect NetBox token version, hint on v1, better 403 message
- TokenVersion() distinguishes nbt_-prefixed v2 tokens from legacy v1
- 403 errors now say "check token permissions" + v1 hint if applicable
- Setup wizard prints a note after saving if a v1 token was entered

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 13:11:01 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 ff9c61c087 feat: interactive setup wizard for first-run and netssh configure
Release / release (push) Successful in 1m36s
- Auto-detects missing config (netbox.url empty) and launches wizard
- `netssh configure` re-runs the wizard anytime to change settings
- 3-page huh form: NetBox connection, SSH defaults, resolver & cache
- Saves to ~/.config/netssh.yaml (permissions 0600)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 13:04:55 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 11f5319eae ci: delete existing release before recreating on retrigger
Release / release (push) Successful in 1m32s
Prevents curl exit 22 (HTTP 409) when a tag's release already exists.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 12:56:50 +02:00
Sebastian UnterschützandClaude Sonnet 4.6 d178f8b053 fix: add cmd/netssh to git and fix overly broad gitignore rule
Release / release (push) Failing after 1m0s
/netssh ignores only the root binary, not the cmd/netssh/ source directory.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-23 12:52:09 +02:00
Sebastian Unterschütz 8ef4bbec16 Add core modules (SSH args parser, cache, resolver, NetBox client) with tests
Release / release (push) Failing after 51s
2026-05-23 12:38:41 +02:00
32 changed files with 54 additions and 1641 deletions

No files matched your search

-13
View File
@@ -1,18 +1,5 @@
# Changelog # Changelog
## 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 ## 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: `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.
+24 -320
View File
@@ -21,9 +21,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [Installation](#installation) - [Installation](#installation)
- [Quick start](#quick-start) - [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) - [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) - [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)
- [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) - [Recipes](#recipes)
- [IP Resolution Strategies](#ip-resolution-strategies) - [IP Resolution Strategies](#ip-resolution-strategies)
- [Shell Completion](#shell-completion) and [Shell Hook](#shell-hook) - [Shell Completion](#shell-completion) and [Shell Hook](#shell-hook)
@@ -149,12 +147,12 @@ A menu then gives access to every other setting; open only the sections you want
| Section | Settings | | Section | Settings |
|---|---| |---|---|
| SSH defaults | `ssh.default_user`, `ssh.default_port` | | SSH defaults | `ssh.default_user`, `ssh.default_port` |
| SSH options | `proxy_jump`, `host_key_checking`, `target`, `address_family`, `extra_args` (one per line), `options` (`Key=Value` per line), `forwards` (`NAME L\|R\|D SPEC` per line), `pre_connect` | | SSH 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 rules | add, edit, remove `ssh.rules` — match by tag, instance, kind, name pattern, each with its own SSH options | | 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 | | 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) | | 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 | | Resolver & cache | strategies, management subnets, interface name, hostname domain, cache TTL, cache file |
| Shortcuts & command alias | domain suffixes, hyphen stripping, rewrite rules (`REGEX => REPLACEMENT` per line), show shortcuts (`shortcuts.show`), `shell.alias` | | Shortcuts & command alias | domain suffixes, hyphen stripping, rewrite rules (`REGEX => REPLACEMENT` per line), `shell.alias` |
| Completion | `completion.max_results` | | Completion | `completion.max_results` |
The result is validated and saved to `~/.config/netssh.yaml`; Ctrl+C cancels without writing. The result is validated and saved to `~/.config/netssh.yaml`; Ctrl+C cancels without writing.
@@ -213,7 +211,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.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` | string | — | API token; `nbt_…` is v2, anything else v1. |
| `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. | | `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. |
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `disable_prefix`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). | | `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `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.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.management_subnets` | list of CIDR | `[]` | Used by `management_subnet`. |
| `resolver.interface_name` | string | — | Used by `interface_name`, e.g. `mgmt0`. | | `resolver.interface_name` | string | — | Used by `interface_name`, e.g. `mgmt0`. |
@@ -229,16 +227,13 @@ 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.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.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.forwards` | map | `{}` | *Layered.* Named port forwards (`local`, `remote`, `dynamic`) — see [Port forwarding](#port-forwarding). |
| `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. | | `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.domains` | list | `[]` | Suffixes stripped for shortcuts and tried when expanding a short name. |
| `shortcuts.strip_hyphens` | bool | `false` | Ignore hyphens when matching shortcuts. | | `shortcuts.strip_hyphens` | bool | `false` | Ignore hyphens when matching shortcuts. |
| `shortcuts.rewrites[]` | list | `[]` | `pattern` (Go regex) and `replace` — see [Host shortcuts](#host-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. | | `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). | | `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). | | `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. | | `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.multiplexer` | `auto` \| `tmux` \| `zellij` | `auto` | Which multiplexer `netssh multi` uses. |
| `multi.panes_per_window` | int | `9` | More hosts open in further tmux windows or zellij tabs. | | `multi.panes_per_window` | int | `9` | More hosts open in further tmux windows or zellij tabs. |
@@ -254,8 +249,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_RESOLVER_STRATEGIES`, `NETSSH_RESOLVER_MANAGEMENT_SUBNETS`, `NETSSH_RESOLVER_INTERFACE_NAME`, `NETSSH_RESOLVER_HOSTNAME_DOMAIN` | `resolver.*` |
| `NETSSH_CACHE_TTL`, `NETSSH_CACHE_PATH` | `cache.*` | | `NETSSH_CACHE_TTL`, `NETSSH_CACHE_PATH` | `cache.*` |
| `NETSSH_SSH_DEFAULT_USER`, `NETSSH_SSH_DEFAULT_PORT` | `ssh.default_*` | | `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`, `NETSSH_SSH_PRE_CONNECT` | global `ssh.*` options | | `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`, `NETSSH_SHORTCUTS_SHOW` | `shortcuts.*` | | `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS` | `shortcuts.*` |
| `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` | | `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` |
| `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` | | `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` |
| `NETSSH_SHELL_ALIAS` | `shell.alias` | | `NETSSH_SHELL_ALIAS` | `shell.alias` |
@@ -310,41 +305,7 @@ 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. For direct connections without an instance prefix, every instance must be reachable to verify uniqueness. A qualified target queries only its own instance and can use a fresh cached IP while other instances are offline. Qualified shortcuts such as `office/web01` also support configured domain suffixes and hyphen folding.
Cache entries retain the instance name. Generated aliases include it by default (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed. 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.
**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. 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.
@@ -403,7 +364,6 @@ 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 [--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 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 scp [netssh flags] [scp options] SOURCE... TARGET` | Copy files — see [SFTP and SCP](#sftp-and-scp). |
| `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 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 hosts [list] \| add NAME ADDRESS [--user U] [--port P] [--tag T]... [--replace] \| remove NAME` | Manage static hosts — see [Static hosts](#static-hosts). |
| `netssh multi [--sync] [--kind K] [--tmux\|--zellij] [-l U] [--jump H\|--no-jump] HOST\|tag:T\|cluster:C\|@GROUP...` | Several hosts side by side — see [Multiple servers](#multiple-servers-in-one-window). | | `netssh 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). |
@@ -513,7 +473,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: **How layers combine.** netssh merges global → instance (or the static host's own `ssh`) → matching rules:
- single values (`proxy_jump`, `host_key_checking`, `target`, `address_family`, `pre_connect`) — the most specific non-empty value wins; - single values (`proxy_jump`, `host_key_checking`, `target`, `address_family`) — the most specific non-empty value wins;
- `options` and `forwards` — merged per key or name, the more specific layer wins; - `options` and `forwards` — merged per key or name, the more specific layer wins;
- `extra_args` — collected from all layers. - `extra_args` — collected from all layers.
@@ -524,46 +484,6 @@ $ 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 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 ### 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`. `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`.
@@ -677,9 +597,7 @@ multi:
| Exclude one pane | `Ctrl+b e` (again: include) or `netssh sync --pane` | not possible — zellij syncs whole tabs | | 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 | | Shown in the border | `[SYNC]` receives broadcast, `[SOLO]` excluded | `(SYNC)` in the tab name |
**Keys in tmux.** The active pane border keeps the available broadcast/solo keys visible after attaching. See the [hotkey cheat sheet](#hotkey-cheat-sheet) for navigation and editor keys. **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`.
`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. **In the TUI**, mark hosts with `Space` (or all listed hosts with `Ctrl+A`) and press `Enter` to open them together.
@@ -753,27 +671,6 @@ 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) | | `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) | | `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 ### Shell aliases
Generate shell aliases for all cached hosts based on the shortcut settings: Generate shell aliases for all cached hosts based on the shortcut settings:
@@ -807,118 +704,6 @@ 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. 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 ### Interactive TUI
Run without arguments to open the interactive search: Run without arguments to open the interactive search:
@@ -929,7 +714,21 @@ 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 10 most-recently-connected hosts. 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. | 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) |
**Tag and kind filter** — press `Ctrl+F` to open a second input line: **Tag and kind filter** — press `Ctrl+F` to open a second input line:
@@ -986,7 +785,6 @@ See the [NetBox REST API documentation](https://netbox.readthedocs.io/en/stable/
```sh ```sh
netssh cache list # show all cached entries 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 # re-fetch ALL hosts from NetBox (paginated)
netssh cache refresh --tag prod # only hosts with the "prod" tag netssh cache refresh --tag prod # only hosts with the "prod" tag
netssh cache refresh --kind vm # only virtual machines netssh cache refresh --kind vm # only virtual machines
@@ -1019,100 +817,6 @@ 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 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+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.
## Recipes ## Recipes
**Everything through a bastion, except the bastion itself** **Everything through a bastion, except the bastion itself**
+4 -25
View File
@@ -14,32 +14,27 @@ import (
) )
func hostsCmd() *cobra.Command { func hostsCmd() *cobra.Command {
var showAliases bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "hosts", Use: "hosts",
Short: "Manage static hosts that are not in NetBox", Short: "Manage static hosts that are not in NetBox",
Long: `Static hosts are defined under hosts: in the config. They are found before Long: `Static hosts are defined under hosts: in the config. They are found before
NetBox, work offline, and support shortcuts, rules (kind: static), aliases, NetBox, work offline, and support shortcuts, rules (kind: static), aliases,
completion, sftp, scp, and tunnels like NetBox hosts.`, completion, sftp, scp, and tunnels like NetBox hosts.`,
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) }, RunE: func(cmd *cobra.Command, args []string) error { return listHosts() },
} }
cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd()) cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd())
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd return cmd
} }
func hostsListCmd() *cobra.Command { func hostsListCmd() *cobra.Command {
var showAliases bool return &cobra.Command{
cmd := &cobra.Command{
Use: "list", Use: "list",
Short: "List static hosts", Short: "List static hosts",
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) }, RunE: func(cmd *cobra.Command, args []string) error { return listHosts() },
} }
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
} }
func listHosts(showAliases bool) error { func listHosts() error {
cfg, err := config.Load() cfg, err := config.Load()
if err != nil { if err != nil {
return err return err
@@ -48,29 +43,13 @@ func listHosts(showAliases bool) error {
fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS") fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS")
return nil 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) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
if withAliases {
fmt.Fprintln(w, "NAME\tALIAS\tADDRESS\tUSER\tPORT\tTAGS")
} else {
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS") fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
}
for _, host := range cfg.Hosts { for _, host := range cfg.Hosts {
port := "" port := ""
if host.Port > 0 { if host.Port > 0 {
port = fmt.Sprint(host.Port) 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, ",")) 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() return w.Flush()
+1 -40
View File
@@ -6,7 +6,6 @@ import (
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "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/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/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts"
) )
@@ -30,28 +29,6 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion) 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 == "" {
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 { func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) string {
return func(target string) string { return func(target string) string {
source, name := netbox.SplitTarget(target) source, name := netbox.SplitTarget(target)
@@ -71,9 +48,6 @@ func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) st
// Names present in several instances stay qualified ("prod/web01"). // Names present in several instances stay qualified ("prod/web01").
// Hosts whose full name does not match are offered by their configured // Hosts whose full name does not match are offered by their configured
// shortcut instead ("fsnb" → "fsnbx1" for fsn1-bx1.example.com). // 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 { func hostCompletions(entries []cache.Entry, toComplete string, sc config.ShortcutsConfig) []string {
prefix := strings.ToLower(toComplete) prefix := strings.ToLower(toComplete)
qualifiedInput := strings.Contains(prefix, "/") qualifiedInput := strings.Contains(prefix, "/")
@@ -101,20 +75,7 @@ func hostCompletions(entries []cache.Entry, toComplete string, sc config.Shortcu
} }
} }
if sc.Enabled() { if sc.Enabled() {
candidates := unmatched names = append(names, shortcutCompletions(entries, unmatched, prefix, sc)...)
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) sort.Strings(names)
return names return names
+2 -30
View File
@@ -48,7 +48,6 @@ var managedSubcommands = map[string]bool{
"hosts": true, "hosts": true,
"multi": true, "multi": true,
"sync": true, "sync": true,
"run": true,
} }
func main() { func main() {
@@ -349,9 +348,6 @@ 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) 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) _, name := netbox.SplitTarget(host.Name)
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags) execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags)
} }
@@ -390,11 +386,6 @@ func runTUI() {
} }
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort) m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
m.SetHostLabel(cfg.HostLabel)
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.SetNotes(notes.New(cfg.NetBox.URL, nbClient))
m.SetForwards(func(name, kind string, tags []string) []string { m.SetForwards(func(name, kind string, tags []string) []string {
return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags})) return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags}))
@@ -529,7 +520,7 @@ func rootCmd() *cobra.Command {
}, },
} }
root.AddCommand(runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd()) root.AddCommand(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. // cobra builds the "completion" command lazily; force init so we can extend it.
root.InitDefaultCompletionCmd() root.InitDefaultCompletionCmd()
@@ -677,8 +668,7 @@ func cacheCmd() *cobra.Command {
} }
func cacheListCmd() *cobra.Command { func cacheListCmd() *cobra.Command {
var showAliases bool return &cobra.Command{
cmd := &cobra.Command{
Use: "list", Use: "list",
Short: "Show all cached entries", Short: "Show all cached entries",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
@@ -694,31 +684,13 @@ func cacheListCmd() *cobra.Command {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
if !showAliases && !cfg.Shortcuts.Show {
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT") fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT")
for _, e := range entries { 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\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
} }
return w.Flush() 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\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 { func cacheClearCmd() *cobra.Command {
-54
View File
@@ -1,54 +0,0 @@
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
@@ -1,112 +0,0 @@
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)
}
}
-83
View File
@@ -1,83 +0,0 @@
package main
import (
"fmt"
"os"
"os/exec"
"sort"
"strings"
"syscall"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"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 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 := resolveTarget(cfg, args[1])
argv := expandHostCommand(command, host, args[2:])
if dryRun {
for i, arg := range argv {
if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ")
}
fmt.Fprintf(cmd.OutOrStdout(), "%q", arg)
}
fmt.Fprintln(cmd.OutOrStdout())
return nil
}
path, err := exec.LookPath(argv[0])
if err != nil {
return fmt.Errorf("%s not found in PATH: %w", argv[0], err)
}
return syscall.Exec(path, argv, os.Environ())
},
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(&dryRun, "dry-run", false, "Print the command without running it")
return cmd
}
-130
View File
@@ -1,130 +0,0 @@
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)
}
})
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ require (
charm.land/bubbles/v2 v2.2.1 charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.1 charm.land/bubbletea/v2 v2.1.1
charm.land/huh/v2 v2.0.3 charm.land/huh/v2 v2.0.3
charm.land/lipgloss/v2 v2.1.1 charm.land/lipgloss/v2 v2.1.0
github.com/spf13/cobra v1.10.2 github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0 github.com/spf13/viper v1.21.0
golang.org/x/sys v0.50.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/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 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc= charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc= charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU=
charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc= charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
-54
View File
@@ -1,54 +0,0 @@
package config
import (
"fmt"
"regexp"
"strings"
)
// HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct {
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 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
@@ -1,37 +0,0 @@
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")
}
}
+1 -9
View File
@@ -11,7 +11,6 @@ import (
) )
type Config struct { type Config struct {
Commands map[string]HostCommand `mapstructure:"commands"`
Shell ShellConfig `mapstructure:"shell"` Shell ShellConfig `mapstructure:"shell"`
NetBox NetBoxConfig `mapstructure:"netbox"` NetBox NetBoxConfig `mapstructure:"netbox"`
NetBoxes []NetBoxConfig `mapstructure:"netboxes"` NetBoxes []NetBoxConfig `mapstructure:"netboxes"`
@@ -31,7 +30,6 @@ type ShellConfig struct {
} }
type NetBoxConfig struct { type NetBoxConfig struct {
DisablePrefix bool `mapstructure:"disable_prefix"`
Name string `mapstructure:"name"` Name string `mapstructure:"name"`
URL string `mapstructure:"url"` URL string `mapstructure:"url"`
Token string `mapstructure:"token"` Token string `mapstructure:"token"`
@@ -68,9 +66,6 @@ type ShortcutsConfig struct {
Domains []string `mapstructure:"domains"` Domains []string `mapstructure:"domains"`
StripHyphens bool `mapstructure:"strip_hyphens"` StripHyphens bool `mapstructure:"strip_hyphens"`
Rewrites []ShortcutRewrite `mapstructure:"rewrites"` 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 // ShortcutRewrite replaces every match of Pattern (Go regexp syntax) with
@@ -126,7 +121,7 @@ func Load() (*Config, error) {
v.SetEnvPrefix("NETSSH") v.SetEnvPrefix("NETSSH")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv() 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", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "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", "shell.alias", "ssh.proxy_jump", "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 { if err := v.BindEnv(key); err != nil {
return nil, err return nil, err
} }
@@ -172,9 +167,6 @@ func Load() (*Config, error) {
if err := cfg.ValidateHosts(); err != nil { if err := cfg.ValidateHosts(); err != nil {
return nil, err return nil, err
} }
if err := cfg.ValidateCommands(); err != nil {
return nil, err
}
if err := cfg.ValidateMulti(); err != nil { if err := cfg.ValidateMulti(); err != nil {
return nil, err return nil, err
} }
-14
View File
@@ -65,17 +65,3 @@ func (c *Config) CachePath() string {
sum := sha256.Sum256([]byte(strings.Join(identities, "\x00"))) 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)) 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,7 +15,6 @@ func TestLoadNamedNetBoxes(t *testing.T) {
- name: Office - name: Office
url: https://office.example/netbox url: https://office.example/netbox
token: nbt_office token: nbt_office
disable_prefix: true
- name: lab - name: lab
url: https://lab.example url: https://lab.example
token: legacy-token token: legacy-token
@@ -35,14 +34,7 @@ cache:
if cfg.NetBox.URL != "" { if cfg.NetBox.URL != "" {
t.Fatal("legacy environment variables added an unnamed instance") 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() first := cfg.CachePath()
cfg.NetBoxes[0].DisablePrefix = false
if cfg.CachePath() != first {
t.Fatal("alias prefix setting discarded cache")
}
if first == cfg.Cache.Path { if first == cfg.Cache.Path {
t.Fatal("named sources reuse legacy cache") t.Fatal("named sources reuse legacy cache")
} }
-21
View File
@@ -24,21 +24,6 @@ type SSHOptions struct {
Options map[string]string `mapstructure:"options"` Options map[string]string `mapstructure:"options"`
// Forwards are named port forwards, selected with --forward or netssh tunnel. // Forwards are named port forwards, selected with --forward or netssh tunnel.
Forwards map[string]Forward `mapstructure:"forwards"` 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"`
}
// 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. // Forward is one port forward; exactly one of the fields is set.
@@ -170,9 +155,6 @@ func (o SSHOptions) Validate(scope string) error {
return fmt.Errorf("%s.options: invalid option %q", scope, key) return fmt.Errorf("%s.options: invalid option %q", scope, key)
} }
} }
if strings.ContainsRune(o.PreConnect, 0) {
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
}
for name, forward := range o.Forwards { for name, forward := range o.Forwards {
if !instanceName.MatchString(name) { if !instanceName.MatchString(name) {
return fmt.Errorf("%s.forwards: name %q must contain only letters, digits, underscores, or hyphens", scope, name) return fmt.Errorf("%s.forwards: name %q must contain only letters, digits, underscores, or hyphens", scope, name)
@@ -239,9 +221,6 @@ func (o SSHOptions) merge(override SSHOptions) SSHOptions {
if override.AddressFamily != "" { if override.AddressFamily != "" {
out.AddressFamily = override.AddressFamily out.AddressFamily = override.AddressFamily
} }
if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect
}
return out return out
} }
-47
View File
@@ -210,50 +210,3 @@ 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)
}
}
+3 -64
View File
@@ -16,7 +16,6 @@ import (
// AliasEntry holds a single shell alias mapping. // AliasEntry holds a single shell alias mapping.
type AliasEntry struct { type AliasEntry struct {
Command string // configured host command; empty means the default SSH alias
Name string // short alias name (e.g. "web01") Name string // short alias name (e.g. "web01")
Host string // canonical NetBox hostname (e.g. "web01.example.com") Host string // canonical NetBox hostname (e.g. "web01.example.com")
} }
@@ -52,7 +51,7 @@ func WriteAliasFiles(entries []AliasEntry) error {
writeFishAliasFile(entries) // best-effort — never blocks the caller on failure writeFishAliasFile(entries) // best-effort — never blocks the caller on failure
alias := "" alias := ""
for _, entry := range entries { for _, entry := range entries {
if entry.Host == "" && entry.Command == "" { if entry.Host == "" {
alias = entry.Name alias = entry.Name
break break
} }
@@ -95,9 +94,6 @@ func writeFishAliasFile(entries []AliasEntry) {
// Empty Host represents an alias for the netssh command itself. // Empty Host represents an alias for the netssh command itself.
func (e AliasEntry) Definition(shell string) string { func (e AliasEntry) Definition(shell string) string {
command := "netssh" command := "netssh"
if e.Command != "" {
command += " run " + shellQuote(e.Command, shell) + " --"
}
if e.Host != "" { if e.Host != "" {
host := e.Host host := e.Host
if !regexp.MustCompile(`^[a-zA-Z0-9_.:-]+$`).MatchString(host) { if !regexp.MustCompile(`^[a-zA-Z0-9_.:-]+$`).MatchString(host) {
@@ -128,71 +124,14 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
seen[cfg.Shell.Alias] = true seen[cfg.Shell.Alias] = true
out = append(out, AliasEntry{Name: cfg.Shell.Alias}) 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) name := shortcuts.AliasName(e.Name, cfg.Shortcuts)
canonical[name] = true if seen[name] || name == "" || !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`).MatchString(name) {
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 continue
} }
seen[name] = true seen[name] = true
out = append(out, AliasEntry{Name: name, Host: e.Name}) 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...)
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
}
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 return out
} }
-163
View File
@@ -2,7 +2,6 @@ package hook_test
import ( import (
"os" "os"
"os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@@ -254,165 +253,3 @@ func TestAliasesUseRewriteRules(t *testing.T) {
t.Fatalf("entries: %+v", entries) 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)
}
})
}
}
+1 -37
View File
@@ -18,7 +18,6 @@ type fake struct {
syncState string syncState string
keys map[string]string // existing prefix bindings by key keys map[string]string // existing prefix bindings by key
solo string solo string
prefix string
n int n int
} }
@@ -34,8 +33,6 @@ func (f *fake) Output(argv ...string) (string, error) {
f.calls = append(f.calls, strings.Join(argv, " ")) f.calls = append(f.calls, strings.Join(argv, " "))
f.n++ f.n++
switch argv[1] { switch argv[1] {
case "show-options":
return f.prefix, nil
case "new-window", "new-session": case "new-window", "new-session":
return fmt.Sprintf("@%d %%%d", f.n, f.n), nil return fmt.Sprintf("@%d %%%d", f.n, f.n), nil
case "split-window": case "split-window":
@@ -124,8 +121,6 @@ func TestTmuxInside(t *testing.T) {
"tmux list-keys -T prefix S", "tmux list-keys -T prefix S",
"tmux list-keys -T prefix e", "tmux list-keys -T prefix e",
"tmux source-file /tmp/l/netssh-multi.tmux.conf", "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", "tmux select-window -t @1",
} }
if strings.Join(f.calls, "\n") != strings.Join(want, "\n") { if strings.Join(f.calls, "\n") != strings.Join(want, "\n") {
@@ -239,7 +234,7 @@ func TestTmuxKeyBindings(t *testing.T) {
t.Errorf("conf lacks %q:\n%s", want, conf) t.Errorf("conf lacks %q:\n%s", want, conf)
} }
} }
if hint != "keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off" { if hint != "keys: C-b S broadcast to all panes, C-b e exclude/include this pane" {
t.Errorf("hint %q", hint) t.Errorf("hint %q", hint)
} }
@@ -284,34 +279,3 @@ func TestToggleSyncPane(t *testing.T) {
t.Fatalf("zellij: %v", err) 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)
}
})
}
}
+4 -23
View File
@@ -27,7 +27,6 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
} }
groups := chunks(panes, opts.PerWindow) groups := chunks(panes, opts.PerWindow)
first := "" first := ""
var windows []string
for i, group := range groups { for i, group := range groups {
name := windowLabel(opts.Label, i, len(groups)) name := windowLabel(opts.Label, i, len(groups))
format := []string{"-P", "-F", "#{window_id} #{pane_id}", "-n", name} format := []string{"-P", "-F", "#{window_id} #{pane_id}", "-n", name}
@@ -53,7 +52,6 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
} }
} }
window, pane, _ := strings.Cut(out, " ") window, pane, _ := strings.Cut(out, " ")
windows = append(windows, window)
if first == "" { if first == "" {
first = window first = window
} }
@@ -93,17 +91,6 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
} }
if keys != "" { if keys != "" {
opts.Hint(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 { if inside {
_, err := r.Output("tmux", "select-window", "-t", first) _, err := r.Output("tmux", "select-window", "-t", first)
@@ -162,8 +149,8 @@ func bindKeys(r Runner, opts Options) (string, error) {
var conf strings.Builder var conf strings.Builder
var hints, taken []string var hints, taken []string
for _, key := range []struct{ key, binding, what string }{ for _, key := range []struct{ key, binding, what string }{
{opts.SyncKey, syncBinding, "sync on/off"}, {opts.SyncKey, syncBinding, "broadcast to all panes"},
{opts.SoloKey, soloBinding, "solo on/off"}, {opts.SoloKey, soloBinding, "exclude/include this pane"},
} { } {
if key.key == "" { if key.key == "" {
continue continue
@@ -174,7 +161,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
continue continue
} }
fmt.Fprintf(&conf, key.binding, key.key) fmt.Fprintf(&conf, key.binding, key.key)
hints = append(hints, displayKey(prefix)+" then "+displayKey(key.key)+": "+key.what) hints = append(hints, prefix+" "+key.key+" "+key.what)
} }
if conf.Len() > 0 { if conf.Len() > 0 {
path := filepath.Join(opts.LayoutDir, "netssh-multi.tmux.conf") path := filepath.Join(opts.LayoutDir, "netssh-multi.tmux.conf")
@@ -185,7 +172,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
return "", err return "", err
} }
} }
hint := "keys: " + strings.Join(hints, " | ") hint := "keys: " + strings.Join(hints, ", ")
if len(hints) == 0 { if len(hints) == 0 {
hint = "toggle broadcast with: netssh sync, netssh sync --pane" hint = "toggle broadcast with: netssh sync, netssh sync --pane"
} }
@@ -205,9 +192,3 @@ func freeSession(r Runner, name string) string {
candidate = name + "-" + strconv.Itoa(n) 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+")
}
-87
View File
@@ -1,87 +0,0 @@
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),
).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,9 +108,6 @@ func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, ori
} }
return nil 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 { 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() return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes()
}), }),
-10
View File
@@ -23,7 +23,6 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
extraArgs := strings.Join(o.ExtraArgs, "\n") extraArgs := strings.Join(o.ExtraArgs, "\n")
options := formatOptions(o.Options) options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards) forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
@@ -70,14 +69,6 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s) _, err := parseForwards(s)
return err return err
}), }),
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() ).Title(title)).Run()
if err != nil { if err != nil {
return o, err return o, err
@@ -93,7 +84,6 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
AddressFamily: addressFamily, AddressFamily: addressFamily,
ExtraArgs: parseLines(extraArgs), ExtraArgs: parseLines(extraArgs),
Options: parsed, Options: parsed,
PreConnect: strings.TrimSpace(preConnect),
}, nil }, nil
} }
+3 -38
View File
@@ -94,7 +94,6 @@ func runMenu(cfg *config.Config) error {
huh.NewOption(fmt.Sprintf("Multi-session — groups, tmux/zellij (%d groups)", len(cfg.Groups)), "multi"), huh.NewOption(fmt.Sprintf("Multi-session — groups, tmux/zellij (%d groups)", len(cfg.Groups)), "multi"),
huh.NewOption("Resolver & cache", "resolver"), huh.NewOption("Resolver & cache", "resolver"),
huh.NewOption("Shortcuts & command alias", "shortcuts"), huh.NewOption("Shortcuts & command alias", "shortcuts"),
huh.NewOption("Custom commands — mtr, ping, scripts", "commands"),
huh.NewOption("Completion", "completion"), huh.NewOption("Completion", "completion"),
huh.NewOption("Save and exit", "save"), huh.NewOption("Save and exit", "save"),
). ).
@@ -123,8 +122,6 @@ func runMenu(cfg *config.Config) error {
err = editResolverCache(cfg) err = editResolverCache(cfg)
case "shortcuts": case "shortcuts":
err = editShortcuts(cfg) err = editShortcuts(cfg)
case "commands":
err = editCommands(cfg)
case "completion": case "completion":
err = editCompletion(cfg) err = editCompletion(cfg)
case "save": case "save":
@@ -229,7 +226,6 @@ func editShortcuts(cfg *config.Config) error {
stripHyphens := cfg.Shortcuts.StripHyphens stripHyphens := cfg.Shortcuts.StripHyphens
rewrites := formatRewrites(cfg.Shortcuts.Rewrites) rewrites := formatRewrites(cfg.Shortcuts.Rewrites)
commandAlias := cfg.Shell.Alias commandAlias := cfg.Shell.Alias
showShortcuts := cfg.Shortcuts.Show
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
Title("Domain suffixes"). Title("Domain suffixes").
@@ -251,11 +247,6 @@ func editShortcuts(cfg *config.Config) error {
_, err := parseRewrites(s) _, err := parseRewrites(s)
return err 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(). huh.NewInput().
Title("Command alias"). Title("Command alias").
Description("Optional alias for netssh itself, e.g. j. Leave empty to disable."). Description("Optional alias for netssh itself, e.g. j. Leave empty to disable.").
@@ -275,7 +266,6 @@ func editShortcuts(cfg *config.Config) error {
} }
cfg.Shortcuts.StripHyphens = stripHyphens cfg.Shortcuts.StripHyphens = stripHyphens
cfg.Shortcuts.Rewrites, _ = parseRewrites(rewrites) cfg.Shortcuts.Rewrites, _ = parseRewrites(rewrites)
cfg.Shortcuts.Show = showShortcuts
cfg.Shell.Alias = strings.TrimSpace(commandAlias) cfg.Shell.Alias = strings.TrimSpace(commandAlias)
return nil return nil
} }
@@ -382,9 +372,6 @@ func save(cfg config.Config) error {
if err := cfg.ValidateHosts(); err != nil { if err := cfg.ValidateHosts(); err != nil {
return err return err
} }
if err := cfg.ValidateCommands(); err != nil {
return err
}
if err := cfg.ValidateMulti(); err != nil { if err := cfg.ValidateMulti(); err != nil {
return err return err
} }
@@ -398,9 +385,6 @@ func save(cfg config.Config) error {
b.WriteString("netboxes:\n") b.WriteString("netboxes:\n")
for _, source := range cfg.NetBoxes { 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) 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) { if !sshOptionsEmpty(source.SSH) {
b.WriteString(" ssh:\n") b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", source.SSH) writeSSHOptions(&b, " ", source.SSH)
@@ -517,7 +501,7 @@ func save(cfg config.Config) error {
fmt.Fprintf(&b, "\ncompletion:\n max_results: %d\n", cfg.Completion.MaxResults) fmt.Fprintf(&b, "\ncompletion:\n max_results: %d\n", cfg.Completion.MaxResults)
} }
if cfg.Shortcuts.Enabled() || cfg.Shortcuts.Show { if cfg.Shortcuts.Enabled() {
b.WriteString("\nshortcuts:\n") b.WriteString("\nshortcuts:\n")
if len(cfg.Shortcuts.Domains) > 0 { if len(cfg.Shortcuts.Domains) > 0 {
b.WriteString(" domains:\n") b.WriteString(" domains:\n")
@@ -534,25 +518,6 @@ func save(cfg config.Config) error {
fmt.Fprintf(&b, " - pattern: %q\n replace: %q\n", r.Pattern, r.Replace) 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)
}
}
} }
if cfg.Shell.Alias != "" { if cfg.Shell.Alias != "" {
@@ -568,12 +533,12 @@ func save(cfg config.Config) error {
} }
func sshOptionsEmpty(o config.SSHOptions) bool { 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 && o.PreConnect == "" return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0
} }
// writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config. // writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config.
func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) { 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}, {"pre_connect", o.PreConnect}} { for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}} {
if field[1] != "" { if field[1] != "" {
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1]) fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
} }
+2 -49
View File
@@ -398,7 +398,7 @@ func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{ cfg := config.Config{
NetBoxes: []config.NetBoxConfig{ NetBoxes: []config.NetBoxConfig{
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2, DisablePrefix: true}, {Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2},
{Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1}, {Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1},
}, },
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
@@ -438,10 +438,9 @@ func TestSaveKeepsSSHOptions(t *testing.T) {
AddressFamily: "inet", AddressFamily: "inet",
ExtraArgs: []string{"-A"}, ExtraArgs: []string{"-A"},
Options: map[string]string{"serveraliveinterval": "60"}, Options: map[string]string{"serveraliveinterval": "60"},
PreConnect: `vpn-check "$NETSSH_HOST" && echo 'ok'`,
} }
cfg := config.Config{ cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off", PreConnect: "none"}}}, NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off"}}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600}, Cache: config.CacheConfig{TTL: 3600},
SSH: config.SSHConfig{ SSH: config.SSHConfig{
@@ -652,49 +651,3 @@ func TestParseGroupsAndSaveMulti(t *testing.T) {
t.Fatalf("got %v %+v", loaded.Groups, loaded.Multi) 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)
}
}
-114
View File
@@ -9,7 +9,6 @@ import (
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "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" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
) )
@@ -80,116 +79,3 @@ func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) {
t.Fatalf("outage warning overflowed view: %d", rows) 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)
}
}
+3 -50
View File
@@ -63,8 +63,6 @@ type searchResultMsg struct {
// --- list item --- // --- list item ---
type hostItem struct { type hostItem struct {
label string // display only; name remains the canonical target
alias string // shortcut alias shown next to the name (shortcuts.show)
name string name string
id int id int
ip string ip string
@@ -72,12 +70,7 @@ type hostItem struct {
tags []string tags []string
} }
func (h hostItem) Title() string { func (h hostItem) Title() string { return h.name }
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) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) }
func (h hostItem) FilterValue() string { return h.name } func (h hostItem) FilterValue() string { return h.name }
@@ -98,11 +91,7 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
if d.marked[h.key()] { if d.marked[h.key()] {
mark = "● " mark = "● "
} }
title := h.Title() line := fmt.Sprintf(" %s%s %s", mark, h.name, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
if h.alias != "" {
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+h.alias)
}
line := fmt.Sprintf(" %s%s %s", mark, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
if index == m.Index() { if index == m.Index() {
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " ")) line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
} }
@@ -192,8 +181,6 @@ type Model struct {
editMode bool // Ctrl+E on the selected item editMode bool // Ctrl+E on the selected item
forwardMode bool // Ctrl+T on the selected item forwardMode bool // Ctrl+T on the selected item
marked map[string]bool // hostItem.key() of hosts marked with space marked map[string]bool // hostItem.key() of hosts marked with space
hostLabel func(string) string
aliasFor func(string) string // shortcut alias per target, "" for none
markOrder []string // targets in the order they were marked markOrder []string // targets in the order they were marked
} }
@@ -691,34 +678,12 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value()) f := parseFilter(m.filterInput.Value())
filtered := applyFilter(entries, f) filtered := applyFilter(entries, f)
items := make([]list.Item, len(filtered)) 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 { for i, e := range filtered {
ip := e.PrimaryIP4 ip := e.PrimaryIP4
if ip == "" { if ip == "" {
ip = e.PrimaryIP6 ip = e.PrimaryIP6
} }
label := labels[i] items[i] = hostItem{id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
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 = ""
}
}
items[i] = hostItem{label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
} }
m.list.SetItems(items) m.list.SetItems(items)
m.resizeList() m.resizeList()
@@ -854,15 +819,3 @@ func parseForwards(input string, available []string) ([]string, error) {
} }
return fields, nil 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
}
+1 -1
View File
@@ -10,7 +10,7 @@ COPY cmd ./cmd
COPY internal ./internal COPY internal ./internal
RUN CGO_ENABLED=0 go build -o /out/netssh ./cmd/netssh RUN CGO_ENABLED=0 go build -o /out/netssh ./cmd/netssh
FROM alpine:3.24 FROM alpine:3.23
# xvfb/xterm/imagemagick/tesseract: render panes in a real terminal emulator, # xvfb/xterm/imagemagick/tesseract: render panes in a real terminal emulator,
# take screenshots, and read them back with OCR (tests/16-render.sh). # take screenshots, and read them back with OCR (tests/16-render.sh).
RUN apk add --no-cache openssh-client-default tmux zellij bash zsh fish bash-completion \ RUN apk add --no-cache openssh-client-default tmux zellij bash zsh fish bash-completion \
+1 -1
View File
@@ -6,7 +6,7 @@
name: netssh-test name: netssh-test
x-netbox: &netbox x-netbox: &netbox
image: netboxcommunity/netbox:v4.7.5-5.1.1 image: netboxcommunity/netbox:v4.7.4-5.1.1
depends_on: depends_on:
postgres: {condition: service_healthy} postgres: {condition: service_healthy}
redis: {condition: service_healthy} redis: {condition: service_healthy}
+1 -1
View File
@@ -1,6 +1,6 @@
# SSH target for the netssh test environment: every NetBox host, the bastion, # SSH target for the netssh test environment: every NetBox host, the bastion,
# and the static host run this image with a different hostname. # and the static host run this image with a different hostname.
FROM alpine:3.24 FROM alpine:3.23
# Alpine locks new accounts with "!"; sshd refuses key logins for locked # Alpine locks new accounts with "!"; sshd refuses key logins for locked
# accounts, so the password field is set to "*" (no password, not locked). # accounts, so the password field is set to "*" (no password, not locked).