Author SHA1 Message Date
Sebastian UnterschützandClaude Opus 5.5 080e52b437 docs: document DNS suggestions, dns settings and links (v1.3.0)
Test / test (pull_request) Successful in 4m16s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:09 +01:00
Sebastian UnterschützandClaude Opus 5.5 e905a39068 feat: add netssh link and shell aliases for links
netssh link add|list|remove manages links; netssh NAME follows them, links
complete with Tab and get a shell alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:09 +01:00
Sebastian UnterschützandClaude Opus 5.5 793f095e80 feat: suggest the host behind unknown DNS names
A name neither in NetBox nor in the cache is resolved through DNS, using
dns.domains for short names. The hosts owning the address in NetBox or the
cache are offered together with a direct connection; without a terminal the
suggestions are part of the error. Afterwards netssh offers to save the name
as a link. info, open and whois use the same lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:08 +01:00
Sebastian UnterschützandClaude Opus 5.5 5c41a5eb6f feat(config): add links and dns settings
- links: short names mapped to host selectors, validated against chains
  and static host names
- dns.suggest / dns.save_link: ask, always or never
- dns.domains: domain rules per name pattern (mx* -> easysahre.de)
- the wizard edits the dns settings under Resolver & cache and keeps links;
  setup.SaveTo reports to a chosen writer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:08 +01:00
Sebastian UnterschützandClaude Opus 5.5 c408d529a0 fix(hook): honour NetBox attribute restrictions in command aliases
Generated command aliases checked commands.*.match against hosts without
their status, site, role, platform and tenant, so a restriction such as
match: {platform: junos} produced no aliases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:08 +01:00
Sebi c87c2623ec Merge pull request 'feat: NetBox insights, host tools and configurable TUI' (#45) from feat/netbox-insights into main
Test / test (push) Successful in 4m14s
Release / release (push) Successful in 8m0s
2026-11-18 11:39:44 +00:00
Sebastian UnterschützandClaude Opus 5.5 1660bb3098 feat: NetBox insights, host tools and configurable TUI
Test / test (pull_request) Successful in 4m15s
- info/open/whois: NetBox details (site, nested locations, rack units,
  role, platform, tenant, IPs per interface), web page, reverse IP lookup
- cache status, site, role, platform, tenant, location chain and rack;
  ask before connecting to hosts in ssh.warn_status (--force skips)
- ssh rules and command restrictions match site/role/platform/tenant/status
- tui.columns selects what the TUI shows; optional TCP reachability column;
  detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters
- resolver.fallback tries other strategies' addresses when unreachable
- copy-id, known-hosts reset and address-change notices
- export ansible (YAML/INI) and export ssh-config
- token: keyring stores NetBox tokens in the system keyring
- fix stale menu number in testenv configure test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:33:59 +01:00
Sebastian Unterschütz e5bde9c61f feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s
2026-11-18 10:41:36 +01:00
62 changed files with 8046 additions and 99 deletions

No files matched your search

+32
View File
@@ -1,5 +1,37 @@
# Changelog # Changelog
## v1.3.0
- Unknown names are resolved through DNS, and the hosts owning the address in NetBox or the cache are suggested, together with a direct connection to the DNS name. Without a terminal the suggestions are part of the error. `netssh info`, `open` and `whois` use it too.
- Add `dns.domains`: domain rules per name pattern for short names (`mx*` → `easysahre.de`, `ah*` → `jhfduwia.de`), independent of `shortcuts.domains`.
- Add `dns.suggest` and `dns.save_link` (`ask`, `always`, `never`) to always accept or always decline the host suggestion and the shortcut offer; `always` also works in scripts. Both are in `netssh configure`.
- Add links (`links:` in the config, `netssh link add|list|remove`): `netssh mx123` and the shell alias `mx123` connect to the linked host. netssh offers to save a link after a DNS suggestion.
- Generated command aliases honour command restrictions on site, role, platform, tenant and status.
## v1.2.0
- Add `netssh info HOST` and `Ctrl+L` in the TUI: site, rack/U, role, platform, tenant, device type, serial, VM resources and all IP addresses per interface from NetBox; `--json` for scripts.
- Add `netssh open HOST` and `Ctrl+G` in the TUI to open the host's NetBox page (`--print` prints the URL).
- Add `netssh whois ADDRESS|HOSTNAME`: the device or VM, interface, DNS name and containing prefixes of an address across all NetBox instances, plus matching cached hosts.
- Cache NetBox ID, status, site, role, platform and tenant. Ask before connecting to hosts whose status is in `ssh.warn_status` (default: offline, planned, staged, failed, inventory, decommissioning); `--force` skips the question, non-interactive callers get a warning. The TUI shows a status badge and filters by `status:`, `site:`, `role:`, `platform:` and `tenant:`.
- `ssh.rules` and command restrictions match `site`, `role`, `platform`, `tenant` and `status` (name or slug), e.g. legacy key exchange for `platform: junos`. The wizard edits the new selectors.
- Show where a device is: site › all nested NetBox locations › rack › rack unit. `netssh info` and the TUI detail view add `Location`, `Rack` (units, height, face) and `Path`; the TUI gets a `location` column and `location:`/`rack:` filters; Ansible exports add `netbox_location`, `netbox_rack`, `netbox_position` and `--group-by location,rack`. Each location is fetched once per run.
- Add `tui.columns` to choose what the TUI shows next to each host and in which order: `alias`, `ip`, `kind`, `source`, `status`, `site`, `location`, `role`, `platform`, `tenant`, `cluster`, `tags`, `reachability` (default `[alias, ip, source, status]`). Also in `netssh configure`.
- Optional TUI reachability check (`reachability` column, off by default): listed hosts are probed on their SSH port and marked ✓/✗ (`tui.reachability_timeout`); hosts behind a jump host are skipped.
- Add `resolver.fallback`: when the chosen address does not answer, connect to the first answering address of the other strategies (or the other primary IP) for this connection.
- Add `netssh copy-id` to run ssh-copy-id with netssh's address, user, port, jump host and options, for single hosts, `tag:`, `cluster:` and `@group`.
- Report changed host addresses on connect and in `netssh cache refresh`, offer to remove the old known_hosts entry, and add `netssh known-hosts reset HOST...`.
- Add `netssh export ansible` (YAML or INI inventory with groups by tag/site/role/platform/… and `netbox_*` host variables) and `netssh export ssh-config`.
- Add keyring token storage: `token: keyring` reads the NetBox token from the system keyring; `netssh token set|migrate|delete|status` manage it, `netssh doctor` checks it.
## v1.1.0
- Add local post-disconnect/post-command scripts, execution timeouts, cancellation, per-command confirmation and host restrictions.
- Add configurable recent-host count, persistent favorites/pins, a TUI command menu and cache/live/stale indicators.
- Add doctor/explain diagnostics, parallel batch commands with failed-host retry, and optional bounded local action history.
- Add configuration export/import that excludes credentials and executable settings while preserving matching local credentials.
- Preserve terminal behavior and process exit status during supervised execution; test Bash/Python scripts, process cancellation, concurrency and batch retries.
## v1.0.0 ## v1.0.0
- Consolidate the complete project into the initial v1 commit. - Consolidate the complete project into the initial v1 commit.
+602 -9
View File
@@ -22,6 +22,8 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [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), [pre-connect hook](#pre-connect-hook), [SFTP & SCP](#sftp-and-scp), [port forwarding](#port-forwarding), [static hosts](#static-hosts), [multiple servers](#multiple-servers-in-one-window), [shortcuts](#host-shortcuts), [TUI](#interactive-tui), [notes](#server-notes), [cache](#cache-management)
- [Operations](#operations) — post scripts, favorites, history, diagnostics, batch commands, configuration sharing
- [NetBox insights and host tools](#netbox-insights-and-host-tools) — `info`, `open`, `whois`, status warnings, TUI columns and reachability, address fallback, `copy-id`, `known-hosts`, `export`, keyring tokens
- [Custom host commands](#custom-host-commands) — automatic aliases for mtr, ping, and other programs - [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 - [Hotkey cheat sheet](#hotkey-cheat-sheet) — search, editors, tmux and zellij
- [Recipes](#recipes) - [Recipes](#recipes)
@@ -36,7 +38,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- **Flexible IP resolution** — configurable chain of strategies: management subnet, primary IP, named interface, or the hostname itself - **Flexible IP resolution** — configurable chain of strategies: management subnet, primary IP, named interface, or the hostname itself
- **Static hosts** — add hosts that are not in NetBox (`netssh hosts add router 192.168.1.1`); they work everywhere, also without any NetBox - **Static hosts** — add hosts that are not in NetBox (`netssh hosts add router 192.168.1.1`); they work everywhere, also without any NetBox
- **Interactive TUI** — fuzzy search with live NetBox queries and 300 ms debouncing (start with `netssh`, no arguments) - **Interactive TUI** — fuzzy search with live NetBox queries and 300 ms debouncing (start with `netssh`, no arguments)
- **Recently-used list** — TUI opens with your 10 most-recently-connected hosts, no typing needed - **Recently-used list** — TUI opens with your most-recently-connected hosts (10 by default, configurable with `tui.history_limit`), no typing needed
- **Tag/kind filter** — press `Ctrl+F` in the TUI to filter by `tag:prod` or `kind:vm` - **Tag/kind filter** — press `Ctrl+F` in the TUI to filter by `tag:prod` or `kind:vm`
- **User/port override** — press `Ctrl+E` in the TUI to override the SSH user or port before connecting - **User/port override** — press `Ctrl+E` in the TUI to override the SSH user or port before connecting
- **Server notes** — multiline local notes or optional NetBox comments, available in the TUI and CLI - **Server notes** — multiline local notes or optional NetBox comments, available in the TUI and CLI
@@ -55,6 +57,14 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- **Several servers in one window** — `netssh multi` opens hosts, a tag, a NetBox cluster, or a saved group side by side in tmux or zellij, with optional typing into all of them - **Several servers in one window** — `netssh multi` opens hosts, a tag, a NetBox cluster, or a saved group side by side in tmux or zellij, with optional typing into all of them
- **Port forwarding** — named forwards in the config (`netssh tunnel host web`, `netssh --forward web host`), ad hoc specs, and `Ctrl+T` in the TUI - **Port forwarding** — named forwards in the config (`netssh tunnel host web`, `netssh --forward web host`), ad hoc specs, and `Ctrl+T` in the TUI
- **Dry run** — `netssh --dry-run host` prints the final `ssh` command instead of connecting - **Dry run** — `netssh --dry-run host` prints the final `ssh` command instead of connecting
- **Host details** — `netssh info host` (and `Ctrl+L` in the TUI) shows site, the nested locations down to rack and rack units, role, platform, tenant, status and all IP addresses per interface; `netssh open host` (`Ctrl+G`) opens the NetBox page
- **DNS names and links** — `netssh mx123.webseite.de` (or `netssh mx123`) for a name that is only in DNS: netssh finds the host owning the address in NetBox, suggests it, and can save `mx123` as a link — `netssh mx123` and the shell alias `mx123` then connect directly
- **Reverse lookup** — `netssh whois 10.1.2.3` names the device or VM, interface, DNS name and prefixes of an address
- **Status warning** — asks before connecting to hosts that are `offline`, `planned`, `decommissioning` …; TUI badge and `status:` filter
- **Configurable TUI** — choose what is shown next to each host (`tui.columns`: IP, source, status, site, location path, role, platform, tenant, cluster, tags, kind, alias); the optional `reachability` column marks hosts ✓/✗ after a quick TCP check of their SSH port; `resolver.fallback` connects to another known address when the chosen one does not answer
- **Rules by NetBox attributes** — `ssh.rules` and command restrictions match `site`, `role`, `platform`, `tenant` and `status`, e.g. legacy ciphers for `platform: junos`
- **ssh-copy-id, known_hosts cleanup, exports** — `netssh copy-id tag:lab`, `netssh known-hosts reset host`, `netssh export ansible` (YAML or INI) and `netssh export ssh-config`
- **Keyring tokens** — `netssh token migrate` moves API tokens from the config into the system keyring
- **Clean uninstall** — `netssh uninstall` removes the binary, profile entries of all versions, completions, cache, and config - **Clean uninstall** — `netssh uninstall` removes the binary, profile entries of all versions, completions, cache, and config
## Installation ## Installation
@@ -211,17 +221,20 @@ Every key, its default, and the section that explains it. Keys marked *layered*
| Key | Type | Default | Description | | Key | Type | Default | Description |
|---|---|---|---| |---|---|---|---|
| `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. `keyring` reads it from the system keyring — see [Keyring tokens](#keyring-tokens). |
| `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`, `disable_prefix`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
| `resolver.strategies` | list | `[management_subnet, primary_ip]` | Tried in order, first IP wins — see [IP Resolution Strategies](#ip-resolution-strategies). The wizard suggests `primary_ip`. | | `resolver.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`. |
| `resolver.hostname_domain` | string | — | Used by `hostname`: appended to NetBox names without a dot. | | `resolver.hostname_domain` | string | — | Used by `hostname`: appended to NetBox names without a dot. |
| `resolver.fallback` | bool | `false` | When the chosen address does not answer on the SSH port, connect to the first address of another strategy that does — see [Address fallback](#address-fallback). |
| `resolver.fallback_timeout` | milliseconds | `1000` | Connect timeout per address for the fallback check. |
| `cache.ttl` | seconds | `3600` | How long a cached IP is used without asking NetBox; `0` always asks NetBox when connecting. | | `cache.ttl` | seconds | `3600` | How long a cached IP is used without asking NetBox; `0` always asks NetBox when connecting. |
| `cache.path` | path | user cache dir `/netssh/hosts.json` | Cache file; named instances use a subdirectory next to it. | | `cache.path` | path | user cache dir `/netssh/hosts.json` | Cache file; named instances use a subdirectory next to it. |
| `ssh.default_user` | string | — | Login user when none is given (`-l` for ssh, `-o User=` for sftp/scp). | | `ssh.default_user` | string | — | Login user when none is given (`-l` for ssh, `-o User=` for sftp/scp). |
| `ssh.default_port` | int | — | Port when none is given (`-p` for ssh, `-P` for sftp/scp). | | `ssh.default_port` | int | — | Port when none is given (`-p` for ssh, `-P` for sftp/scp). |
| `ssh.warn_status` | list | `[offline, planned, staged, failed, inventory, decommissioning]` | NetBox status values that ask before connecting; `[]` disables the question — see [Status warning](#status-warning). |
| `ssh.proxy_jump` | string | — | *Layered.* Jump host (`-J`); `none` disables an inherited one. | | `ssh.proxy_jump` | string | — | *Layered.* Jump host (`-J`); `none` disables an inherited one. |
| `ssh.host_key_checking` | `strict` \| `accept-new` \| `off` | ssh's own | *Layered.* See [SSH options](#ssh-options). | | `ssh.host_key_checking` | `strict` \| `accept-new` \| `off` | ssh's own | *Layered.* See [SSH options](#ssh-options). |
| `ssh.target` | `ip` \| `name` \| `hostname` | `ip` | *Layered.* What is passed to ssh as destination. | | `ssh.target` | `ip` \| `name` \| `hostname` | `ip` | *Layered.* What is passed to ssh as destination. |
@@ -229,8 +242,14 @@ 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.post_disconnect` | string | — | *Layered.* Local shell command after the client exits; `none` disables inheritance. |
| `tui.history_limit` | integer | `10` | Recent hosts shown; `0` means all, favorites are additional. |
| `tui.columns` | list | `[alias, ip, source, status]` | What the TUI shows next to each hostname (also `location`), in order; `[]` shows only names. Adding `reachability` enables the TCP check — see [TUI columns](#tui-columns-and-reachability). |
| `tui.reachability_timeout` | milliseconds | `300` | Timeout of the TCP check of the `reachability` column. |
| `activity.enabled` | boolean | `false` | Enable local execution metadata history. |
| `activity.retention_days` / `activity.max_entries` | integer | `30` / `1000` | History retention limits; `0` disables the respective limit. |
| `ssh.pre_connect` | string | — | *Layered.* Shell command run locally before connecting; a non-zero exit aborts; `none` disables an inherited one — see [Pre-connect hook](#pre-connect-hook). | | `ssh.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`, `site`, `role`, `platform`, `tenant`, `status`) 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). |
@@ -240,6 +259,10 @@ Every key, its default, and the section that explains it. Keys marked *layered*
| `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). | | `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. |
| `dns.suggest` | `ask` \| `always` \| `never` | `ask` | Unknown names: suggest the host owning the DNS address (`ask`), take the first suggestion without asking, also in scripts (`always`), or do no DNS lookup (`never`) — see [DNS names and links](#dns-names-and-links). |
| `dns.save_link` | `ask` \| `always` \| `never` | `ask` | Save a link after a suggestion: ask, always, or never. |
| `dns.domains[]` | list | `[]` | `match` (glob on the typed name, e.g. `mx*`; empty = all) and `domain` appended to names without a dot. |
| `links` | map | `{}` | Short names for hosts, `mx123: prod/web07`: `netssh mx123` and the shell alias `mx123` connect to the host — see [DNS names and links](#dns-names-and-links). |
| `multi.multiplexer` | `auto` \| `tmux` \| `zellij` | `auto` | Which multiplexer `netssh multi` uses. | | `multi.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. |
| `multi.sync_key`, `multi.solo_key` | tmux key \| `none` | `S`, `e` | Keys after the tmux prefix: broadcast to all panes, exclude/include the current pane. | | `multi.sync_key`, `multi.solo_key` | tmux key \| `none` | `S`, `e` | Keys after the tmux prefix: broadcast to all panes, exclude/include the current pane. |
@@ -254,11 +277,15 @@ 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_WARN_STATUS` | `ssh.warn_status` |
| `NETSSH_TUI_COLUMNS`, `NETSSH_TUI_REACHABILITY_TIMEOUT` | `tui.columns`, `tui.reachability_timeout` |
| `NETSSH_RESOLVER_FALLBACK`, `NETSSH_RESOLVER_FALLBACK_TIMEOUT` | `resolver.fallback*` |
| `NETSSH_SSH_PROXY_JUMP`, `NETSSH_SSH_HOST_KEY_CHECKING`, `NETSSH_SSH_TARGET`, `NETSSH_SSH_ADDRESS_FAMILY`, `NETSSH_SSH_PRE_CONNECT` | global `ssh.*` options | | `NETSSH_SSH_PROXY_JUMP`, `NETSSH_SSH_HOST_KEY_CHECKING`, `NETSSH_SSH_TARGET`, `NETSSH_SSH_ADDRESS_FAMILY`, `NETSSH_SSH_PRE_CONNECT` | global `ssh.*` options |
| `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS`, `NETSSH_SHORTCUTS_SHOW` | `shortcuts.*` | | `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS`, `NETSSH_SHORTCUTS_SHOW` | `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` |
| `NETSSH_DNS_SUGGEST`, `NETSSH_DNS_SAVE_LINK` | `dns.suggest`, `dns.save_link` |
netssh also respects `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, `ZDOTDIR`, and `SHELL` (for `hook install`, `completion install`, and `alias` without `--shell`). netssh also respects `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, `ZDOTDIR`, and `SHELL` (for `hook install`, `completion install`, and `alias` without `--shell`).
@@ -393,6 +420,9 @@ NetBox supports two token formats:
`netssh` auto-detects the version from the token prefix and stores it as `token_version` in the config. `netssh` auto-detects the version from the token prefix and stores it as `token_version` in the config.
A hint is shown during `netssh configure` if a legacy v1 token is entered. A hint is shown during `netssh configure` if a legacy v1 token is entered.
To keep tokens out of the config file, store them in the system keyring with
`netssh token set` or `netssh token migrate` — see [Keyring tokens](#keyring-tokens).
## Usage ## Usage
### Command overview ### Command overview
@@ -403,6 +433,17 @@ 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 doctor [--online]` / `netssh explain HOST` | Diagnose configuration and explain effective settings. |
| `netssh info [--json] HOST` / `netssh open [--print] HOST` | Show NetBox details of a host / open its NetBox page — see [Host details](#host-details-and-netbox-page). |
| `netssh link list \| add NAME HOST \| remove NAME` | Short names for hosts — see [DNS names and links](#dns-names-and-links). |
| `netssh whois [--json] ADDRESS\|HOSTNAME` | Find the host, interface and prefix of an address — see [Reverse lookup](#reverse-lookup). |
| `netssh copy-id [-i KEY] [-l U] [--dry-run] HOST\|tag:T\|cluster:C\|@GROUP...` | Install your public key with ssh-copy-id — see [ssh-copy-id](#ssh-copy-id). |
| `netssh known-hosts reset [--yes] [--dry-run] HOST...` | Remove stored host keys of re-deployed hosts — see [known_hosts cleanup](#known_hosts-cleanup). |
| `netssh export ansible [--format yaml\|ini] [--group-by …]` / `netssh export ssh-config` | Export cached hosts — see [Exports](#exports-ansible-inventory-and-ssh_config). |
| `netssh token set\|migrate\|delete\|status` | Keep NetBox tokens in the system keyring — see [Keyring tokens](#keyring-tokens). |
| `netssh favorites` / `netssh history` | Manage saved hosts and optional action records. |
| `netssh batch COMMAND HOST...` | Run a configured command with bounded parallelism and retry. |
| `netssh config export\|import FILE` | Share host configuration without secrets or executable settings. |
| `netssh run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]` | Run a [custom host command](#custom-host-commands), e.g. mtr or ping, using the configured resolver. | | `netssh 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). |
@@ -418,7 +459,7 @@ A hint is shown during `netssh configure` if a legacy v1 token is entered.
| `netssh uninstall [--dry-run] [--keep-config] [--yes]` | Remove netssh. | | `netssh uninstall [--dry-run] [--keep-config] [--yes]` | Remove netssh. |
| `netssh version` / `netssh --version` | Print the version. | | `netssh version` / `netssh --version` | Print the version. |
The netssh flags `--dry-run`, `--jump`, `--no-jump`, and `--forward` must come before the host. Everything after the host is passed to ssh as the remote command (for `tunnel`: forward names). The netssh flags `--dry-run`, `--force`, `--jump`, `--no-jump`, and `--forward` must come before the host. `--force` connects without asking about the NetBox status. Everything after the host is passed to ssh as the remote command (for `tunnel`: forward names).
### SSH wrapper mode ### SSH wrapper mode
@@ -927,17 +968,19 @@ Run without arguments to open the interactive search:
netssh netssh
``` ```
The TUI opens with your 10 most-recently-connected hosts. Start typing to search all cached hosts or query NetBox live. The TUI opens with your most-recently-connected hosts (10 by default, configurable with `tui.history_limit`). Start typing to search all cached hosts or query NetBox live.
See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys. See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys.
**Tag and kind filter** — press `Ctrl+F` to open a second input line: **Filter** — press `Ctrl+F` to open a second input line:
``` ```
Filter: tag:prod kind:vm Filter: tag:prod kind:vm status:active site:fsn1 location:building-a role:router platform:junos tenant:acme
``` ```
Multiple `tag:` values are AND-combined. The filter is applied locally against the cache; when doing a live NetBox search the first tag is also forwarded as a query parameter. `location:` matches any level of the location chain (name or slug), `rack:` the rack name.
Multiple `tag:` values are AND-combined. `site:`, `role:`, `platform:` and `tenant:` accept the NetBox name or slug; they need a cache written by this version (`netssh cache refresh`). The filter is applied locally against the cache; when doing a live NetBox search the first tag is also forwarded as a query parameter.
**User/port override** — press `Ctrl+E` on any highlighted host: **User/port override** — press `Ctrl+E` on any highlighted host:
@@ -947,6 +990,10 @@ Connect as: admin@my-router:22
Edit the pre-filled value and press `Enter` to connect. `Esc` cancels. The configured default port is pre-filled. An explicit port 22 overrides a different configured default. Edit the pre-filled value and press `Enter` to connect. `Esc` cancels. The configured default port is pre-filled. An explicit port 22 overrides a different configured default.
**Details and NetBox page** — `Ctrl+L` shows the host's NetBox details (site, rack, role, platform, status, IP addresses) without leaving the TUI; `Enter` connects from there. `Ctrl+G` opens the host's NetBox page in the browser.
**Columns** — by default each host shows its shortcut alias, IP, source and a badge such as `[offline]` when its NetBox status is not `active`. Choose other information, its order, and the optional `✓`/`✗` reachability check with `tui.columns` — see [TUI columns](#tui-columns-and-reachability).
### Server notes ### Server notes
Select a server in the TUI and press `Ctrl+N` for local notes, or `Ctrl+B` for Select a server in the TUI and press `Ctrl+N` for local notes, or `Ctrl+B` for
@@ -1038,12 +1085,17 @@ in the search, while tmux uses `Ctrl+b` as its default prefix.
| `Enter` | connect to selected host | | `Enter` | connect to selected host |
| `Space` | mark/unmark the host; with marks, `Enter` opens them side by side (`netssh multi`) | | `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+A` | mark all listed hosts (again: unmark all) |
| `Ctrl+R` | choose SSH or a configured command; marked hosts run the command as a batch |
| `Ctrl+D` | toggle favorite for the selected host |
| `Ctrl+P` | toggle pin; pinning also adds the host to favorites |
| `Ctrl+O` | open an SFTP session to the selected host | | `Ctrl+O` | open an SFTP session to the selected host |
| `Ctrl+T` | start a tunnel: enter forward names or specs (`web, 8080:localhost:80`) | | `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+E` | open inline editor to override user/port before connecting |
| `Ctrl+N` | edit local notes for the selected server | | `Ctrl+N` | edit local notes for the selected server |
| `Ctrl+B` | edit NetBox comments 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`) | | `Ctrl+F` | open/close the filter (`tag:prod kind:vm status:active site:fsn1 platform:junos`) |
| `Ctrl+L` | show NetBox details of the selected host (`Enter` connects, `Ctrl+G` opens NetBox, `Esc` back) |
| `Ctrl+G` | open the NetBox page of the selected host in the browser |
| `Esc` | quit search | | `Esc` | quit search |
| `Ctrl+C` | quit from any TUI mode, including editors | | `Ctrl+C` | quit from any TUI mode, including editors |
@@ -1113,6 +1165,547 @@ the whole tab. When starting a new zellij session, enable broadcast manually
with `Ctrl+t` then `s`; `--sync` is applied automatically only inside an with `Ctrl+t` then `s`; `--sync` is applied automatically only inside an
existing zellij session. existing zellij session.
## Operations
### Post scripts
`ssh.post_disconnect` runs a local shell command after the SSH, SFTP, SCP or
tunnel process exits. Configure it globally, per NetBox instance, per static host
or in an SSH rule. More specific values override broader ones; `none` disables
an inherited hook.
```yaml
ssh:
post_disconnect: /home/user/scripts/after-ssh.sh
rules:
- match: {tag: lab}
post_disconnect: none
commands:
maintenance:
alias_prefix: maint
args: [bash, /home/user/scripts/maintenance.sh, "{address}"]
post_run: /home/user/scripts/after-maintenance.sh
match: {instance: prod, tag: router, name: "router*"}
confirm: true
timeout: 5m
```
Post scripts receive the existing `NETSSH_HOST`, `NETSSH_TARGET`,
`NETSSH_INSTANCE`, `NETSSH_IP`, `NETSSH_KIND`, `NETSSH_TAGS` and
`NETSSH_CLIENT` variables, plus `NETSSH_COMMAND` and `NETSSH_EXIT_CODE`.
They run after a started process succeeds, fails or is cancelled, but not after
a failed pre-connect hook, failed process start, or a dry run. Output goes to
stderr, stdin is closed, and post scripts have a 30-second timeout.
A failing main process retains its exit code. If only the post script fails,
its exit code is returned. Hooks cannot run after the wrapper is forcibly killed
with SIGKILL. In multi-mode each connection runs its own post script.
Without a post hook or activity logging, SSH still replaces netssh directly.
With either enabled, netssh waits for the client while preserving terminal I/O.
### Favorites, pins and recent hosts
```yaml
tui:
history_limit: 25 # default 10; 0 = all used hosts
```
Favorites remain on the TUI's opening screen independently of the recent-host
limit. Pins appear first, followed by favorites and recent hosts. `Ctrl+D`
toggles a favorite; `Ctrl+P` toggles a pin. Removing a favorite also unpins it.
A saved host missing from the cache is still shown and resolved when selected.
```sh
netssh favorites
netssh favorites add prod/web01
netssh favorites pin prod/router01
netssh favorites unpin prod/router01
netssh favorites remove prod/web01
```
Favorites use canonical targets such as `prod/web01`, so identical hostnames in
different instances stay independent. Change the recent-host limit in
`netssh configure` → **History & activity logging**.
The TUI labels results as `live`, `static` or `cache AGE`; expired cache entries
also show `stale`. A partial NetBox outage keeps available and cached results
visible and identifies failed instances in the warning. Cached results are not
proof of current reachability; normal resolution rules still apply on connect.
### TUI actions, restrictions and confirmations
Press `Ctrl+R` on a host to choose SSH or one of your configured commands,
including MTR, Ping and scripts. With marked hosts, SSH opens the existing
multi-session layout; custom commands run through `netssh batch`.
A command's `match` uses the same `instance`, `tag`, `kind` and hostname
glob `name` selectors as SSH rules. All supplied selectors must match.
Restrictions apply to generated aliases, the TUI menu and execution itself.
The chosen command is checked again for every batch target.
`confirm: true` asks before execution. Non-interactive callers must explicitly
pass `--yes`; a batch asks once for the entire selected set. For example:
```sh
netssh run --yes maintenance prod/router01
netssh run --status maintenance prod/router01
```
The terminal shows elapsed runtime for custom commands; `--status` also
enables these messages when output is redirected. `timeout` accepts durations
such as `30s` or `5m`; no value means no timeout. Timeout exits with 124.
Ctrl+C cancels foreground commands. Background batch commands run in isolated
process groups; cancellation terminates their descendants, with a two-second
grace period before forced termination. Interactive programs retain foreground
terminal behavior.
### Diagnostics
```sh
netssh doctor # validate configuration, resolver, cache and programs
netssh doctor --online # additionally query each NetBox instance
netssh explain prod/web01 # resolve and print effective settings, without connecting
```
`explain` reports the chosen instance, address, cache/static/live source,
resolver order and recorded winning strategy, matching SSH rule numbers,
effective SSH options and hooks, and username/port defaults. It does not execute
hooks, mark the host as used or modify the cache. It can query NetBox if resolution
requires it. Older cache entries may lack the winning strategy; this is reported
explicitly. A cache refresh records that information for future explanations.
### Batch commands and retry
```sh
netssh batch --parallel 4 mtr prod/router01 prod/router02 -- --report
netssh batch --yes maintenance prod/router01 prod/router02
netssh batch --dry-run maintenance prod/router01 prod/router02
netssh batch --retry-failed --parallel 2 --yes
```
Batch mode accepts explicit host names and shortcuts. All targets are resolved
and checked before launching commands; duplicates are removed. Parallelism is
bounded (default 4, range 1–64). Output is grouped by host, with each exit code
and a final success/failure count. Batch commands receive no interactive stdin.
The last non-dry-run batch saves its command name, extra arguments and failed
canonical targets in `~/.config/netssh/last-failed.json` with mode `0600`.
Retry uses only that failed subset and rechecks the current configuration and
confirmation requirement. A successful batch clears the retry targets.
Concurrent batches each run independently; the last one to finish owns the
retry file. Command output is held in temporary private files and removed at
completion.
### Optional action history
```yaml
activity:
enabled: true # default false
retention_days: 30 # 0 = unlimited age
max_entries: 1000 # 0 = unlimited count
```
```sh
netssh history
netssh history clear
```
History records host, command name, start time, total duration and final exit
code for custom commands and managed SSH/SFTP/SCP/tunnel sessions. It does not
record arguments, environment variables, API tokens or command output.
Retention is applied when writing records or showing history.
Favorites, pins and action records live in `~/.config/netssh/activity.json`
(mode `0600`), with locking and atomic writes for simultaneous sessions.
`history clear` preserves favorites. `XDG_CONFIG_HOME` applies to both state
files. Configure logging and retention in **History & activity logging**.
### Export and import without secrets
```sh
netssh config export team.json
netssh config import team.json --dry-run
netssh config import team.json --yes
```
Export uses an allowlist: instance names/URLs, static hosts, groups, resolver
settings, shortcuts, completion, recent-host limit and SSH user/port defaults.
It excludes API tokens, credentials embedded in URLs, custom command definitions,
hooks, arbitrary SSH options/rules, local history, favorites and cache contents.
The output is JSON, which is also valid YAML.
Import accepts JSON or YAML and strips credentials and executable settings even
if the supplied file contains them. It preserves local commands and global SSH
rules/options. Existing credentials and per-instance SSH options are retained
only when the instance name and URL match; static-host SSH options are retained
only for the same name/address. New instances require a local token afterward.
Import validates before writing, requires confirmation (or `--yes`), and saves
the previous configuration as `netssh.yaml.before-import` with mode `0600`.
The preview does not modify files. Export/import is intended for shared host
configuration, not a complete backup of local executable settings or secrets.
## NetBox insights and host tools
These commands and settings use more of what NetBox knows about a host. Site,
role, platform, tenant, status and the NetBox ID are stored in the cache by
`netssh cache refresh` (and by every live lookup); caches written by older
versions get them with the next refresh.
### Host details and NetBox page
```sh
netssh info prod/sw1 # site, locations, rack/U, role, platform, tenant, type, serial, IPs per interface
netssh info --json web01 # the same as JSON
netssh open web01 # NetBox page in the browser ($BROWSER, open, or xdg-open)
netssh open --print web01 # only print the URL
```
```
sw1 (device, NetBox prod)
Status Active
Site FSN1
Location Building A › Floor 2 › Room 2.04
Rack R12 U20-21 (2U, front)
Path FSN1 › Building A › Floor 2 › Room 2.04 › R12 › U20
Role Core Switch
Platform Junos
Type Juniper QFX5120
Connect 10.0.0.7 (management_subnet, cache)
URL https://netbox.example.com/dcim/devices/7/
IP addresses
* 10.0.0.7/24 em0 sw1.example.com active
192.0.2.7/24 xe-0/0/1 active
```
`Location` lists every nested NetBox location from the one directly below the
site down to the device's own location (NetBox nests them through `parent`).
`Rack` shows the occupied units with the device height and mounting face.
`*` marks primary addresses. In the TUI, `Ctrl+L` shows the same view and
`Ctrl+G` opens the page. Static hosts have no NetBox record; `info` shows their
configured address, user and port.
### Reverse lookup
```sh
netssh whois 10.0.0.7
netssh whois mail.example.com # resolved through DNS first
netssh whois --json 10.0.0.7
```
```
10.0.0.7
IP 10.0.0.7/24 prod/sw1 (device) em0 active dns sw1.example.com
Prefix 10.0.0.0/8 (prod) "internal"
Prefix 10.0.0.0/24 (prod) active site FSN1 vlan 100 (mgmt)
Cache prod/sw1
```
All NetBox instances are queried; prefixes are listed from the widest to the
most specific. The exit code is 1 when nothing is found. A failing instance is
reported as a warning without hiding the answers of the others.
### DNS names and links
Customers and colleagues often know a host by a DNS name such as
`mx123.webseite.de` that is not the device or VM name in NetBox. When netssh
finds a name neither in NetBox nor in the cache, it resolves it through DNS,
looks the addresses up in NetBox (and the cache) and suggests the hosts that
own them:
```
$ netssh mx123.webseite.de
netssh: "mx123.webseite.de" is not in NetBox or the cache. DNS: mx123.webseite.de → 203.0.113.5
1) prod/web07 203.0.113.5 on eth0 (NetBox)
2) connect directly to mx123.webseite.de
Choose [1-2, Enter = 1, q = cancel]:
Save shortcut "mx123" → prod/web07 (netssh mx123, shell alias mx123)? [y/N or another name]: y
```
- Short names get their domain from `dns.domains` (see below), so `netssh mx123`
looks up `mx123.easysahre.de`. `shortcuts.domains` are not used here.
- Choosing a host connects with all of its settings (user, port, jump host,
rules). "Directly" connects to the DNS name with the global settings.
- The shortcut offer saves a **link** under `links:` in the config: from then on
`netssh mx123` connects to `prod/web07` without asking, and new shells get
the alias `mx123` (it also completes with `<Tab>`). Answer with another name
to choose it, or `n` to skip.
- Without a terminal (scripts) netssh does not choose, unless `dns.suggest:
always`: the error lists the suggestions, e.g.
`netssh prod/web07 # 203.0.113.5 on eth0 (NetBox)`.
- `netssh info` and `netssh open` use the same suggestion, and `netssh whois mx123`
also uses `dns.domains`.
```yaml
dns:
suggest: ask # ask | always (first suggestion, also in scripts) | never (no DNS lookup)
save_link: ask # ask | always (save the shortcut without asking) | never
domains: # tried in order for names without a dot
- match: "mx*" # shell glob on the typed name
domain: easysahre.de
- match: "ah*"
domain: jhfduwia.de
# - domain: example.com # without match: every name
```
A name without a dot gets the domain of every matching rule (`mx123` →
`mx123.easysahre.de`); only when no rule matches is the bare name looked up,
using the system resolver's search domains. A name with a dot is looked up as
typed. With `suggest: always` netssh connects to the first suggestion (NetBox
hosts first), or directly to the DNS name when no host owns the address. All
three settings are also in `netssh configure` → **Resolver & cache**.
Manage links directly:
```sh
netssh link add mx123 prod/web07 # or: netssh link add mx123 mx123.webseite.de
netssh link list
netssh link remove mx123
```
```yaml
links:
mx123: "prod/web07"
shop: "lab/web1"
```
A link points to a host netssh knows (NetBox or static host), not to another
link; its name must not be a static host. Links take precedence over NetBox
names. The target is fixed: if the DNS name later points elsewhere, update the
link.
### Status warning
Connecting to a host whose NetBox status is listed in `ssh.warn_status` asks first:
```
prod/web03 has NetBox status "decommissioning" — connect anyway? [y/N]
```
```yaml
ssh:
warn_status: [offline, planned, staged, failed, inventory, decommissioning] # default
# warn_status: [] # never ask
```
`--force` skips the question (`netssh --force web03`). Without a terminal
(scripts, pipes) netssh only prints a warning and connects, so automation keeps
working. `--dry-run` prints the warning as a comment. `copy-id` asks the same
question; `--ignore-status` skips it.
### TUI columns and reachability
`tui.columns` chooses what the TUI shows next to each hostname, in this order:
```yaml
tui:
columns: [reachability, ip, status, site, platform, tags]
reachability_timeout: 300 # ms, only used with the reachability column
```
```
✓ ★ prod/sw1 10.0.0.7 site:fsn1 platform:junos #core
✗ prod/web03 10.0.2.3 [decommissioning] site:nbg1 platform:ubuntu-24-04
```
| Column | Shows |
|---|---|
| `alias` | shortcut alias (`→ fsnbx1`), with `shortcuts.show` |
| `ip` | the address from the cache or NetBox |
| `kind` | `[device]`, `[vm]` or `[static]` |
| `source` | `[live]`, `[static]`, `[cache 5m]`, `stale` |
| `status` | `[offline]` etc. — only when the NetBox status is not `active` |
| `site`, `role`, `platform`, `tenant`, `cluster` | `site:fsn1` — the slug, like in the `Ctrl+F` filter |
| `location` | `⌂ FSN1 › Building A › Room 2.04 › R12 › U20` — site, every nested location, rack and lowest rack unit |
| `tags` | `#prod #web` |
| `reachability` | `✓` / `✗` before the name: TCP check of the SSH port |
Without `tui.columns` the TUI shows `[alias, ip, source, status]`; `columns: []`
shows only the names. Empty values are left out. `netssh configure` →
**History & activity logging** offers the same choice.
The **reachability check is optional** and off by default, because it opens a
TCP connection to every listed host. With the `reachability` column, every host
in the result list is probed on its SSH port (default port, or the static host's
port), in parallel and with `tui.reachability_timeout`. `✓` means the port
answers, `✗` that it does not. Hosts behind a jump host (`proxy_jump`,
`ProxyCommand`) cannot be checked from your machine and get no mark. Each host
is probed once per TUI session.
### Address fallback
```yaml
resolver:
strategies: [management_subnet, primary_ip]
fallback: true
fallback_timeout: 1000 # ms per address
```
With `resolver.fallback`, netssh checks the chosen address before connecting
(ssh, sftp, scp, tunnel). If it does not answer on the SSH port, netssh asks
NetBox for the addresses of all strategies (plus the primary IPv4 and IPv6) and
connects to the first one that answers:
```
netssh: 10.10.0.7 does not answer on port 22, using 192.0.2.7 (primary_ip)
```
The fallback address is used for this connection only; the cache keeps the
address of the configured order. Static hosts, hosts behind a jump host and
`--dry-run` are not checked. When no address answers, netssh still tries the
original one, so ssh reports the actual error.
### Rules by site, role, platform, tenant and status
`ssh.rules[].match` and `commands.*.match` also select by NetBox attributes
(name or slug, case-insensitive; status by value):
```yaml
ssh:
rules:
- match: {platform: junos}
host_key_checking: accept-new
options:
KexAlgorithms: +diffie-hellman-group14-sha1
HostKeyAlgorithms: +ssh-rsa
- match: {site: fsn1, role: core-switch}
proxy_jump: jump-fsn1.example.com
- match: {tenant: customer-a}
options: {User: customer-a} # any layered key
commands:
junos-cli:
args: [ssh, -t, "{address}", cli]
match: {platform: junos, status: active}
```
All selectors of a match must apply. `netssh explain HOST` lists the matching
rule numbers and the host's attributes.
### ssh-copy-id
```sh
netssh copy-id web01
netssh copy-id -i ~/.ssh/id_ed25519.pub tag:lab
netssh copy-id -l root cluster:pve-fsn1 --kind vm
netssh copy-id --dry-run @k8s # print the ssh-copy-id commands
```
Runs `ssh-copy-id` for each host with the same address, user, port, jump host
and `-o` options as `netssh HOST` (a jump host is passed as `-o ProxyJump=`,
since ssh-copy-id has no `-J`). Selectors work like for `netssh multi`. Hosts
run one after another so password prompts stay readable; a failing host does
not stop the others, and the exit code is 1 if any failed. `-f` and `-n` are
passed on to ssh-copy-id.
### known_hosts cleanup
When a live lookup or `netssh cache refresh` finds a new address for a host,
netssh says so:
```
netssh: address of web01 changed from 10.0.0.5 to 10.0.0.9
Remove the known_hosts entry of the old address 10.0.0.5? [y/N]
```
After a host was re-installed (new host key, same address), remove its keys with:
```sh
netssh known-hosts reset web01 # asks first; --yes for scripts
netssh known-hosts reset --dry-run web01 # print the ssh-keygen -R commands
```
Removed are the hostname, the current address, the previously cached address,
and `[name]:port` / `[address]:port` for a non-standard port, using
`ssh-keygen -R` (which keeps `known_hosts.old`). A `UserKnownHostsFile` from
`ssh.options` is honoured.
### Exports: Ansible inventory and ssh_config
```sh
netssh export ansible > inventory.yml # YAML (default)
netssh export ansible --format ini -o hosts.ini # INI
netssh export ansible --group-by site,role,platform # choose groups
netssh export ansible --tag prod --status active --no-static
netssh export ssh-config -o ~/.ssh/netssh.conf # Host blocks for other tools
```
Exports read the cache (run `netssh cache refresh` first) including static hosts.
Filters: `--tag`, `--kind`, `--instance`, `--status`, `--no-static`. A hostname
that exists in several instances is exported as `instance-name`.
**Ansible.** Each host gets `ansible_host` (the address netssh connects to),
`ansible_user`, `ansible_port` (if not 22) and, with a jump host,
`ansible_ssh_common_args: -o ProxyJump=…`. NetBox hosts additionally get
`netbox_instance`, `netbox_kind`, `netbox_status`, `netbox_site`, `netbox_role`,
`netbox_platform`, `netbox_tenant`, `netbox_cluster`, `netbox_location`
(`Building A/Room 2.04`), `netbox_rack`, `netbox_position`, `netbox_id` and
`netbox_tags` (`--no-vars` leaves them out). Groups are named
`<attribute>_<value>` such as `tag_prod`, `site_fsn1`, `platform_junos`;
`--group-by` accepts `tag, site, location, rack, role, platform, tenant, kind,
instance, cluster, status` (default `tag,site,role,platform,kind`) or `none`.
`location` puts a host into a group for every level, e.g. `location_building_a`
and `location_room_2_04`.
```yaml
all:
hosts:
sw1:
ansible_host: 10.0.0.7
ansible_user: admin
ansible_ssh_common_args: -o ProxyJump=jump.example.com
netbox_site: FSN1
netbox_platform: Junos
children:
platform_junos:
hosts:
sw1: {}
```
```ini
[all]
sw1 ansible_host=10.0.0.7 ansible_user=admin ansible_ssh_common_args="-o ProxyJump=jump.example.com" netbox_site=FSN1
[platform_junos]
sw1
```
In INI, `netbox_tags` is a comma-separated string, since INI has no lists.
**ssh_config.** One `Host` block per host with `HostName`, `User`, `Port`,
`ProxyJump`, host key checking, `AddressFamily` and `ssh.options`; shortcut
aliases become extra Host names (`--no-aliases` to skip). Include the file once
from `~/.ssh/config` with `Include ~/.ssh/netssh.conf`. `extra_args`, forwards
and hooks have no ssh_config equivalent and are not exported.
### Keyring tokens
```sh
netssh token migrate # move all tokens from netssh.yaml into the keyring
netssh token set prod # store a token (asked without echo)
echo "$TOKEN" | netssh token set prod
netssh token status # where each instance's token comes from
netssh token delete prod
```
Tokens are stored in the system keyring — Secret Service (GNOME Keyring,
KWallet) on Linux, Keychain on macOS — under the service `netssh` with the
instance name as account (`default` for the unnamed `netbox:` instance). The
config then contains `token: keyring`:
```yaml
netboxes:
- name: prod
url: https://netbox.example.com
token: keyring
```
`netssh doctor` checks that every keyring token can be read. On machines without
a keyring (servers, containers) keep the token in the file or use
`NETSSH_NETBOX_TOKEN`.
## Recipes ## Recipes
**Everything through a bastion, except the bastion itself** **Everything through a bastion, except the bastion itself**
+191
View File
@@ -0,0 +1,191 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
)
type batchRetry struct {
Command string
Hosts []string
Extra []string
}
type batchResult struct {
Host string
Code int
}
var batchExecutable = os.Executable
func batchPath() string {
return filepath.Join(filepath.Dir(config.Path()), "netssh", "last-failed.json")
}
func batchCmd() *cobra.Command {
var parallel int
var retry, yes, dry bool
cmd := &cobra.Command{Use: "batch COMMAND HOST... [-- EXTRA_ARGS...]", Short: "Run a configured command on hosts with bounded parallelism", RunE: func(cmd *cobra.Command, args []string) error {
if parallel < 1 || parallel > 64 {
return fmt.Errorf("parallel must be between 1 and 64")
}
cfg, err := config.Load()
if err != nil {
return err
}
work := batchRetry{}
if retry {
if len(args) > 0 {
return fmt.Errorf("--retry-failed takes no positional arguments")
}
data, err := os.ReadFile(batchPath())
if err != nil {
return err
}
if err = json.Unmarshal(data, &work); err != nil {
return err
}
} else {
split := cmd.ArgsLenAtDash()
if split >= 0 {
work.Extra = args[split:]
args = args[:split]
}
if len(args) < 2 {
return fmt.Errorf("specify COMMAND and at least one HOST")
}
work.Command, work.Hosts = args[0], args[1:]
}
command, ok := cfg.Commands[work.Command]
if !ok {
return fmt.Errorf("unknown command %q", work.Command)
}
if len(work.Hosts) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No failed hosts to retry.")
return nil
}
// Resolve and validate the entire list before launching any action.
var targets []string
seen := map[string]bool{}
for _, target := range work.Hosts {
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
if !command.Allowed(commandHost(h)) {
return fmt.Errorf("%s is not allowed on %s", work.Command, h.Name)
}
if !seen[h.Name] {
targets = append(targets, h.Name)
seen[h.Name] = true
}
}
if command.Confirm && !dry {
if err := confirmAction(fmt.Sprintf("Run %s on %d hosts", work.Command, len(targets)), yes); err != nil {
return err
}
}
executable, err := batchExecutable()
if err != nil {
return err
}
// Temporary output files bound memory even for very verbose commands.
dir, err := os.MkdirTemp("", "netssh-batch-")
if err != nil {
return err
}
defer os.RemoveAll(dir)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
jobs := make(chan int)
results := make(chan batchResult, len(targets))
var wg sync.WaitGroup
var output sync.Mutex
for n := 0; n < parallel; n++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
host := targets[i]
if ctx.Err() != nil {
results <- batchResult{host, 130}
continue
}
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] starting\n", host)
output.Unlock()
f, err := os.CreateTemp(dir, "output-")
if err != nil {
results <- batchResult{host, 1}
continue
}
argv := []string{executable, "run", "--yes"}
if dry {
argv = append(argv, "--dry-run")
}
argv = append(argv, work.Command, "--", host)
argv = append(argv, work.Extra...)
r := runner.Run(ctx, argv, runner.Options{Stdout: f, Stderr: f})
f.Close()
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] exit=%d duration=%s\n", host, r.Code, r.Duration.Round(time.Millisecond))
read, err := os.Open(f.Name())
if err == nil {
_, _ = io.Copy(cmd.OutOrStdout(), read)
read.Close()
}
output.Unlock()
results <- batchResult{host, r.Code}
}
}()
}
for i := range targets {
jobs <- i
}
close(jobs)
wg.Wait()
close(results)
failed := map[string]bool{}
for r := range results {
if r.Code != 0 {
failed[r.Host] = true
}
}
work.Hosts = nil
for _, host := range targets {
if failed[host] {
work.Hosts = append(work.Hosts, host)
}
}
if !dry {
data, _ := json.Marshal(work)
if err := os.MkdirAll(filepath.Dir(batchPath()), 0700); err != nil {
return err
}
if err := storage.WriteFile(batchPath(), data, 0600); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "%d succeeded, %d failed\n", len(targets)-len(failed), len(failed))
if len(failed) > 0 {
return fmt.Errorf("batch failed; retry with netssh batch --retry-failed")
}
return nil
}}
cmd.Flags().IntVar(&parallel, "parallel", 4, "Maximum simultaneous hosts (1-64)")
cmd.Flags().BoolVar(&retry, "retry-failed", false, "Repeat failed targets from the last batch")
cmd.Flags().BoolVar(&yes, "yes", false, "Confirm the batch action")
cmd.Flags().BoolVar(&dry, "dry-run", false, "Resolve and print commands without running")
return cmd
}
+217
View File
@@ -0,0 +1,217 @@
package main
import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/charmbracelet/x/term"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
// stdinIsTerminal is replaced in tests.
var stdinIsTerminal = func() bool { return term.IsTerminal(os.Stdin.Fd()) }
// confirmStatus asks before connecting to a host whose NetBox status is listed
// in ssh.warn_status. Without a terminal it only warns, so scripts keep working.
func confirmStatus(cfg *config.Config, host resolvedHost, force bool) error {
if force || !cfg.SSH.WarnsStatus(host.Status) {
return nil
}
message := fmt.Sprintf("%s has NetBox status %q", host.Name, host.Status)
if !stdinIsTerminal() {
fmt.Fprintf(os.Stderr, "netssh: warning: %s\n", message)
return nil
}
if err := confirmAction(message+" — connect anyway", false); err != nil {
return fmt.Errorf("%s: %w (skip this question with --force)", host.Name, err)
}
return nil
}
// connectPort returns the port given in args (-p for ssh, -P for sftp and scp,
// or -o Port=), else 22. The default port is already in args at this point.
func connectPort(client internalssh.Client, args []string, dests []int) int {
end := len(args)
if len(dests) > 0 && dests[0] <= len(args) {
end = dests[0]
}
flag := client.PortArgs("")[0]
for i := 0; i < end; i++ {
arg := args[i]
value := ""
switch {
case arg == flag && i+1 < end:
value = args[i+1]
case strings.HasPrefix(arg, flag) && len(arg) > len(flag):
value = arg[len(flag):]
case arg == "-o" && i+1 < end:
if key, v, ok := strings.Cut(args[i+1], "="); ok && strings.EqualFold(strings.TrimSpace(key), "port") {
value = v
}
}
if port, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && port > 0 && port <= 65535 {
return port
}
}
return 22
}
// reachable reports whether address accepts TCP connections on port.
func reachable(address string, port int, timeout time.Duration) bool {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout)
if err != nil {
return false
}
_ = conn.Close()
return true
}
// usesJumpHost reports whether the connection goes through a jump host, so
// the target address cannot be probed from this machine.
func usesJumpHost(opts config.SSHOptions, flags internalssh.WrapperFlags) bool {
if flags.NoJump {
return false
}
return flags.Jump != "" || (opts.ProxyJump != "" && !strings.EqualFold(opts.ProxyJump, "none")) || opts.Options["proxycommand"] != ""
}
// fallbackProbe and fallbackCandidates are replaced in tests.
var (
fallbackProbe = reachable
fallbackCandidates = netboxCandidates
)
// applyFallback keeps host.IP when it answers on the SSH port. Otherwise it
// tries the addresses the other resolver strategies find and connects to the
// first one that answers, with resolver.fallback enabled.
func applyFallback(cfg *config.Config, host resolvedHost, opts config.SSHOptions, flags internalssh.WrapperFlags, port int) resolvedHost {
if !cfg.Resolver.Fallback || host.Kind == config.StaticKind || usesJumpHost(opts, flags) {
return host
}
timeout := cfg.Resolver.FallbackTimeoutDuration()
if fallbackProbe(host.IP, port, timeout) {
return host
}
candidates, err := fallbackCandidates(cfg, host)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s does not answer on port %d and no other address is known: %v\n", host.IP, port, err)
return host
}
for _, candidate := range candidates {
if candidate.Address == host.IP || !internalssh.ValidAddress(candidate.Address) {
continue
}
if fallbackProbe(candidate.Address, port, timeout) {
fmt.Fprintf(os.Stderr, "netssh: %s does not answer on port %d, using %s (%s)\n", host.IP, port, candidate.Address, candidate.Strategy)
host.IP = candidate.Address
return host
}
}
fmt.Fprintf(os.Stderr, "netssh: no address of %s answers on port %d; trying %s anyway\n", host.Name, port, host.IP)
return host
}
// netboxCandidates looks the host up again and lists every strategy's address.
func netboxCandidates(cfg *config.Config, host resolvedHost) ([]resolver.Candidate, error) {
if !cfg.HasNetBox() {
return nil, fmt.Errorf("no NetBox configured")
}
client := newNetBoxClient(cfg)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
target, err := client.FindHost(ctx, host.Name, host.Kind)
if err != nil {
return nil, err
}
chain, err := resolver.New(cfg.Resolver)
if err != nil {
return nil, err
}
return chain.Candidates(ctx, &target, client)
}
// knownHostsKeys lists the known_hosts names ssh may have stored for a host.
func knownHostsKeys(name string, addresses []string, port int) []string {
seen := map[string]bool{}
var keys []string
add := func(key string) {
if key == "" || seen[strings.ToLower(key)] {
return
}
seen[strings.ToLower(key)] = true
keys = append(keys, key)
if port != 22 {
keys = append(keys, "["+key+"]:"+strconv.Itoa(port))
}
}
_, bare := netbox.SplitTarget(name)
add(bare)
for _, address := range addresses {
add(address)
}
return keys
}
// knownHostsFile returns the first UserKnownHostsFile configured for the
// host, or "" for ssh-keygen's default (~/.ssh/known_hosts).
func knownHostsFile(opts config.SSHOptions) string {
fields := strings.Fields(opts.Options["userknownhostsfile"])
if len(fields) == 0 || fields[0] == "/dev/null" {
return ""
}
file := fields[0]
if rest, ok := strings.CutPrefix(file, "~/"); ok {
if home, err := os.UserHomeDir(); err == nil {
file = filepath.Join(home, rest)
}
}
return file
}
// removeKnownHosts runs ssh-keygen -R for every key. ssh-keygen keeps a
// known_hosts.old backup of the previous file.
var removeKnownHosts = func(keys []string, file string) error {
for _, key := range keys {
args := []string{"-R", key}
if file != "" {
args = append(args, "-f", file)
}
cmd := exec.Command("ssh-keygen", args...)
cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("ssh-keygen -R %s: %w", key, err)
}
}
return nil
}
// offerKnownHostsCleanup reports a changed NetBox address and, in a terminal,
// offers to remove the host key stored for the old address.
func offerKnownHostsCleanup(opts config.SSHOptions, host resolvedHost, port int) {
fmt.Fprintf(os.Stderr, "netssh: address of %s changed from %s to %s\n", host.Name, host.PreviousIP, host.IP)
if opts.HostKeyChecking == "off" {
return
}
keys := knownHostsKeys("", []string{host.PreviousIP}, port)
if !stdinIsTerminal() {
fmt.Fprintf(os.Stderr, "netssh: remove the old host key with: netssh known-hosts reset %s\n", host.Name)
return
}
if confirmAction("Remove the known_hosts entry of the old address "+host.PreviousIP, false) != nil {
return
}
if err := removeKnownHosts(keys, knownHostsFile(opts)); err != nil {
fmt.Fprintf(os.Stderr, "netssh: %v\n", err)
}
}
+186
View File
@@ -0,0 +1,186 @@
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
type copyIDFlags struct {
identity, user, kind, jump string
force, check, dryRun, yes bool
noJump, ignoreStatus bool
}
func copyIDCmd() *cobra.Command {
var f copyIDFlags
cmd := &cobra.Command{
Use: "copy-id [flags] HOST|tag:TAG|cluster:NAME|@GROUP...",
Short: "Install your public key on hosts with ssh-copy-id",
Long: `Run ssh-copy-id for each host with the address, user, port, jump host and
SSH options netssh would use to connect. Hosts are given like for netssh multi:
names, tag:TAG, cluster:NAME (devices; --kind vm|all for VMs) or @GROUP.
Hosts run one after another, so password prompts stay readable. A failing
host does not stop the others; the exit code is 1 if any host failed.`,
Example: ` netssh copy-id web01
netssh copy-id -i ~/.ssh/id_ed25519.pub tag:lab
netssh copy-id --dry-run @k8s`,
Args: cobra.MinimumNArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return multiCompletions(cfg, toComplete)
},
RunE: func(cmd *cobra.Command, args []string) error {
return runCopyID(loadConfigOrSetup(), args, f)
},
}
cmd.Flags().StringVarP(&f.identity, "identity", "i", "", "Public key file to install (ssh-copy-id -i)")
cmd.Flags().StringVarP(&f.user, "user", "l", "", "Login user for every host")
cmd.Flags().StringVar(&f.kind, "kind", "", "Host kind for tag: and cluster: — device, vm, or all")
cmd.Flags().StringVar(&f.jump, "jump", "", "Jump host for every host")
cmd.Flags().BoolVar(&f.noJump, "no-jump", false, "Disable jump hosts")
cmd.Flags().BoolVarP(&f.force, "force", "f", false, "Install the key even if it seems present (ssh-copy-id -f)")
cmd.Flags().BoolVarP(&f.check, "check", "n", false, "Only show which keys would be installed (ssh-copy-id -n)")
cmd.Flags().BoolVar(&f.dryRun, "dry-run", false, "Print the ssh-copy-id commands without running them")
cmd.Flags().BoolVarP(&f.yes, "yes", "y", false, fmt.Sprintf("Run for more than %d hosts without asking", maxHostsWithoutConfirm))
cmd.Flags().BoolVar(&f.ignoreStatus, "ignore-status", false, "Do not ask about hosts with a NetBox status in ssh.warn_status")
_ = cmd.RegisterFlagCompletionFunc("kind", cobra.FixedCompletions([]cobra.Completion{"device", "vm", "all"}, cobra.ShellCompDirectiveNoFileComp))
return cmd
}
func runCopyID(cfg *config.Config, selectors []string, f copyIDFlags) error {
if f.jump != "" && f.noJump {
return errors.New("--jump and --no-jump are mutually exclusive")
}
switch f.kind {
case "", "device", "vm", "all":
default:
return fmt.Errorf("--kind must be device, vm, or all")
}
if strings.HasPrefix(f.user, "-") || strings.ContainsAny(f.user, " \t\n@") {
return fmt.Errorf("invalid user %q", f.user)
}
if strings.HasPrefix(f.jump, "-") {
return fmt.Errorf("--jump: invalid host %q", f.jump)
}
c := newCache(cfg)
_ = c.Load()
targets, warnings, err := expandSelectors(cfg, c, selectors, f.kind)
for _, warning := range warnings {
fmt.Fprintln(os.Stderr, "netssh: warning: "+warning)
}
if err != nil {
return err
}
if len(targets) > maxHostsWithoutConfirm && !f.yes && !f.dryRun {
if err := confirmAction(fmt.Sprintf("Run ssh-copy-id for %d hosts", len(targets)), false); err != nil {
return err
}
}
var failed []string
for _, target := range targets {
h, err := resolveTargetE(cfg, target, false)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", target, err)
failed = append(failed, target)
continue
}
if !f.dryRun {
if err := confirmStatus(cfg, h, f.ignoreStatus); err != nil {
fmt.Fprintf(os.Stderr, "netssh: skipping %v\n", err)
failed = append(failed, target)
continue
}
}
argv, err := copyIDArgv(cfg, h, f)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", target, err)
failed = append(failed, target)
continue
}
if f.dryRun {
fmt.Println(internalssh.Quote(argv))
continue
}
fmt.Fprintf(os.Stderr, "==> %s (%s)\n", h.Name, h.IP)
if err := runCopyIDCommand(argv); err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", h.Name, err)
failed = append(failed, h.Name)
}
}
if len(failed) > 0 {
return fmt.Errorf("ssh-copy-id failed for %d of %d hosts: %s", len(failed), len(targets), strings.Join(failed, " "))
}
return nil
}
// runCopyIDCommand is replaced in tests.
var runCopyIDCommand = func(argv []string) error {
path, err := exec.LookPath(argv[0])
if err != nil {
return fmt.Errorf("%s not found in PATH (it ships with OpenSSH): %w", argv[0], err)
}
cmd := exec.Command(path, argv[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
return cmd.Run()
}
// copyIDArgv builds the ssh-copy-id command for a resolved host. The
// connection options come from the same code that builds ssh commands, so
// the key lands where netssh HOST connects to. ssh-copy-id passes -o and -p
// on to ssh but has no -J, so a jump host becomes -o ProxyJump=.
func copyIDArgv(cfg *config.Config, h resolvedHost, f copyIDFlags) ([]string, error) {
if !internalssh.ValidAddress(h.IP) {
return nil, fmt.Errorf("refusing address %q", h.IP)
}
user, port := hostDefaults(cfg, h)
if f.user != "" {
user = f.user
}
_, name := netbox.SplitTarget(h.Name)
dest := name
if user != "" {
dest = user + "@" + name
}
var args []string
if port > 0 && port != 22 {
args = append(args, "-p", strconv.Itoa(port))
}
args = append(args, dest)
opts := hostOptions(cfg, h)
opts.ExtraArgs, opts.Forwards = nil, nil
result := internalssh.SSH.Apply(args, []int{len(args) - 1}, internalssh.Host{Name: name, IP: h.IP}, opts, internalssh.WrapperFlags{Jump: f.jump, NoJump: f.noJump})
argv := []string{"ssh-copy-id"}
if f.identity != "" {
argv = append(argv, "-i", f.identity)
}
if f.force {
argv = append(argv, "-f")
}
if f.check {
argv = append(argv, "-n")
}
for i := 0; i < len(result.Args); i++ {
if result.Args[i] == "-J" && i+1 < len(result.Args) {
argv = append(argv, "-o", "ProxyJump="+result.Args[i+1])
i++
continue
}
argv = append(argv, result.Args[i])
}
return argv, nil
}
+301
View File
@@ -0,0 +1,301 @@
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
// dnsSuggestion is a host that owns an address the queried name resolves to.
type dnsSuggestion struct {
target string // host selector, e.g. prod/web07
reason string // e.g. "203.0.113.5 on eth0 (NetBox)"
}
// dnsMatch is what a DNS lookup of an unknown name found.
type dnsMatch struct {
name string // the DNS name that resolved, e.g. mx123.webseite.de
addresses []string // its addresses
suggestions []dnsSuggestion
}
// offerLinkFunc is offerLink; link add replaces it to avoid a second question.
// The first argument is dns.save_link.
var offerLinkFunc = offerLink
// promptInput is replaced in tests.
var promptInput io.Reader = os.Stdin
// promptReader buffers promptInput once, so that consecutive questions do
// not lose answers that a previous reader had already buffered.
var (
promptReader *bufio.Reader
promptSource io.Reader
)
func readAnswer() (string, error) {
if promptReader == nil || promptSource != promptInput {
promptReader, promptSource = bufio.NewReader(promptInput), promptInput
}
line, err := promptReader.ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
return strings.TrimSpace(line), nil
}
// dnsNames lists the DNS names to try for query, following dns.domains.
func dnsNames(cfg *config.Config, query string) []string {
if !plainName(query) {
return nil
}
return cfg.DNS.Names(query)
}
// lookupDNS resolves the first of names that has addresses.
func lookupDNS(ctx context.Context, names []string) (string, []string) {
for _, name := range names {
addresses, err := lookupHost(ctx, name)
if err == nil && len(addresses) > 0 {
return name, addresses
}
}
return "", nil
}
// findDNSMatch resolves query through DNS and finds the hosts in NetBox and
// the cache that own the addresses. It returns nil when DNS knows no address.
func findDNSMatch(ctx context.Context, cfg *config.Config, query string) *dnsMatch {
if source, _ := netbox.SplitTarget(query); source != "" {
return nil
}
name, addresses := lookupDNS(ctx, dnsNames(cfg, query))
if name == "" {
return nil
}
match := &dnsMatch{name: name, addresses: addresses}
seen := map[string]bool{}
add := func(target, reason string) {
if target != "" && !seen[strings.ToLower(target)] {
seen[strings.ToLower(target)] = true
match.suggestions = append(match.suggestions, dnsSuggestion{target: target, reason: reason})
}
}
if cfg.HasNetBox() {
client := newNetBoxClient(cfg)
for _, address := range addresses {
owners, err := client.LookupIP(ctx, address)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: warning: %v\n", err)
}
for _, owner := range owners {
reason := address
if owner.Interface != "" {
reason += " on " + owner.Interface
}
add(owner.Target(), reason+" (NetBox)")
}
}
}
c := newCache(cfg)
_ = c.Load()
entries := c.All()
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
for _, address := range addresses {
for _, e := range entries {
if e.IP == address {
source := "cache"
if e.Static {
source = "static host"
}
add(e.Name, address+" ("+source+")")
}
}
}
return match
}
// resolveOrSuggest resolves host like resolveTargetE. When neither NetBox nor
// the cache know it, the name is resolved through DNS and the hosts owning
// its address are offered, in a terminal, together with a direct connection
// to the DNS name. Without a terminal the suggestion is part of the error.
func resolveOrSuggest(cfg *config.Config, host string, record bool) (resolvedHost, error) {
resolved, err := resolveTargetE(cfg, host, record)
if err == nil || !errors.Is(err, netbox.ErrHostNotFound) || cfg.DNS.SuggestMode() == config.DNSNever {
return resolved, err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
match := findDNSMatch(ctx, cfg, host)
if match == nil {
return resolved, err
}
var (
choice string
ok bool
promptErr error
)
switch {
case cfg.DNS.SuggestMode() == config.DNSAlways:
choice, ok = match.first(host)
case !stdinIsTerminal():
return resolved, fmt.Errorf("%w\n%s", err, match.describe())
default:
choice, ok, promptErr = chooseDNSSuggestion(host, match)
}
if promptErr != nil {
return resolved, promptErr
}
if !ok {
return resolved, errors.New("cancelled")
}
if choice == "" {
if !internalssh.ValidAddress(match.name) {
return resolved, fmt.Errorf("refusing DNS name %q", match.name)
}
return resolvedHost{Name: host, Kind: "dns", IP: match.name, Origin: "dns"}, nil
}
resolved, err = resolveTargetE(cfg, choice, record)
if err != nil {
return resolved, err
}
offerLinkFunc(cfg.DNS.SaveLinkMode(), host, resolved.Name)
return resolved, nil
}
// first takes the first suggestion for dns.suggest: always, or the DNS name
// itself when no host owns the address.
func (m *dnsMatch) first(query string) (string, bool) {
if len(m.suggestions) == 0 {
fmt.Fprintf(os.Stderr, "netssh: %s → %s (%s), no host owns it; connecting directly (dns.suggest: always)\n", query, m.name, strings.Join(m.addresses, ", "))
return "", true
}
s := m.suggestions[0]
fmt.Fprintf(os.Stderr, "netssh: %s → %s, %s: connecting to %s (dns.suggest: always)\n", query, m.name, s.reason, s.target)
return s.target, true
}
// describe renders the DNS result and the owning hosts for an error message.
func (m *dnsMatch) describe() string {
var b strings.Builder
fmt.Fprintf(&b, "DNS: %s → %s", m.name, strings.Join(m.addresses, ", "))
if len(m.suggestions) == 0 {
fmt.Fprintf(&b, "; no host in NetBox or the cache has this address")
return b.String()
}
for _, s := range m.suggestions {
fmt.Fprintf(&b, "\n netssh %s # %s", s.target, s.reason)
}
return b.String()
}
// chooseDNSSuggestion asks which host to connect to. It returns the chosen
// target, "" for a direct connection to the DNS name, and false on cancel.
func chooseDNSSuggestion(query string, m *dnsMatch) (string, bool, error) {
fmt.Fprintf(os.Stderr, "netssh: %q is not in NetBox or the cache. DNS: %s → %s\n", query, m.name, strings.Join(m.addresses, ", "))
if len(m.suggestions) == 0 {
fmt.Fprintln(os.Stderr, "No host in NetBox or the cache has this address.")
}
for i, s := range m.suggestions {
fmt.Fprintf(os.Stderr, " %d) %s %s\n", i+1, s.target, s.reason)
}
direct := len(m.suggestions) + 1
fmt.Fprintf(os.Stderr, " %d) connect directly to %s\n", direct, m.name)
fmt.Fprintf(os.Stderr, "Choose [1-%d, Enter = 1, q = cancel]: ", direct)
answer, err := readAnswer()
if err != nil {
return "", false, err
}
switch {
case answer == "":
answer = "1"
case strings.EqualFold(answer, "q"):
return "", false, nil
}
n, convErr := strconv.Atoi(answer)
if convErr != nil || n < 1 || n > direct {
return "", false, fmt.Errorf("invalid choice %q", answer)
}
if n == direct {
return "", true, nil
}
return m.suggestions[n-1].target, true, nil
}
// linkName proposes a link name for what the user typed: the first label of
// a DNS name ("mx123" for mx123.webseite.de), else the input.
func linkName(query string) string {
if first, _, ok := strings.Cut(query, "."); ok && first != "" {
return strings.ToLower(first)
}
return strings.ToLower(query)
}
// offerLink asks whether to save query as a link to target, so that the next
// netssh NAME (and the shell alias NAME) connects without asking.
func offerLink(mode, query, target string) {
name := linkName(query)
if strings.EqualFold(name, target) || mode == config.DNSNever {
return
}
if mode == config.DNSAlways {
if err := saveLink(name, target); err != nil {
fmt.Fprintf(os.Stderr, "netssh: shortcut not saved: %v\n", err)
return
}
fmt.Fprintf(os.Stderr, "netssh: saved shortcut %s → %s (dns.save_link: always)\n", name, target)
return
}
if !stdinIsTerminal() {
return
}
fmt.Fprintf(os.Stderr, "Save shortcut %q → %s (netssh %s, shell alias %s)? [y/N or another name]: ", name, target, name, name)
answer, err := readAnswer()
if err != nil {
return
}
switch strings.ToLower(answer) {
case "", "n", "no":
return
case "y", "yes", "j", "ja":
default:
name = strings.ToLower(answer)
}
if err := saveLink(name, target); err != nil {
fmt.Fprintf(os.Stderr, "netssh: shortcut not saved: %v\n", err)
return
}
fmt.Fprintf(os.Stderr, "netssh: saved; netssh %s now connects to %s (new shells also get the alias %s).\n", name, target, name)
}
// saveLink adds a link to the config file and regenerates the shell aliases.
var saveLink = func(name, target string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if cfg.Links == nil {
cfg.Links = map[string]string{}
}
for key := range cfg.Links {
if strings.EqualFold(key, name) {
delete(cfg.Links, key)
}
}
cfg.Links[name] = target
if err := cfg.ValidateLinks(); err != nil {
return err
}
return saveHostsTo(cfg, os.Stderr)
}
+199
View File
@@ -0,0 +1,199 @@
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// dnsEnv: NetBox "prod" knows web07 (203.0.113.5 on eth0) but not mx123;
// DNS resolves mx123.webseite.de to 203.0.113.5.
func dnsEnv(t *testing.T, extra string) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ipam/ip-addresses/":
if r.URL.Query().Get("address") == "203.0.113.5" {
fmt.Fprint(w, `{"count":1,"results":[{"address":"203.0.113.5/24","assigned_object":{"name":"eth0","virtual_machine":{"id":7,"name":"web07"}}}]}`)
return
}
fmt.Fprint(w, `{"count":0,"results":[]}`)
case "/api/dcim/devices/", "/api/virtualization/virtual-machines/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
insightEnv(t, fmt.Sprintf("netboxes:\n - name: prod\n url: %s\n token: t\nshortcuts:\n domains: [shortcut.example]\ndns:\n domains:\n - match: \"mx*\"\n domain: webseite.de\n - match: \"ah*\"\n domain: other.example\n%s", srv.URL, extra))
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
c := cache.New(cfg.CachePath(), 3600)
c.Upsert(cache.Entry{Name: "prod/web07", IP: "203.0.113.5", Kind: "vm", ID: 7})
if err := c.Save(); err != nil {
t.Fatal(err)
}
old := lookupHost
lookupHost = func(_ context.Context, name string) ([]string, error) {
if name == "mx123.webseite.de" {
return []string{"203.0.113.5"}, nil
}
if strings.HasSuffix(name, ".shortcut.example") {
t.Errorf("shortcut domain looked up: %s", name)
}
return nil, errors.New("no such host")
}
t.Cleanup(func() { lookupHost = old })
}
func answer(t *testing.T, input string) {
t.Helper()
old := promptInput
promptInput = strings.NewReader(input)
t.Cleanup(func() { promptInput = old })
}
func TestDNSNames(t *testing.T) {
cfg := &config.Config{
Shortcuts: config.ShortcutsConfig{Domains: []string{"shortcut.example"}},
DNS: config.DNSConfig{Domains: []config.DNSDomain{
{Match: "mx*", Domain: "easysahre.de"}, {Match: "ah*", Domain: ".jhfduwia.de."}, {Match: "MX1*", Domain: "backup.de"},
}},
}
for query, want := range map[string]string{
"mx123": "mx123.easysahre.de mx123.backup.de",
"ah123": "ah123.jhfduwia.de",
"web01": "web01",
"mx123.webseite.de": "mx123.webseite.de",
} {
if got := strings.Join(dnsNames(cfg, query), " "); got != want {
t.Errorf("%s: got %q, want %q", query, got, want)
}
}
cfg.DNS.Domains = append(cfg.DNS.Domains, config.DNSDomain{Domain: "fallback.de"})
if got := strings.Join(dnsNames(cfg, "web01"), " "); got != "web01.fallback.de" {
t.Fatalf("rule without match: %q", got)
}
if dnsNames(cfg, "-oProxyCommand=x") != nil {
t.Fatal("option-like name looked up")
}
}
func TestDNSSuggestionWithoutTerminalExplains(t *testing.T) {
dnsEnv(t, "")
stubTerminal(t, false)
cfg, _ := config.Load()
_, err := resolveOrSuggest(cfg, "mx123", false)
if err == nil {
t.Fatal("must not connect without asking")
}
for _, want := range []string{"host not found", "DNS: mx123.webseite.de → 203.0.113.5", "netssh prod/web07", "203.0.113.5 on eth0 (NetBox)"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("missing %q in %v", want, err)
}
}
}
func TestDNSSuggestionChooseHostAndSaveLink(t *testing.T) {
dnsEnv(t, "")
stubTerminal(t, true)
var saved [2]string
old := saveLink
saveLink = func(name, target string) error { saved = [2]string{name, target}; return nil }
t.Cleanup(func() { saveLink = old })
answer(t, "\ny\n")
cfg, _ := config.Load()
h, err := resolveOrSuggest(cfg, "mx123.webseite.de", false)
if err != nil {
t.Fatal(err)
}
if h.Name != "prod/web07" || h.IP != "203.0.113.5" {
t.Fatalf("resolved %+v", h)
}
if saved != [2]string{"mx123", "prod/web07"} {
t.Fatalf("link %v", saved)
}
}
func TestDNSSuggestionDirectAndCancel(t *testing.T) {
dnsEnv(t, "")
stubTerminal(t, true)
cfg, _ := config.Load()
answer(t, "2\n")
h, err := resolveOrSuggest(cfg, "mx123", false)
if err != nil || h.Kind != "dns" || h.IP != "mx123.webseite.de" || h.Name != "mx123" {
t.Fatalf("direct: %+v %v", h, err)
}
answer(t, "q\n")
if _, err := resolveOrSuggest(cfg, "mx123", false); err == nil || err.Error() != "cancelled" {
t.Fatalf("cancel: %v", err)
}
answer(t, "7\n")
if _, err := resolveOrSuggest(cfg, "mx123", false); err == nil || !strings.Contains(err.Error(), "invalid choice") {
t.Fatalf("invalid: %v", err)
}
// Names DNS does not know keep the plain not-found error.
if _, err := resolveOrSuggest(cfg, "nothere", false); err == nil || strings.Contains(err.Error(), "DNS") {
t.Fatalf("unknown: %v", err)
}
}
func stubSaveLink(t *testing.T) *[][2]string {
t.Helper()
var saved [][2]string
old := saveLink
saveLink = func(name, target string) error { saved = append(saved, [2]string{name, target}); return nil }
t.Cleanup(func() { saveLink = old })
return &saved
}
func TestDNSSuggestAlwaysWorksWithoutTerminal(t *testing.T) {
dnsEnv(t, " suggest: always\n save_link: always\n")
stubTerminal(t, false)
saved := stubSaveLink(t)
cfg, _ := config.Load()
h, err := resolveOrSuggest(cfg, "mx123", true)
if err != nil || h.Name != "prod/web07" {
t.Fatalf("always: %+v %v", h, err)
}
if len(*saved) != 1 || (*saved)[0] != [2]string{"mx123", "prod/web07"} {
t.Fatalf("save_link always: %v", *saved)
}
}
func TestDNSSaveLinkNeverAndAskWithoutTerminal(t *testing.T) {
dnsEnv(t, " suggest: always\n save_link: never\n")
stubTerminal(t, false)
saved := stubSaveLink(t)
cfg, _ := config.Load()
if _, err := resolveOrSuggest(cfg, "mx123", false); err != nil || len(*saved) != 0 {
t.Fatalf("never: %v %v", *saved, err)
}
cfg.DNS.SaveLink = ""
if _, err := resolveOrSuggest(cfg, "mx123", false); err != nil || len(*saved) != 0 {
t.Fatalf("ask without terminal must not save: %v %v", *saved, err)
}
}
func TestDNSSuggestNeverSkipsLookup(t *testing.T) {
dnsEnv(t, " suggest: never\n")
stubTerminal(t, true)
looked := false
old := lookupHost
lookupHost = func(context.Context, string) ([]string, error) { looked = true; return []string{"203.0.113.5"}, nil }
t.Cleanup(func() { lookupHost = old })
cfg, _ := config.Load()
if _, err := resolveOrSuggest(cfg, "mx123", false); err == nil || looked {
t.Fatalf("never: looked=%v err=%v", looked, err)
}
}
+523
View File
@@ -0,0 +1,523 @@
package main
import (
"fmt"
"io"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"go.yaml.in/yaml/v3"
"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/storage"
)
// exportFilter selects the cached hosts to export.
type exportFilter struct {
tag, kind, instance, status string
noStatic bool
output string
}
func (f *exportFilter) register(cmd *cobra.Command) {
cmd.Flags().StringVar(&f.tag, "tag", "", "Only hosts with this tag")
cmd.Flags().StringVar(&f.kind, "kind", "", "Only this kind: device, vm, or static")
cmd.Flags().StringVar(&f.instance, "instance", "", "Only hosts of this NetBox instance")
cmd.Flags().StringVar(&f.status, "status", "", "Only hosts with this NetBox status, e.g. active")
cmd.Flags().BoolVar(&f.noStatic, "no-static", false, "Leave out static hosts (hosts:)")
cmd.Flags().StringVarP(&f.output, "output", "o", "", "Write to this file instead of stdout")
_ = cmd.RegisterFlagCompletionFunc("kind", cobra.FixedCompletions([]cobra.Completion{"device", "vm", "static"}, cobra.ShellCompDirectiveNoFileComp))
}
func (f exportFilter) matches(e cache.Entry) bool {
instance, _ := netbox.SplitTarget(e.Name)
switch {
case f.noStatic && e.Static,
f.kind != "" && !strings.EqualFold(e.Kind, f.kind),
f.instance != "" && !strings.EqualFold(instance, f.instance),
f.status != "" && !strings.EqualFold(e.Status, f.status),
f.tag != "" && !hasTag(e.Tags, f.tag):
return false
}
return true
}
// exportHost is one host with the connection settings netssh would use.
type exportHost struct {
entry cache.Entry
name string // unique inventory / Host name
address string
user string
port int
opts config.SSHOptions
}
// exportHosts loads the filtered cache entries. Hostnames that exist in
// several instances get the instance as prefix ("prod-web01"), others stay bare.
func exportHosts(cfg *config.Config, f exportFilter) ([]exportHost, error) {
c := newCache(cfg)
if err := c.Load(); err != nil {
return nil, err
}
var entries []cache.Entry
counts := map[string]int{}
for _, e := range c.All() {
if !f.matches(e) {
continue
}
entries = append(entries, e)
_, name := netbox.SplitTarget(e.Name)
counts[strings.ToLower(name)]++
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
out := make([]exportHost, 0, len(entries))
for _, e := range entries {
instance, name := netbox.SplitTarget(e.Name)
if counts[strings.ToLower(name)] > 1 && instance != "" {
name = instance + "-" + name
}
h := hostFromEntry(e, "cache")
user, port := hostDefaults(cfg, h)
out = append(out, exportHost{entry: e, name: name, address: e.IP, user: user, port: port, opts: hostOptions(cfg, h)})
}
if len(out) == 0 {
return nil, fmt.Errorf("no cached hosts match; run netssh cache refresh first")
}
return out, nil
}
// writeExport writes data to the --output file, or stdout.
func writeExport(f exportFilter, data []byte) error {
if f.output == "" || f.output == "-" {
_, err := os.Stdout.Write(data)
return err
}
if err := storage.WriteFile(f.output, data, 0o600); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Written → %s\n", f.output)
return nil
}
func exportCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "export",
Short: "Export cached hosts as Ansible inventory or ssh_config",
}
cmd.AddCommand(exportAnsibleCmd(), exportSSHConfigCmd())
return cmd
}
// ansibleGroupKeys are the attributes --group-by accepts.
var ansibleGroupKeys = []string{"tag", "site", "location", "rack", "role", "platform", "tenant", "kind", "instance", "cluster", "status"}
func exportAnsibleCmd() *cobra.Command {
var f exportFilter
var format, groupBy string
var noVars bool
cmd := &cobra.Command{
Use: "ansible",
Short: "Print an Ansible inventory (YAML or INI) of the cached hosts",
Long: `Print an Ansible inventory of the cached hosts. Every host gets ansible_host
(the address netssh connects to), ansible_user, ansible_port and, with a jump
host, ansible_ssh_common_args. NetBox attributes are added as netbox_* host
variables (disable with --no-vars).
Groups are formed from host attributes, named like tag_prod, site_fsn1,
role_router or platform_junos. Choose them with --group-by (comma-separated:
` + strings.Join(ansibleGroupKeys, ", ") + `, or none).`,
Example: ` netssh export ansible > inventory.yml
netssh export ansible --format ini --group-by site,role -o hosts.ini
netssh export ansible --tag prod --status active`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
keys, err := parseGroupBy(groupBy)
if err != nil {
return err
}
hosts, err := exportHosts(cfg, f)
if err != nil {
return err
}
inv := buildInventory(hosts, keys, !noVars)
var data []byte
switch strings.ToLower(format) {
case "yaml", "yml":
data, err = inv.yaml()
case "ini":
data = inv.ini()
default:
return fmt.Errorf("--format must be yaml or ini")
}
if err != nil {
return err
}
return writeExport(f, data)
},
}
f.register(cmd)
cmd.Flags().StringVar(&format, "format", "yaml", "Inventory format: yaml or ini")
cmd.Flags().StringVar(&groupBy, "group-by", "tag,site,role,platform,kind", "Attributes to group hosts by, or none")
cmd.Flags().BoolVar(&noVars, "no-vars", false, "Leave out the netbox_* host variables")
_ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]cobra.Completion{"yaml", "ini"}, cobra.ShellCompDirectiveNoFileComp))
return cmd
}
func parseGroupBy(value string) ([]string, error) {
if strings.EqualFold(strings.TrimSpace(value), "none") || strings.TrimSpace(value) == "" {
return nil, nil
}
var keys []string
for _, key := range strings.Split(value, ",") {
key = strings.ToLower(strings.TrimSpace(key))
valid := false
for _, known := range ansibleGroupKeys {
valid = valid || key == known
}
if !valid {
return nil, fmt.Errorf("--group-by: unknown attribute %q; use %s, or none", key, strings.Join(ansibleGroupKeys, ", "))
}
keys = append(keys, key)
}
return keys, nil
}
// inventoryVar is a host variable; list values stay lists in YAML.
type inventoryVar struct {
key string
value any // string, int, or []string
}
type inventory struct {
hosts []string
vars map[string][]inventoryVar
groups map[string][]string
}
var groupInvalid = regexp.MustCompile(`[^a-z0-9_]+`)
// groupName builds a valid Ansible group name such as site_fsn1.
func groupName(prefix, value string) string {
name := strings.Trim(groupInvalid.ReplaceAllString(strings.ToLower(value), "_"), "_")
if name == "" {
return ""
}
return prefix + "_" + name
}
func buildInventory(hosts []exportHost, groupBy []string, netboxVars bool) inventory {
inv := inventory{vars: map[string][]inventoryVar{}, groups: map[string][]string{}}
for _, h := range hosts {
e := h.entry
inv.hosts = append(inv.hosts, h.name)
vars := []inventoryVar{{"ansible_host", h.address}}
if h.user != "" {
vars = append(vars, inventoryVar{"ansible_user", h.user})
}
if h.port > 0 && h.port != 22 {
vars = append(vars, inventoryVar{"ansible_port", h.port})
}
if jump := h.opts.ProxyJump; jump != "" && !strings.EqualFold(jump, "none") {
vars = append(vars, inventoryVar{"ansible_ssh_common_args", "-o ProxyJump=" + jump})
}
instance, _ := netbox.SplitTarget(e.Name)
if netboxVars && !e.Static {
for _, pair := range [][2]string{
{"netbox_instance", instance}, {"netbox_kind", e.Kind}, {"netbox_status", e.Status},
{"netbox_site", cache.RefOf(e.Site).Name}, {"netbox_role", cache.RefOf(e.Role).Name},
{"netbox_platform", cache.RefOf(e.Platform).Name}, {"netbox_tenant", cache.RefOf(e.Tenant).Name},
{"netbox_cluster", e.Cluster}, {"netbox_location", locationNames(e.Location)},
{"netbox_rack", e.Rack}, {"netbox_position", e.Position},
} {
if pair[1] != "" {
vars = append(vars, inventoryVar{pair[0], pair[1]})
}
}
if e.ID > 0 {
vars = append(vars, inventoryVar{"netbox_id", e.ID})
}
if len(e.Tags) > 0 {
vars = append(vars, inventoryVar{"netbox_tags", append([]string(nil), e.Tags...)})
}
}
inv.vars[h.name] = vars
for _, key := range groupBy {
var values []string
switch key {
case "tag":
values = e.Tags
case "site":
values = []string{cache.RefOf(e.Site).Key()}
case "location":
// Every level, so a play can target a building or a single room.
for _, location := range e.Location {
values = append(values, location.Key())
}
case "rack":
values = []string{e.Rack}
case "role":
values = []string{cache.RefOf(e.Role).Key()}
case "platform":
values = []string{cache.RefOf(e.Platform).Key()}
case "tenant":
values = []string{cache.RefOf(e.Tenant).Key()}
case "kind":
values = []string{e.Kind}
case "instance":
values = []string{instance}
case "cluster":
values = []string{e.Cluster}
case "status":
values = []string{e.Status}
}
for _, value := range values {
if group := groupName(key, value); group != "" {
inv.groups[group] = append(inv.groups[group], h.name)
}
}
}
}
return inv
}
func (inv inventory) groupNames() []string {
names := make([]string, 0, len(inv.groups))
for name := range inv.groups {
names = append(names, name)
}
sort.Strings(names)
return names
}
func exportHeader(comment string) string {
return fmt.Sprintf("%s Generated by netssh export on %s — changes are overwritten on the next export.\n", comment, time.Now().Format(time.RFC3339))
}
// yaml renders the inventory with host variables under all.hosts and the
// groups as children of all, listing their member hosts.
func (inv inventory) yaml() ([]byte, error) {
node := func(kind yaml.Kind, value string) *yaml.Node {
n := &yaml.Node{Kind: kind, Value: value}
if kind == yaml.ScalarNode {
n.Tag = "!!str"
}
return n
}
mapping := func() *yaml.Node { return &yaml.Node{Kind: yaml.MappingNode} }
add := func(m *yaml.Node, key string, value *yaml.Node) {
m.Content = append(m.Content, node(yaml.ScalarNode, key), value)
}
hosts := mapping()
for _, name := range inv.hosts {
vars := mapping()
for _, v := range inv.vars[name] {
var value *yaml.Node
switch typed := v.value.(type) {
case int:
value = &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(typed)}
case []string:
value = &yaml.Node{Kind: yaml.SequenceNode}
for _, item := range typed {
value.Content = append(value.Content, node(yaml.ScalarNode, item))
}
default:
value = node(yaml.ScalarNode, fmt.Sprint(typed))
}
add(vars, v.key, value)
}
add(hosts, name, vars)
}
all := mapping()
add(all, "hosts", hosts)
if len(inv.groups) > 0 {
children := mapping()
for _, group := range inv.groupNames() {
members := mapping()
for _, host := range inv.groups[group] {
add(members, host, &yaml.Node{Kind: yaml.MappingNode, Style: yaml.FlowStyle})
}
g := mapping()
add(g, "hosts", members)
add(children, group, g)
}
add(all, "children", children)
}
root := mapping()
add(root, "all", all)
var b strings.Builder
b.WriteString(exportHeader("#"))
enc := yaml.NewEncoder(&b)
enc.SetIndent(2)
if err := enc.Encode(&yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return []byte(b.String()), nil
}
// ini renders host variables in [all] and one section per group. Lists such
// as netbox_tags become comma-separated strings, since INI has no lists.
func (inv inventory) ini() []byte {
var b strings.Builder
b.WriteString(exportHeader(";"))
b.WriteString("[all]\n")
for _, name := range inv.hosts {
b.WriteString(name)
for _, v := range inv.vars[name] {
value := fmt.Sprint(v.value)
if list, ok := v.value.([]string); ok {
value = strings.Join(list, ",")
}
fmt.Fprintf(&b, " %s=%s", v.key, iniQuote(value))
}
b.WriteString("\n")
}
for _, group := range inv.groupNames() {
fmt.Fprintf(&b, "\n[%s]\n", group)
for _, host := range inv.groups[group] {
b.WriteString(host + "\n")
}
}
return []byte(b.String())
}
// iniQuote quotes values that Ansible's INI parser (shlex) would split.
func iniQuote(value string) string {
if value != "" && !strings.ContainsAny(value, " \t\"'\\#;=") {
return value
}
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(value) + `"`
}
func exportSSHConfigCmd() *cobra.Command {
var f exportFilter
var noAliases bool
cmd := &cobra.Command{
Use: "ssh-config",
Short: "Print ssh_config Host blocks for the cached hosts",
Long: `Print one ssh_config Host block per cached host with the address, user, port,
jump host and SSH options netssh would use. Tools that run ssh themselves
(VS Code Remote, rsync, git, Ansible) can then reach the hosts by name.
Include the file from ~/.ssh/config:
netssh export ssh-config -o ~/.ssh/netssh.conf
echo 'Include ~/.ssh/netssh.conf' >> ~/.ssh/config # once
Shortcut aliases are added as extra Host names (disable with --no-aliases).
extra_args, forwards and hooks have no ssh_config equivalent and are skipped.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
hosts, err := exportHosts(cfg, f)
if err != nil {
return err
}
aliases := map[string]string{}
if !noAliases {
c := newCache(cfg)
_ = c.Load()
aliases = shortcutAliases(c.All(), *cfg)
}
var b strings.Builder
writeSSHConfig(&b, hosts, aliases)
return writeExport(f, []byte(b.String()))
},
}
f.register(cmd)
cmd.Flags().BoolVar(&noAliases, "no-aliases", false, "Do not add shortcut aliases as Host names")
return cmd
}
var sshConfigUnsafe = regexp.MustCompile(`[\s"#*?!,]`)
func writeSSHConfig(w io.Writer, hosts []exportHost, aliases map[string]string) {
fmt.Fprint(w, exportHeader("#"))
used := map[string]bool{}
for _, h := range hosts {
used[strings.ToLower(h.name)] = true
}
for _, h := range hosts {
if sshConfigUnsafe.MatchString(h.name) {
fmt.Fprintf(w, "\n# skipped %q: not usable as a Host name\n", h.name)
continue
}
names := []string{h.name}
if alias := aliases[strings.ToLower(h.entry.Name)]; alias != "" && !used[strings.ToLower(alias)] && !sshConfigUnsafe.MatchString(alias) {
used[strings.ToLower(alias)] = true
names = append(names, alias)
}
fmt.Fprintf(w, "\nHost %s\n", strings.Join(names, " "))
_, bare := netbox.SplitTarget(h.entry.Name)
hostName := h.address
if h.opts.Target == "hostname" && plainName(bare) {
hostName = bare
}
line := func(key, value string) {
if value != "" {
fmt.Fprintf(w, " %s %s\n", key, value)
}
}
line("HostName", hostName)
if h.opts.Target == "name" && plainName(bare) {
line("HostKeyAlias", bare)
}
line("User", h.user)
if h.port > 0 && h.port != 22 {
line("Port", strconv.Itoa(h.port))
}
if jump := h.opts.ProxyJump; jump != "" {
line("ProxyJump", jump)
}
switch h.opts.HostKeyChecking {
case "strict":
line("StrictHostKeyChecking", "yes")
case "accept-new":
line("StrictHostKeyChecking", "accept-new")
case "off":
line("StrictHostKeyChecking", "no")
line("UserKnownHostsFile", "/dev/null")
}
line("AddressFamily", h.opts.AddressFamily)
keys := make([]string, 0, len(h.opts.Options))
for key := range h.opts.Options {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
line(key, h.opts.Options[key])
}
if len(h.opts.ExtraArgs) > 0 {
fmt.Fprintf(w, " # extra_args not exported: %s\n", strings.Join(h.opts.ExtraArgs, " "))
}
}
}
var plainNamePattern = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`)
func plainName(name string) bool { return plainNamePattern.MatchString(name) }
// locationNames joins a location chain as "Building A/Room 2.04".
func locationNames(chain []config.Ref) string {
names := make([]string, 0, len(chain))
for _, location := range chain {
names = append(names, location.Name)
}
return strings.Join(names, "/")
}
+6 -2
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"fmt" "fmt"
"io"
"os" "os"
"strings" "strings"
"text/tabwriter" "text/tabwriter"
@@ -146,8 +147,11 @@ func hostsRemoveCmd() *cobra.Command {
} }
// saveHosts writes the config and regenerates the shell aliases. // saveHosts writes the config and regenerates the shell aliases.
func saveHosts(cfg *config.Config) error { func saveHosts(cfg *config.Config) error { return saveHostsTo(cfg, os.Stdout) }
if err := setup.Save(*cfg); err != nil {
// saveHostsTo writes the config, reporting to w, and regenerates the aliases.
func saveHostsTo(cfg *config.Config, w io.Writer) error {
if err := setup.SaveTo(*cfg, w); err != nil {
return err return err
} }
loaded, err := config.Load() loaded, err := config.Load()
+437
View File
@@ -0,0 +1,437 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// hostCompletion completes cached hostnames for commands taking hosts.
func hostCompletion(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
return completeHosts(toComplete), cobra.ShellCompDirectiveNoFileComp
}
// netboxHost finds the NetBox record of a host given like on the command line
// (shortcut, instance/host). The cache supplies the ID when it has one.
func netboxHost(ctx context.Context, cfg *config.Config, target string) (netbox.HostEntry, *netbox.Client, resolvedHost, error) {
h, err := resolveOrSuggest(cfg, target, false)
if err != nil {
return netbox.HostEntry{}, nil, h, err
}
switch h.Kind {
case config.StaticKind:
return netbox.HostEntry{}, nil, h, fmt.Errorf("%s is a static host (hosts:) and has no NetBox record", h.Name)
case "dns":
return netbox.HostEntry{}, nil, h, fmt.Errorf("%s (%s) is not in NetBox", h.Name, h.IP)
}
client := newNetBoxClient(cfg)
if client == nil {
return netbox.HostEntry{}, nil, h, fmt.Errorf("no NetBox is configured (netssh configure)")
}
return netboxEntry(ctx, client, h.Name, h.Kind, h.ID, h)
}
// netboxEntry completes a cached host with its NetBox ID, looking it up if needed.
func netboxEntry(ctx context.Context, client *netbox.Client, name, kind string, id int, h resolvedHost) (netbox.HostEntry, *netbox.Client, resolvedHost, error) {
source, bare := netbox.SplitTarget(name)
entry := netbox.HostEntry{Source: source, Name: bare, Kind: kind, ID: id}
if id <= 0 {
found, err := client.FindHost(ctx, name, kind)
if err != nil {
return entry, client, h, fmt.Errorf("NetBox: %w", err)
}
entry = found
}
return entry, client, h, nil
}
// openBrowser opens url with $BROWSER, open (macOS), or xdg-open.
var openBrowser = func(url string) error {
var cmd *exec.Cmd
switch browser := os.Getenv("BROWSER"); {
case browser != "":
cmd = exec.Command(browser, url)
case runtime.GOOS == "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
cmd.Stdout, cmd.Stderr = nil, nil
if err := cmd.Start(); err != nil {
return fmt.Errorf("opening browser: %w (print the URL with --print)", err)
}
return cmd.Process.Release()
}
func openCmd() *cobra.Command {
var printOnly bool
cmd := &cobra.Command{
Use: "open HOST",
Short: "Open the NetBox page of a host in the web browser",
Long: "Open the device or virtual machine page in the NetBox web interface.\nThe browser is $BROWSER, else open (macOS) or xdg-open.",
Args: cobra.ExactArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
entry, client, _, err := netboxHost(ctx, cfg, args[0])
if err != nil {
return err
}
url, err := client.WebURL(entry)
if err != nil {
return err
}
if printOnly {
fmt.Fprintln(cmd.OutOrStdout(), url)
return nil
}
fmt.Fprintf(os.Stderr, "Opening %s\n", url)
return openBrowser(url)
},
}
cmd.Flags().BoolVar(&printOnly, "print", false, "Print the URL instead of opening it")
return cmd
}
func infoCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "info HOST",
Short: "Show site, rack, role, platform, status and IP addresses of a host",
Args: cobra.ExactArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveOrSuggest(cfg, args[0], false)
if err != nil {
return err
}
out := cmd.OutOrStdout()
if h.Kind == config.StaticKind || h.Kind == "dns" {
return printStaticInfo(out, cfg, h, asJSON)
}
client := newNetBoxClient(cfg)
if client == nil {
return fmt.Errorf("no NetBox is configured (netssh configure)")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
entry, _, _, err := netboxEntry(ctx, client, h.Name, h.Kind, h.ID, h)
if err != nil {
return err
}
details, err := client.GetDetails(ctx, entry)
if err != nil && details.Name == "" {
return fmt.Errorf("NetBox: %w", err)
}
if asJSON {
return json.NewEncoder(out).Encode(map[string]any{"host": details, "connect": map[string]any{"address": h.IP, "source": h.Origin, "resolver": h.Resolver}})
}
writeDetails(out, details, h)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: %v\n", err)
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "Print JSON")
return cmd
}
func printStaticInfo(w io.Writer, cfg *config.Config, h resolvedHost, asJSON bool) error {
user, port := hostDefaults(cfg, h)
if asJSON {
return json.NewEncoder(w).Encode(map[string]any{"host": map[string]any{"name": h.Name, "kind": h.Kind, "address": h.IP, "user": user, "port": port, "tags": h.Tags}})
}
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
origin := "(static host from hosts:)"
if h.Kind == "dns" {
origin = "(DNS name, not in NetBox)"
}
fmt.Fprintf(tw, "%s\t%s\n", h.Name, origin)
row(tw, "Address", h.IP)
row(tw, "User", user)
if port > 0 {
row(tw, "Port", fmt.Sprint(port))
}
row(tw, "Tags", strings.Join(h.Tags, ", "))
return tw.Flush()
}
func row(w io.Writer, label, value string) {
if strings.TrimSpace(value) != "" {
fmt.Fprintf(w, " %s\t%s\n", label, value)
}
}
// formatDetails renders netssh info output; the TUI detail view uses it too.
func formatDetails(d netbox.HostDetails, h resolvedHost) string {
var b strings.Builder
writeDetails(&b, d, h)
return b.String()
}
func writeDetails(w io.Writer, d netbox.HostDetails, h resolvedHost) {
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
header := d.Target() + "\t(" + d.Kind
if d.Source != "" {
header += ", NetBox " + d.Source
}
fmt.Fprintln(tw, header+")")
status := d.StatusLabel
if status == "" {
status = d.Status
}
row(tw, "Status", status)
row(tw, "Site", d.Site.Name)
var locations []string
for _, location := range d.Location {
locations = append(locations, location.Name)
}
row(tw, "Location", strings.Join(locations, " › "))
row(tw, "Rack", strings.TrimSpace(d.Rack+" "+d.RackUnits()))
if len(d.Location) > 0 || d.Rack != "" {
row(tw, "Path", d.LocationPath())
}
row(tw, "Role", d.Role.Name)
row(tw, "Platform", d.Platform.Name)
row(tw, "Tenant", d.Tenant.Name)
row(tw, "Type", d.DeviceType)
row(tw, "Serial", d.Serial)
row(tw, "Asset tag", d.AssetTag)
row(tw, "Cluster", d.Cluster)
var resources []string
if d.VCPUs != "" {
resources = append(resources, d.VCPUs+" vCPU")
}
if d.MemoryMB > 0 {
resources = append(resources, fmt.Sprintf("%d MB RAM", d.MemoryMB))
}
if d.DiskGB > 0 {
resources = append(resources, fmt.Sprintf("%d GB disk", d.DiskGB))
}
row(tw, "Resources", strings.Join(resources, ", "))
row(tw, "Tags", strings.Join(d.Tags, ", "))
if h.IP != "" {
via := h.Resolver
if h.Origin != "" {
via = strings.Trim(via+", "+h.Origin, ", ")
}
connect := h.IP
if via != "" {
connect += " (" + via + ")"
}
row(tw, "Connect", connect)
}
row(tw, "URL", d.URL)
row(tw, "Description", d.Description)
_ = tw.Flush()
if len(d.IPs) == 0 {
return
}
fmt.Fprintln(w, "\nIP addresses")
tw = tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
for _, ip := range d.IPs {
mark := " "
if ip.Primary {
mark = "*"
}
extra := ip.Status
if ip.Role != "" {
extra = strings.Trim(extra+", "+ip.Role, ", ")
}
if ip.VRF != "" {
extra = strings.Trim(extra+", vrf "+ip.VRF, ", ")
}
fmt.Fprintf(tw, " %s %s\t%s\t%s\t%s\n", mark, ip.Address, orDash(ip.Interface), ip.DNSName, extra)
}
_ = tw.Flush()
}
// whoisResult is what netssh whois found for one address.
type whoisResult struct {
Address string `json:"address"`
NetBox []netbox.IPOwner `json:"netbox"`
Prefixes []netbox.PrefixInfo `json:"prefixes"`
Cached []string `json:"cached_hosts"`
}
func whoisCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "whois ADDRESS|HOSTNAME",
Short: "Find the host, interface and prefix an IP address belongs to",
Long: `Look an IP address up in every NetBox instance and in the local cache:
the device or VM and interface it is assigned to, its DNS name, and the
prefixes containing it. A hostname is resolved through DNS first.`,
Example: " netssh whois 10.20.0.15\n netssh whois mail.example.com",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
addresses, err := whoisAddresses(ctx, args[0])
if err != nil {
// A short name like mx123 may resolve with a shortcut domain.
if names := dnsNames(cfg, args[0]); len(names) > 0 && names[0] != args[0] {
if _, found := lookupDNS(ctx, names); len(found) > 0 {
addresses, err = found, nil
}
}
}
if err != nil {
return err
}
c := newCache(cfg)
_ = c.Load()
var client *netbox.Client
if cfg.HasNetBox() {
client = newNetBoxClient(cfg)
}
var results []whoisResult
var warnings []error
found := false
for _, address := range addresses {
r := whoisResult{Address: address}
for _, e := range c.All() {
if e.IP == address {
r.Cached = append(r.Cached, e.Name)
}
}
sort.Strings(r.Cached)
if client != nil {
owners, err := client.LookupIP(ctx, address)
if err != nil {
warnings = append(warnings, err)
}
r.NetBox = owners
prefixes, err := client.PrefixesContaining(ctx, address)
if err != nil {
warnings = append(warnings, err)
}
r.Prefixes = prefixes
}
found = found || len(r.NetBox) > 0 || len(r.Cached) > 0 || len(r.Prefixes) > 0
results = append(results, r)
}
for _, warning := range warnings {
fmt.Fprintf(os.Stderr, "warning: %v\n", warning)
}
out := cmd.OutOrStdout()
if asJSON {
return json.NewEncoder(out).Encode(results)
}
writeWhois(out, results)
if !found {
cmd.SilenceErrors, cmd.SilenceUsage = true, true
return &commandExit{code: 1}
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "Print JSON")
return cmd
}
// lookupHost is replaced in tests.
var lookupHost = net.DefaultResolver.LookupHost
func whoisAddresses(ctx context.Context, query string) ([]string, error) {
query = strings.TrimSpace(query)
if ip := net.ParseIP(query); ip != nil {
return []string{ip.String()}, nil
}
if _, network, err := net.ParseCIDR(query); err == nil {
return []string{network.IP.String()}, nil
}
addresses, err := lookupHost(ctx, query)
if err != nil {
return nil, fmt.Errorf("%q is no IP address and cannot be resolved: %w", query, err)
}
if len(addresses) == 0 {
return nil, errors.New("no addresses found")
}
return addresses, nil
}
func writeWhois(w io.Writer, results []whoisResult) {
for i, r := range results {
if i > 0 {
fmt.Fprintln(w)
}
fmt.Fprintln(w, r.Address)
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
if len(r.NetBox) == 0 && len(r.Cached) == 0 && len(r.Prefixes) == 0 {
fmt.Fprintln(tw, " not found in NetBox or the cache")
}
for _, o := range r.NetBox {
owner := "unassigned"
if o.Target() != "" {
owner = o.Target() + " (" + o.HostKind + ")"
if o.Interface != "" {
owner += " " + o.Interface
}
}
var extra []string
if o.Status != "" {
extra = append(extra, o.Status)
}
if o.VRF != "" {
extra = append(extra, "vrf "+o.VRF)
}
if o.DNSName != "" {
extra = append(extra, "dns "+o.DNSName)
}
if o.Description != "" {
extra = append(extra, fmt.Sprintf("%q", o.Description))
}
fmt.Fprintf(tw, " IP\t%s\t%s\t%s\n", o.Address, owner, strings.Join(extra, " "))
}
for _, p := range r.Prefixes {
var extra []string
for _, pair := range [][2]string{{"", p.Status}, {"site ", p.Site}, {"role ", p.Role}, {"vlan ", p.VLAN}, {"vrf ", p.VRF}} {
if pair[1] != "" {
extra = append(extra, pair[0]+pair[1])
}
}
if p.Description != "" {
extra = append(extra, fmt.Sprintf("%q", p.Description))
}
prefix := p.Prefix
if p.Source != "" {
prefix += " (" + p.Source + ")"
}
fmt.Fprintf(tw, " Prefix\t%s\t%s\n", prefix, strings.Join(extra, " "))
}
for _, name := range r.Cached {
fmt.Fprintf(tw, " Cache\t%s\n", name)
}
_ = tw.Flush()
}
}
+559
View File
@@ -0,0 +1,559 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"go.yaml.in/yaml/v3"
"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/resolver"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/secret"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
// insightEnv writes a config and a cache with two NetBox hosts and a static host.
func insightEnv(t *testing.T, yamlConfig string) string {
t.Helper()
configDir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", configDir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
path := filepath.Join(t.TempDir(), "hosts.json")
t.Setenv("NETSSH_CACHE_PATH", path)
t.Setenv("NETSSH_SHELL_ALIAS", "")
if err := os.WriteFile(filepath.Join(configDir, "netssh.yaml"), []byte(yamlConfig), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
c := cache.New(cfg.CachePath(), 3600)
c.Upsert(cache.Entry{Name: "prod/web01", IP: "10.0.0.1", Kind: "vm", Tags: []string{"prod", "Web Server"}, ID: 11, Status: "active",
Site: &config.Ref{Name: "FSN 1", Slug: "fsn1"}, Role: &config.Ref{Name: "Web", Slug: "web"}, Platform: &config.Ref{Name: "Ubuntu 24.04", Slug: "ubuntu-24-04"}})
c.Upsert(cache.Entry{Name: "lab/web01", IP: "10.9.0.1", Kind: "vm", ID: 12, Status: "planned"})
c.Upsert(cache.Entry{Name: "prod/sw1", IP: "10.0.0.2", Kind: "device", ID: 13, Status: "active", Platform: &config.Ref{Name: "Junos", Slug: "junos"},
Location: []config.Ref{{Name: "Building A", Slug: "building-a"}, {Name: "Room 2.04", Slug: "room-2-04"}}, Rack: "R12", Position: "20"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
return path
}
const insightConfig = `netboxes:
- name: prod
url: https://nb.example
token: t
- name: lab
url: https://lab.example
token: t
ssh:
default_user: admin
rules:
- match: {platform: junos}
proxy_jump: jump.example
options: {KexAlgorithms: +diffie-hellman-group14-sha1}
hosts:
- name: router
address: 192.168.1.1
port: 2222
tags: [home]
`
func TestExportAnsibleYAML(t *testing.T) {
insightEnv(t, insightConfig)
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("tag,site,platform,status")
hosts, err := exportHosts(cfg, exportFilter{})
if err != nil {
t.Fatal(err)
}
data, err := buildInventory(hosts, keys, true).yaml()
if err != nil {
t.Fatal(err)
}
var inv struct {
All struct {
Hosts map[string]map[string]any `yaml:"hosts"`
Children map[string]struct {
Hosts map[string]any `yaml:"hosts"`
} `yaml:"children"`
} `yaml:"all"`
}
if err := yaml.Unmarshal(data, &inv); err != nil {
t.Fatalf("invalid YAML: %v\n%s", err, data)
}
web := inv.All.Hosts["prod-web01"]
if web["ansible_host"] != "10.0.0.1" || web["ansible_user"] != "admin" || web["netbox_site"] != "FSN 1" || web["netbox_id"] != 11 {
t.Fatalf("prod-web01 vars wrong: %+v\n%s", web, data)
}
if tags, _ := web["netbox_tags"].([]any); len(tags) != 2 {
t.Fatalf("tags should stay a list: %#v", web["netbox_tags"])
}
if _, ok := inv.All.Hosts["lab-web01"]; !ok {
t.Fatalf("duplicate hostnames must be qualified: %v", inv.All.Hosts)
}
sw := inv.All.Hosts["sw1"]
if sw["ansible_ssh_common_args"] != "-o ProxyJump=jump.example" {
t.Fatalf("jump host missing for platform rule: %+v", sw)
}
router := inv.All.Hosts["router"]
if router["ansible_port"] != 2222 || router["ansible_host"] != "192.168.1.1" {
t.Fatalf("static host wrong: %+v", router)
}
for _, group := range []string{"tag_prod", "tag_web_server", "site_fsn1", "platform_junos", "status_planned", "tag_home"} {
if _, ok := inv.All.Children[group]; !ok {
t.Errorf("group %s missing in\n%s", group, data)
}
}
if _, ok := inv.All.Children["platform_junos"].Hosts["sw1"]; !ok {
t.Fatal("sw1 not in platform_junos")
}
}
func TestExportAnsibleINI(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{instance: "prod"})
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("tag,role")
out := string(buildInventory(hosts, keys, true).ini())
for _, want := range []string{
"[all]\nsw1 ansible_host=10.0.0.2 ansible_user=admin ansible_ssh_common_args=\"-o ProxyJump=jump.example\"",
`web01 ansible_host=10.0.0.1`,
`netbox_site="FSN 1"`,
`netbox_tags="prod,Web Server"`,
"\n[role_web]\nweb01\n",
"\n[tag_prod]\nweb01\n",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
if strings.Contains(out, "lab") || strings.Contains(out, "router") {
t.Fatalf("--instance prod not applied:\n%s", out)
}
}
func TestExportFiltersAndGroupByValidation(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{status: "active", noStatic: true})
if err != nil {
t.Fatal(err)
}
if len(hosts) != 2 {
t.Fatalf("status filter: %+v", hosts)
}
if _, err := parseGroupBy("site,color"); err == nil {
t.Fatal("unknown group-by accepted")
}
if keys, err := parseGroupBy("none"); err != nil || keys != nil {
t.Fatal("none should disable groups")
}
if _, err := exportHosts(cfg, exportFilter{tag: "missing"}); err == nil {
t.Fatal("empty export should fail")
}
}
func TestExportSSHConfig(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{})
if err != nil {
t.Fatal(err)
}
var b bytes.Buffer
writeSSHConfig(&b, hosts, map[string]string{"prod/sw1": "sw"})
out := b.String()
for _, want := range []string{
"\nHost sw1 sw\n HostName 10.0.0.2\n User admin\n ProxyJump jump.example\n kexalgorithms +diffie-hellman-group14-sha1\n",
"\nHost router\n HostName 192.168.1.1\n User admin\n Port 2222\n",
"\nHost prod-web01\n HostName 10.0.0.1\n",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
}
func TestCopyIDArgv(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
h, err := resolveTargetE(cfg, "prod/sw1", false)
if err != nil {
t.Fatal(err)
}
argv, err := copyIDArgv(cfg, h, copyIDFlags{identity: "/k.pub"})
if err != nil {
t.Fatal(err)
}
got := internalssh.Quote(argv)
for _, want := range []string{"ssh-copy-id -i /k.pub", "-o ProxyJump=jump.example", "-o kexalgorithms=+diffie-hellman-group14-sha1", "admin@10.0.0.2"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in %s", want, got)
}
}
if strings.Contains(got, " -J ") {
t.Fatalf("ssh-copy-id has no -J: %s", got)
}
router, _ := resolveTargetE(cfg, "router", false)
argv, _ = copyIDArgv(cfg, router, copyIDFlags{user: "root", noJump: true, check: true})
if got := internalssh.Quote(argv); !strings.Contains(got, "-n") || !strings.Contains(got, "-p 2222") || !strings.HasSuffix(got, "root@192.168.1.1") {
t.Fatalf("static host argv wrong: %s", got)
}
}
func TestRunCopyIDContinuesAfterFailure(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
var ran []string
old := runCopyIDCommand
runCopyIDCommand = func(argv []string) error {
ran = append(ran, argv[len(argv)-1])
if strings.Contains(argv[len(argv)-1], "10.0.0.2") {
return errors.New("permission denied")
}
return nil
}
t.Cleanup(func() { runCopyIDCommand = old })
stubTerminal(t, false)
err := runCopyID(cfg, []string{"prod/sw1", "router"}, copyIDFlags{})
if err == nil || !strings.Contains(err.Error(), "1 of 2 hosts") || len(ran) != 2 {
t.Fatalf("err %v, ran %v", err, ran)
}
}
func stubTerminal(t *testing.T, tty bool) {
t.Helper()
old := stdinIsTerminal
stdinIsTerminal = func() bool { return tty }
t.Cleanup(func() { stdinIsTerminal = old })
}
func TestConfirmStatusWarnsWithoutTerminal(t *testing.T) {
stubTerminal(t, false)
cfg := &config.Config{}
if err := confirmStatus(cfg, resolvedHost{Name: "web", Status: "offline"}, false); err != nil {
t.Fatalf("non-interactive status check must not fail: %v", err)
}
if err := confirmStatus(cfg, resolvedHost{Name: "web", Status: "active"}, false); err != nil {
t.Fatal(err)
}
}
func TestKnownHostsKeysAndFile(t *testing.T) {
keys := knownHostsKeys("prod/web01", []string{"10.0.0.1", "10.0.0.1", "10.0.0.9"}, 2222)
want := []string{"web01", "[web01]:2222", "10.0.0.1", "[10.0.0.1]:2222", "10.0.0.9", "[10.0.0.9]:2222"}
if strings.Join(keys, " ") != strings.Join(want, " ") {
t.Fatalf("got %v", keys)
}
if keys := knownHostsKeys("web", []string{"10.0.0.1"}, 22); strings.Join(keys, " ") != "web 10.0.0.1" {
t.Fatalf("got %v", keys)
}
t.Setenv("HOME", "/home/u")
if f := knownHostsFile(config.SSHOptions{Options: map[string]string{"userknownhostsfile": "~/.ssh/lab_hosts ~/.ssh/other"}}); f != "/home/u/.ssh/lab_hosts" {
t.Fatalf("file %q", f)
}
if f := knownHostsFile(config.SSHOptions{Options: map[string]string{"userknownhostsfile": "/dev/null"}}); f != "" {
t.Fatalf("file %q", f)
}
}
func TestKnownHostsResetRemovesNameAndAddresses(t *testing.T) {
insightEnv(t, insightConfig)
var removed []string
old := removeKnownHosts
removeKnownHosts = func(keys []string, file string) error { removed = append(removed, keys...); return nil }
t.Cleanup(func() { removeKnownHosts = old })
cmd := rootCmd()
cmd.SetArgs([]string{"known-hosts", "reset", "--yes", "router"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if strings.Join(removed, " ") != "router [router]:2222 192.168.1.1 [192.168.1.1]:2222" {
t.Fatalf("removed %v", removed)
}
}
func TestConnectPort(t *testing.T) {
for _, tc := range []struct {
client internalssh.Client
args []string
want int
}{
{internalssh.SSH, []string{"-p", "2222", "web"}, 2222},
{internalssh.SSH, []string{"-p2200", "web"}, 2200},
{internalssh.SSH, []string{"-o", "Port=2022", "web"}, 2022},
{internalssh.SFTP, []string{"-P", "23", "web"}, 23},
{internalssh.SSH, []string{"web", "-p", "1"}, 22},
} {
dest := 0
for i, a := range tc.args {
if a == "web" {
dest = i
}
}
if got := connectPort(tc.client, tc.args, []int{dest}); got != tc.want {
t.Errorf("%v: got %d, want %d", tc.args, got, tc.want)
}
}
}
func TestApplyFallback(t *testing.T) {
up := map[string]bool{"10.0.0.2": true}
oldProbe, oldCandidates := fallbackProbe, fallbackCandidates
fallbackProbe = func(address string, port int, _ time.Duration) bool { return up[address] && port == 22 }
fallbackCandidates = func(*config.Config, resolvedHost) ([]resolver.Candidate, error) {
return []resolver.Candidate{{Address: "10.0.0.1", Strategy: "management_subnet"}, {Address: "10.0.0.2", Strategy: "primary_ip"}}, nil
}
t.Cleanup(func() { fallbackProbe, fallbackCandidates = oldProbe, oldCandidates })
host := resolvedHost{Name: "web", Kind: "vm", IP: "10.0.0.1"}
cfg := &config.Config{}
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("fallback ran while disabled")
}
cfg.Resolver.Fallback = true
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.2" {
t.Fatalf("fallback did not switch: %s", got.IP)
}
if got := applyFallback(cfg, host, config.SSHOptions{ProxyJump: "jump"}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("hosts behind a jump host must not be probed")
}
if got := applyFallback(cfg, host, config.SSHOptions{ProxyJump: "jump"}, internalssh.WrapperFlags{NoJump: true}, 22); got.IP != "10.0.0.2" {
t.Fatal("--no-jump should allow the fallback")
}
up = map[string]bool{}
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("must keep the chosen address when nothing answers")
}
}
func TestReachableProbe(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
port := ln.Addr().(*net.TCPAddr).Port
if !reachable("127.0.0.1", port, time.Second) {
t.Fatal("listening port reported unreachable")
}
ln.Close()
if reachable("127.0.0.1", port, 200*time.Millisecond) {
t.Fatal("closed port reported reachable")
}
}
func TestWhoisAddresses(t *testing.T) {
old := lookupHost
lookupHost = func(_ context.Context, host string) ([]string, error) {
if host == "mail.example.com" {
return []string{"192.0.2.25"}, nil
}
return nil, errors.New("no such host")
}
t.Cleanup(func() { lookupHost = old })
for in, want := range map[string]string{"10.0.0.1": "10.0.0.1", "10.0.0.0/24": "10.0.0.0", "mail.example.com": "192.0.2.25"} {
got, err := whoisAddresses(context.Background(), in)
if err != nil || len(got) != 1 || got[0] != want {
t.Errorf("%s: %v %v", in, got, err)
}
}
if _, err := whoisAddresses(context.Background(), "nope.invalid"); err == nil {
t.Fatal("unresolvable name accepted")
}
}
func TestWhoisCommandUsesNetBoxAndCache(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":1,"results":[{"address":"10.0.0.1/24","dns_name":"web01.example.com","assigned_object":{"name":"eth0","virtual_machine":{"id":11,"name":"web01"}}}]}`)
case "/api/ipam/prefixes/":
fmt.Fprint(w, `{"count":1,"results":[{"prefix":"10.0.0.0/24","description":"servers"}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
insightEnv(t, fmt.Sprintf("netboxes:\n - name: prod\n url: %s\n token: t\n", srv.URL))
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"whois", "10.0.0.1"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"prod/web01 (vm) eth0", "dns web01.example.com", "10.0.0.0/24 (prod)", `"servers"`, "Cache prod/web01"} {
if !strings.Contains(out.String(), want) {
t.Errorf("missing %q in\n%s", want, out.String())
}
}
}
func TestOpenPrintsNetBoxURL(t *testing.T) {
insightEnv(t, insightConfig)
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"open", "--print", "prod/sw1"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if strings.TrimSpace(out.String()) != "https://nb.example/dcim/devices/13/" {
t.Fatalf("got %q", out.String())
}
cmd = rootCmd()
cmd.SetArgs([]string{"open", "--print", "router"})
if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "static host") {
t.Fatalf("static host: %v", err)
}
}
func TestTokenMigrateAndResolve(t *testing.T) {
secret.MockInit()
insightEnv(t, insightConfig)
var saved config.Config
old := saveConfig
saveConfig = func(cfg config.Config) error { saved = cfg; return nil }
t.Cleanup(func() { saveConfig = old })
tokenMu.Lock()
tokenCache = map[string]string{}
tokenMu.Unlock()
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"token", "migrate"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if len(saved.NetBoxes) != 2 || !config.IsKeyringToken(saved.NetBoxes[0].Token) || !config.IsKeyringToken(saved.NetBoxes[1].Token) {
t.Fatalf("tokens not replaced: %+v", saved.NetBoxes)
}
token, err := resolveToken(saved.NetBoxes[0])
if err != nil || token != "t" {
t.Fatalf("token %q, %v", token, err)
}
cmd = rootCmd()
cmd.SetIn(strings.NewReader("nbt_secret\n"))
cmd.SetOut(&out)
cmd.SetArgs([]string{"token", "set", "lab"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
stored, err := secret.Get("lab")
if err != nil || stored != "nbt_secret" {
t.Fatalf("stored %q, %v", stored, err)
}
for _, n := range saved.NetBoxes {
if n.Name == "lab" && n.TokenVersion != 2 {
t.Fatalf("token version not detected: %+v", n)
}
}
cmd = rootCmd()
cmd.SetArgs([]string{"token", "set"})
if err := cmd.Execute(); err == nil {
t.Fatal("ambiguous instance accepted")
}
}
func TestCacheRefreshStoresAttributesAndReportsChangedAddresses(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/dcim/devices/":
fmt.Fprint(w, `{"count":1,"results":[{"id":5,"name":"sw1","primary_ip4":{"address":"192.0.2.5/24"},
"status":{"value":"offline"},"site":{"name":"FSN1","slug":"fsn1"},"role":{"name":"Switch","slug":"switch"},"platform":{"name":"Junos","slug":"junos"}}]}`)
case "/api/virtualization/virtual-machines/", "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
path := prepareRefreshTest(t, srv.URL, "[primary_ip]")
c := cache.New(path, 3600)
c.Upsert(cache.Entry{Name: "sw1", IP: "192.0.2.99", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
stdout := captureStdout(t, func() {
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
})
if !strings.Contains(stdout, "sw1: 192.0.2.99 → 192.0.2.5") || !strings.Contains(stdout, "known-hosts reset") {
t.Fatalf("address change not reported:\n%s", stdout)
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
got, _ := c.Get("sw1")
if got.ID != 5 || got.Status != "offline" || cache.RefOf(got.Site).Slug != "fsn1" || cache.RefOf(got.Platform).Slug != "junos" || cache.RefOf(got.Role).Name != "Switch" {
t.Fatalf("attributes not cached: %+v", got)
}
cfg, _ := config.Load()
h, _ := resolveTargetE(cfg, "sw1", false)
if h.Status != "offline" || h.Platform.Slug != "junos" || h.ID != 5 {
t.Fatalf("resolved host lacks attributes: %+v", h)
}
}
func captureStdout(t *testing.T, fn func()) string {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = w
done := make(chan string)
go func() {
var b bytes.Buffer
_, _ = b.ReadFrom(r)
done <- b.String()
}()
defer func() { os.Stdout = old }()
fn()
w.Close()
os.Stdout = old
return <-done
}
func TestExportLocationVarsAndGroups(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{instance: "prod", kind: "device"})
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("location,rack")
out := string(buildInventory(hosts, keys, true).ini())
for _, want := range []string{`netbox_location="Building A/Room 2.04"`, "netbox_rack=R12", "netbox_position=20",
"\n[location_building_a]\nsw1\n", "\n[location_room_2_04]\nsw1\n", "\n[rack_r12]\nsw1\n"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
}
+5 -3
View File
@@ -20,14 +20,16 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
if len(cfg.NetBoxes) > 0 { if len(cfg.NetBoxes) > 0 {
sources := make([]netbox.Source, 0, len(cfg.NetBoxes)) sources := make([]netbox.Source, 0, len(cfg.NetBoxes))
for _, source := range cfg.NetBoxes { for _, source := range cfg.NetBoxes {
sources = append(sources, netbox.Source{Name: source.Name, URL: source.URL, Token: source.Token, TokenVersion: source.TokenVersion}) token, version := clientToken(source)
sources = append(sources, netbox.Source{Name: source.Name, URL: source.URL, Token: token, TokenVersion: version})
} }
return netbox.NewMultiClient(sources) return netbox.NewMultiClient(sources)
} }
if cfg.NetBox.URL == "" { if cfg.NetBox.URL == "" {
return nil return nil
} }
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion) token, version := clientToken(cfg.NetBox)
return netbox.NewClient(cfg.NetBox.URL, token, version)
} }
// shortcutAliases maps each target (lowercased) to the shell alias generated for // shortcutAliases maps each target (lowercased) to the shell alias generated for
@@ -41,7 +43,7 @@ func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string
} }
plain := strings.NewReplacer(".", "_", "/", "_") plain := strings.NewReplacer(".", "_", "/", "_")
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) { for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
if alias.Host == "" { if alias.Host == "" || alias.Command != "" {
continue // the command alias for netssh itself continue // the command alias for netssh itself
} }
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) { if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
+98
View File
@@ -0,0 +1,98 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
func knownHostsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "known-hosts",
Short: "Clean up host keys of re-deployed hosts",
}
cmd.AddCommand(knownHostsResetCmd())
return cmd
}
func knownHostsResetCmd() *cobra.Command {
var yes, dryRun bool
cmd := &cobra.Command{
Use: "reset HOST...",
Short: "Remove the known_hosts entries of hosts (name, current and previous address)",
Long: `Remove the stored host keys of hosts with ssh-keygen -R, after a host was
re-installed or got a new address. Removed are the hostname, the address
netssh connects to, the previously cached address if NetBox changed it, and
[name]:port / [address]:port for a non-standard port. ssh-keygen keeps the
previous file as known_hosts.old.`,
Example: " netssh known-hosts reset web01\n netssh known-hosts reset --dry-run web01 web02",
Args: cobra.MinimumNArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
c := newCache(cfg)
_ = c.Load()
type plan struct {
keys []string
file string
}
var plans []plan
var all []string
for _, target := range args {
previous, _ := c.Get(target)
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
addresses := []string{h.IP}
if h.PreviousIP != "" {
addresses = append(addresses, h.PreviousIP)
}
if previous.IP != "" && previous.IP != h.IP {
addresses = append(addresses, previous.IP)
}
_, port := hostDefaults(cfg, h)
if port <= 0 {
port = 22
}
opts := hostOptions(cfg, h)
p := plan{keys: knownHostsKeys(h.Name, addresses, port), file: knownHostsFile(opts)}
plans = append(plans, p)
all = append(all, p.keys...)
}
if dryRun {
for _, p := range plans {
for _, key := range p.keys {
argv := []string{"ssh-keygen", "-R", key}
if p.file != "" {
argv = append(argv, "-f", p.file)
}
fmt.Fprintln(cmd.OutOrStdout(), internalssh.Quote(argv))
}
}
return nil
}
if err := confirmAction("Remove known_hosts entries for "+strings.Join(all, ", "), yes); err != nil {
return err
}
for _, p := range plans {
if err := removeKnownHosts(p.keys, p.file); err != nil {
return err
}
}
fmt.Fprintln(os.Stderr, "Done. The next connection asks to confirm the new host key.")
return nil
},
}
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the ssh-keygen commands without running them")
return cmd
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"fmt"
"sort"
"strings"
"text/tabwriter"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func linkCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "link",
Short: "Short names for hosts: netssh NAME and shell alias NAME",
Long: `Links give a host a name of your own, for example mx123 for the server that
mx123.webseite.de points to. netssh NAME then connects to the host, and new
shells get the alias NAME. netssh offers to create a link after a DNS
suggestion; links are stored under links: in the config.`,
}
cmd.AddCommand(linkListCmd(), linkAddCmd(), linkRemoveCmd())
return cmd
}
func linkListCmd() *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "List links",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if len(cfg.Links) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No links. Add one with: netssh link add NAME HOST")
return nil
}
names := make([]string, 0, len(cfg.Links))
for name := range cfg.Links {
names = append(names, name)
}
sort.Strings(names)
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "NAME\tHOST")
for _, name := range names {
fmt.Fprintf(w, "%s\t%s\n", name, cfg.Links[name])
}
return w.Flush()
},
}
}
func linkAddCmd() *cobra.Command {
return &cobra.Command{
Use: "add NAME HOST",
Short: "Create or replace a link",
Example: " netssh link add mx123 prod/web07\n netssh link add mx123 mx123.webseite.de # asks which host owns the address",
Args: cobra.ExactArgs(2),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
if len(args) == 1 {
return hostCompletion(cmd, args, toComplete)
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
name := strings.ToLower(args[0])
if _, isLink := cfg.Link(args[1]); isLink {
return fmt.Errorf("%q is a link itself; link to a host", args[1])
}
// Resolve now, so a typo fails here and the link stores the canonical target.
h, err := resolveOrSuggestQuiet(cfg, args[1])
if err != nil {
return err
}
if h.Kind == "dns" {
return fmt.Errorf("%s is not a NetBox or static host; links point to hosts netssh knows", args[1])
}
if err := saveLink(name, h.Name); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "netssh %s → %s (open a new shell for the alias %s)\n", name, h.Name, name)
return nil
},
}
}
// resolveOrSuggestQuiet resolves for link add without offering another link.
func resolveOrSuggestQuiet(cfg *config.Config, host string) (resolvedHost, error) {
old := offerLinkFunc
offerLinkFunc = func(string, string, string) {}
defer func() { offerLinkFunc = old }()
return resolveOrSuggest(cfg, host, false)
}
func linkRemoveCmd() *cobra.Command {
return &cobra.Command{
Use: "remove NAME",
Short: "Remove a link",
Args: cobra.ExactArgs(1),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var names []string
for name := range cfg.Links {
names = append(names, name)
}
return filterPrefix(names, toComplete, nil), cobra.ShellCompDirectiveNoFileComp
},
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
removed := false
for key := range cfg.Links {
if strings.EqualFold(key, args[0]) {
delete(cfg.Links, key)
removed = true
}
}
if !removed {
return fmt.Errorf("no link %q", args[0])
}
if err := saveHosts(cfg); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "Link %s removed.\n", args[0])
return nil
},
}
}
+85
View File
@@ -0,0 +1,85 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
)
func TestLinksResolveAndBecomeAliases(t *testing.T) {
dnsEnv(t, "links:\n mx123: prod/web07\n")
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
h, err := resolveTargetE(cfg, "MX123", false)
if err != nil || h.Name != "prod/web07" {
t.Fatalf("link not followed: %+v %v", h, err)
}
var found bool
for _, a := range hook.BuildAliasEntries(nil, *cfg) {
if a.Name == "mx123" && a.Host == "mx123" {
found = true
}
}
if !found {
t.Fatal("link has no shell alias")
}
if got := completeHosts("mx"); len(got) == 0 || got[0] != "mx123" {
t.Fatalf("completion: %v", got)
}
}
func TestLinkAddListRemove(t *testing.T) {
dnsEnv(t, "")
stubTerminal(t, false)
run := func(args ...string) (string, error) {
var out strings.Builder
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs(args)
err := cmd.Execute()
return out.String(), err
}
if _, err := run("link", "add", "mx123", "prod/web07"); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"))
if !strings.Contains(string(data), "links:\n mx123: \"prod/web07\"") {
t.Fatalf("link not written:\n%s", data)
}
if out, _ := run("link", "list"); !strings.Contains(out, "mx123 prod/web07") {
t.Fatalf("list: %q", out)
}
if _, err := run("link", "add", "x", "missing-host"); err == nil {
t.Fatal("link to unknown host accepted")
}
if _, err := run("link", "remove", "mx123"); err != nil {
t.Fatal(err)
}
cfg, _ := config.Load()
if len(cfg.Links) != 0 {
t.Fatalf("not removed: %v", cfg.Links)
}
}
func TestValidateLinks(t *testing.T) {
for _, tc := range []struct {
cfg config.Config
ok bool
}{
{config.Config{Links: map[string]string{"mx123": "prod/web07"}}, true},
{config.Config{Links: map[string]string{"bad name": "web"}}, false},
{config.Config{Links: map[string]string{"a": "-oProxyCommand=x"}}, false},
{config.Config{Links: map[string]string{"a": "b", "b": "web"}}, false},
{config.Config{Links: map[string]string{"router": "web"}, Hosts: []config.StaticHost{{Name: "router", Address: "1.2.3.4"}}}, false},
} {
if err := tc.cfg.ValidateLinks(); (err == nil) != tc.ok {
t.Errorf("%v: %v", tc.cfg.Links, err)
}
}
}
+222 -30
View File
@@ -17,6 +17,7 @@ import (
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/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/hook"
@@ -30,6 +31,7 @@ import (
// managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode. // managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode.
var managedSubcommands = map[string]bool{ var managedSubcommands = map[string]bool{
"doctor": true, "explain": true, "favorites": true, "history": true, "batch": true, "config": true,
"configure": true, "configure": true,
"notes": true, "notes": true,
"search": true, "search": true,
@@ -49,6 +51,14 @@ var managedSubcommands = map[string]bool{
"multi": true, "multi": true,
"sync": true, "sync": true,
"run": true, "run": true,
"open": true,
"info": true,
"whois": true,
"copy-id": true,
"export": true,
"token": true,
"known-hosts": true,
"link": true,
} }
func main() { func main() {
@@ -75,6 +85,10 @@ func main() {
if managedSubcommands[args[0]] { if managedSubcommands[args[0]] {
if err := rootCmd().Execute(); err != nil { if err := rootCmd().Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
os.Exit(1) os.Exit(1)
} }
return return
@@ -208,25 +222,89 @@ func prependArgs(extra, args []string, dests []int) []string {
// resolvedHost is a NetBox host with the address to connect to. // resolvedHost is a NetBox host with the address to connect to.
type resolvedHost struct { type resolvedHost struct {
Origin string
Resolver string
CachedAt time.Time
Name string // cache/selector name, may carry an instance prefix Name string // cache/selector name, may carry an instance prefix
Kind string Kind string
IP string IP string
Tags []string Tags []string
ID int // NetBox ID; 0 for static hosts and old cache entries
Status string
Site config.Ref
Role config.Ref
Platform config.Ref
Tenant config.Ref
Location []config.Ref
Rack string
Position string
// PreviousIP is the cached address a live lookup replaced, if it differs.
PreviousIP string
}
// hostFromEntry converts a cache entry into a resolved host.
func hostFromEntry(entry cache.Entry, origin string) resolvedHost {
return resolvedHost{
Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags, Origin: origin, Resolver: entry.Resolver, CachedAt: entry.CachedAt,
ID: entry.ID, Status: entry.Status, Site: cache.RefOf(entry.Site), Role: cache.RefOf(entry.Role), Platform: cache.RefOf(entry.Platform), Tenant: cache.RefOf(entry.Tenant),
Location: entry.Location, Rack: entry.Rack, Position: entry.Position,
}
}
// LocationPath renders site › locations › rack › U position.
func (h resolvedHost) LocationPath() string {
return config.LocationPath(h.Site, h.Location, h.Rack, h.Position)
}
// cacheEntry records a NetBox host and its resolved address in the cache.
func cacheEntry(target netbox.HostEntry, ip, strategy string) cache.Entry {
return cache.Entry{
Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy,
ID: target.ID, Status: target.Status, Site: cache.RefPtr(target.Site), Role: cache.RefPtr(target.Role), Platform: cache.RefPtr(target.Platform), Tenant: cache.RefPtr(target.Tenant),
Location: target.Location, Rack: target.Rack, Position: target.Position,
}
}
// upsertResolved caches a live result and reports the address it replaced.
func upsertResolved(c *cache.Cache, entry cache.Entry) (previous string) {
if old, _ := c.Get(entry.Name); old.Name != "" && !old.Static && old.IP != "" && old.IP != entry.IP {
previous = old.IP
}
c.Upsert(entry)
return previous
} }
// resolveTarget finds host in the cache (also by shortcut) or NetBox and // resolveTarget finds host in the cache (also by shortcut) or NetBox and
// resolves its address. It exits on failure. // resolves its address. It exits on failure.
func resolveTarget(cfg *config.Config, host string) resolvedHost { func resolveTarget(cfg *config.Config, host string) resolvedHost {
result, err := resolveOrSuggest(cfg, host, true)
if err != nil {
fatalf("%v", err)
}
return result
}
func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, error) {
if target, ok := cfg.Link(host); ok {
host = target
}
c := newCache(cfg) c := newCache(cfg)
_ = c.Load() _ = c.Load()
if record {
maybeBackgroundRefresh(cfg, c) maybeBackgroundRefresh(cfg, c)
}
source, _ := netbox.SplitTarget(host) source, _ := netbox.SplitTarget(host)
useCache := len(cfg.NetBoxes) == 0 || source != "" useCache := len(cfg.NetBoxes) == 0 || source != ""
used := func(entry cache.Entry) resolvedHost { used := func(entry cache.Entry) resolvedHost {
if record {
c.MarkUsed(entry.Name) c.MarkUsed(entry.Name)
_ = c.Save() _ = c.Save()
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags} }
origin := "cache"
if entry.Static {
origin = "static"
}
return hostFromEntry(entry, origin)
} }
// Static hosts from the config win and need no NetBox. // Static hosts from the config win and need no NetBox.
@@ -237,16 +315,16 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
} }
entry, found, err := c.GetStatic(host, normalize) entry, found, err := c.GetStatic(host, normalize)
if err != nil { if err != nil {
fatalf("%v", err) return resolvedHost{}, err
} }
if found { if found {
return used(entry) return used(entry), nil
} }
} }
// Cache hit with a fresh TTL — connect directly without querying NetBox. // Cache hit with a fresh TTL — connect directly without querying NetBox.
if entry, fresh := c.Get(host); fresh && useCache { if entry, fresh := c.Get(host); fresh && useCache {
return used(entry) return used(entry), nil
} }
// Shortcut cache lookup: scan entries whose normalized name matches the input. // Shortcut cache lookup: scan entries whose normalized name matches the input.
@@ -257,11 +335,11 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
normalize := normalizeTarget(cfg.Shortcuts, source != "") normalize := normalizeTarget(cfg.Shortcuts, source != "")
entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize) entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize)
if err != nil { if err != nil {
fatalf("%v", err) return resolvedHost{}, err
} }
if found { if found {
if fresh { if fresh {
return used(entry) return used(entry), nil
} }
// Stale shortcut match — use canonical name for NetBox re-fetch. // Stale shortcut match — use canonical name for NetBox re-fetch.
lookupHost = entry.Name lookupHost = entry.Name
@@ -269,7 +347,7 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
} }
if !cfg.HasNetBox() { if !cfg.HasNetBox() {
fatalf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host) return resolvedHost{}, fmt.Errorf("host %q is not in hosts: and no NetBox is configured (netssh configure): %w", host, netbox.ErrHostNotFound)
} }
nbClient := newNetBoxClient(cfg) nbClient := newNetBoxClient(cfg)
@@ -280,33 +358,36 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled { if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled {
entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false)) entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false))
if cacheErr != nil { if cacheErr != nil {
fatalf("%v", cacheErr) return resolvedHost{}, cacheErr
} }
if found { if found {
target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains) target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains)
} }
} }
if err != nil { if err != nil {
fatalf("NetBox: %v", err) return resolvedHost{}, fmt.Errorf("NetBox: %w", err)
} }
if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind { if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind {
return used(cached) return used(cached), nil
} }
chain, err := resolver.New(cfg.Resolver) chain, err := resolver.New(cfg.Resolver)
if err != nil { if err != nil {
fatalf("resolver: %v", err) return resolvedHost{}, err
} }
ip, err := chain.Resolve(ctx, &target, nbClient) ip, strategy, err := chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil { if err != nil {
fatalf("IP resolution for %q: %v", host, err) return resolvedHost{}, fmt.Errorf("IP resolution for %q: %w", host, err)
} }
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster} entry := cacheEntry(target, ip, strategy)
c.Upsert(entry) previous := upsertResolved(c, entry)
return used(entry) result := used(entry)
result.Origin = "live"
result.PreviousIP = previous
return result, nil
} }
// findSSHHost uses the paginated, ambiguity-checking lookup for connection // findSSHHost uses the paginated, ambiguity-checking lookup for connection
@@ -349,17 +430,47 @@ 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 flags.DryRun {
if cfg.SSH.WarnsStatus(host.Status) {
fmt.Fprintf(os.Stderr, "# warning: %s has NetBox status %q\n", host.Name, host.Status)
}
} else {
if err := confirmStatus(cfg, host, flags.Force); err != nil {
fatalf("%v", err)
}
port := connectPort(client, args, dests)
host = applyFallback(cfg, host, opts, flags, port)
if host.PreviousIP != "" {
offerKnownHostsCleanup(opts, host, port)
}
}
if err := runPreConnect(opts.PreConnectCommand(), host, client.Name, flags.DryRun); err != nil { if err := runPreConnect(opts.PreConnectCommand(), host, client.Name, flags.DryRun); err != nil {
fatalf("%v", err) 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) result := client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags)
post := config.HookCommand(opts.PostDisconnect)
if flags.DryRun {
if post != "" {
fmt.Fprintf(os.Stderr, "# post_disconnect (skipped in --dry-run): %s\n", post)
}
}
if !flags.DryRun && (post != "" || cfg.Activity.Enabled) {
if result.Notice != "" {
fmt.Fprintln(os.Stderr, result.Notice)
}
code := supervise(cfg, host, client.Name, append([]string{client.Name}, result.Args...), post, 0, false, os.Stdin, os.Stdout, os.Stderr)
if code != 0 {
os.Exit(code)
}
return
}
execClient(client, result, flags)
} }
// hostOptions merges the global, instance, and rule SSH options for host. // hostOptions merges the global, instance, and rule SSH options for host.
func hostOptions(cfg *config.Config, host resolvedHost) config.SSHOptions { func hostOptions(cfg *config.Config, host resolvedHost) config.SSHOptions {
instance, name := netbox.SplitTarget(host.Name) return cfg.SSHOptionsFor(commandHost(host))
return cfg.SSHOptionsFor(config.SSHHost{Instance: instance, Name: name, Kind: host.Kind, Tags: host.Tags})
} }
// execClient replaces the process with the client, or prints the command for --dry-run. // execClient replaces the process with the client, or prints the command for --dry-run.
@@ -391,14 +502,64 @@ 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) m.SetHostLabel(cfg.HostLabel)
m.SetHistoryLimit(cfg.TUI.HistoryLimit)
state, stateErr := activity.Read()
if stateErr != nil {
fmt.Fprintf(os.Stderr, "favorites: %v\n", stateErr)
}
m.SetPreferences(state.Favorites, state.Pinned, func(favorites, pinned map[string]bool) error {
err := activity.Update(func(s *activity.State) {
merge := func(dst, previous, next map[string]bool) {
for name, value := range next {
if previous[name] != value {
if value {
dst[name] = true
} else {
delete(dst, name)
}
}
}
for name, value := range previous {
if value && !next[name] {
delete(dst, name)
}
}
}
merge(s.Favorites, state.Favorites, favorites)
merge(s.Pinned, state.Pinned, pinned)
})
if err == nil {
state.Favorites = favorites
state.Pinned = pinned
}
return err
})
known := func(name, kind string, tags []string) resolvedHost {
if e, _ := c.Get(name); e.Name != "" && e.Kind == kind {
return hostFromEntry(e, "cache")
}
return resolvedHost{Name: name, Kind: kind, Tags: tags}
}
m.SetCommands(func(name, kind string, tags []string) []string {
var names []string
h := commandHost(known(name, kind, tags))
for name, c := range cfg.Commands {
if c.Allowed(h) {
names = append(names, name)
}
}
sort.Strings(names)
return names
})
if cfg.Shortcuts.Show { if cfg.Shortcuts.Show {
aliases := shortcutAliases(c.All(), *cfg) aliases := shortcutAliases(c.All(), *cfg)
m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] }) 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, known(name, kind, tags)))
}) })
configureTUIExtras(m, cfg, nbClient, known)
p := tea.NewProgram(m) p := tea.NewProgram(m)
final, err := p.Run() final, err := p.Run()
if err != nil { if err != nil {
@@ -413,6 +574,22 @@ func runTUI() {
if host == nil { if host == nil {
return return
} }
if host.Command != "" {
args := []string{"run", host.Command, "--", host.Name}
if len(host.Targets) > 0 {
args = append([]string{"batch", host.Command}, host.Targets...)
}
root := rootCmd()
root.SetArgs(args)
if err := root.Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
fatalf("%v", err)
}
return
}
if host.Action == tui.ActionMulti { if host.Action == tui.ActionMulti {
if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil { if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil {
fatalf("%v", err) fatalf("%v", err)
@@ -421,10 +598,9 @@ func runTUI() {
} }
// Revalidate stale or live TUI results through the configured resolver chain. // Revalidate stale or live TUI results through the configured resolver chain.
var tags []string var resolved resolvedHost
if cached, fresh := c.Get(host.Name); fresh && cached.Kind == host.Kind { if cached, fresh := c.Get(host.Name); fresh && cached.Kind == host.Kind {
host.IP = cached.IP resolved = hostFromEntry(cached, "cache")
tags = cached.Tags
} else { } else {
if nbClient == nil { if nbClient == nil {
fatalf("cannot resolve %q: NetBox is not configured", host.Name) fatalf("cannot resolve %q: NetBox is not configured", host.Name)
@@ -439,20 +615,24 @@ func runTUI() {
if err != nil { if err != nil {
fatalf("resolver: %v", err) fatalf("resolver: %v", err)
} }
host.IP, err = chain.Resolve(ctx, &target, nbClient) var strategy string
host.IP, strategy, err = chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil { if err != nil {
fatalf("IP resolution: %v", err) fatalf("IP resolution: %v", err)
} }
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster}) entry := cacheEntry(target, host.IP, strategy)
tags = target.Tags previous := upsertResolved(c, entry)
resolved = hostFromEntry(entry, "live")
resolved.PreviousIP = previous
} }
host.IP = resolved.IP
fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP) fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP)
c.MarkUsed(host.Name) c.MarkUsed(host.Name)
_ = c.Save() _ = c.Save()
client, flags, args := tuiCommand(cfg, host) client, flags, args := tuiCommand(cfg, host)
connectHost(cfg, client, flags, resolvedHost{Name: host.Name, Kind: host.Kind, IP: host.IP, Tags: tags}, []int{len(args) - 1}, args) connectHost(cfg, client, flags, resolved, []int{len(args) - 1}, args)
} }
// tuiCommand builds the client and arguments for the action chosen in the TUI. // tuiCommand builds the client and arguments for the action chosen in the TUI.
@@ -529,7 +709,8 @@ func rootCmd() *cobra.Command {
}, },
} }
root.AddCommand(runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd()) root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd(),
openCmd(), infoCmd(), whoisCmd(), copyIDCmd(), exportCmd(), tokenCmd(), knownHostsCmd(), linkCmd())
// 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()
@@ -780,6 +961,7 @@ func cacheRefreshCmd() *cobra.Command {
return fmt.Errorf("resolver: %w", err) return fmt.Errorf("resolver: %w", err)
} }
written := 0 written := 0
var changed []string
nameCounts := make(map[string]int) nameCounts := make(map[string]int)
for _, e := range entries { for _, e := range entries {
nameCounts[strings.ToLower(e.Target())]++ nameCounts[strings.ToLower(e.Target())]++
@@ -792,7 +974,7 @@ func cacheRefreshCmd() *cobra.Command {
continue continue
} }
ip, err := chain.Resolve(ctx, e, nbClient) ip, strategy, err := chain.ResolveWithStrategy(ctx, e, nbClient)
if err != nil { if err != nil {
// Do not turn a failed configured strategy into a fresh // Do not turn a failed configured strategy into a fresh
// primary-IP cache hit that bypasses the resolver. // primary-IP cache hit that bypasses the resolver.
@@ -803,7 +985,9 @@ func cacheRefreshCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err) fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err)
continue continue
} }
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster}) if previous := upsertResolved(c, cacheEntry(*e, ip, strategy)); previous != "" {
changed = append(changed, fmt.Sprintf("%s: %s → %s", e.Target(), previous, ip))
}
written++ written++
} }
@@ -821,6 +1005,14 @@ func cacheRefreshCmd() *cobra.Command {
} }
} }
fmt.Printf("%d entries written to cache.\n", written) fmt.Printf("%d entries written to cache.\n", written)
if len(changed) > 0 {
sort.Strings(changed)
fmt.Printf("%d hosts changed their address:\n", len(changed))
for _, line := range changed {
fmt.Printf(" %s\n", line)
}
fmt.Println("Remove outdated host keys with: netssh known-hosts reset HOST")
}
return nil return nil
}, },
} }
+201
View File
@@ -0,0 +1,201 @@
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
"github.com/spf13/cobra"
)
func doctorCmd() *cobra.Command {
var online bool
cmd := &cobra.Command{Use: "doctor", Short: "Check configuration, programs, cache and optional NetBox connectivity", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
failed := false
report := func(label string, err error) {
if err != nil {
failed = true
fmt.Fprintf(cmd.OutOrStdout(), "FAIL %s: %v\n", label, err)
} else {
fmt.Fprintf(cmd.OutOrStdout(), "OK %s\n", label)
}
}
report("configuration", nil)
_, err = resolver.New(cfg.Resolver)
report("resolver", err)
programs := map[string]bool{"ssh": true, "sftp": true, "scp": true}
for name, c := range cfg.Commands {
programs[c.Args[0]] = true
if len(c.Args) > 1 && !strings.HasPrefix(c.Args[1], "-") {
switch c.Args[0] {
case "bash", "sh", "python", "python3":
f, err := os.Open(c.Args[1])
if err == nil {
f.Close()
}
report("script "+name, err)
}
}
}
var names []string
for p := range programs {
names = append(names, p)
}
sort.Strings(names)
for _, p := range names {
_, err := exec.LookPath(p)
report("program "+p, err)
}
report("cache", newCache(cfg).Load())
for _, instance := range instanceConfigs(cfg) {
if config.IsKeyringToken(instance.Token) {
_, err := resolveToken(*instance)
report("keyring token "+instance.KeyringAccount(), err)
}
}
if online {
sources := cfg.NetBoxes
if len(sources) == 0 && cfg.NetBox.URL != "" {
sources = []config.NetBoxConfig{cfg.NetBox}
}
for _, s := range sources {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
token, version := clientToken(s)
_, err := netbox.NewClient(s.URL, token, version).Search(ctx, "", netbox.SearchOptions{})
cancel()
report("NetBox "+s.Name, err)
}
}
if failed {
return fmt.Errorf("doctor found problems")
}
return nil
}}
cmd.Flags().BoolVar(&online, "online", false, "Also query every NetBox instance")
return cmd
}
func explainCmd() *cobra.Command {
return &cobra.Command{Use: "explain HOST", Short: "Explain actual host resolution and effective SSH settings without connecting", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, args[0], false)
if err != nil {
return err
}
selectors := commandHost(h)
user, port := hostDefaults(cfg, h)
opts := hostOptions(cfg, h)
var rules []int
for i, r := range cfg.SSH.Rules {
if r.Match.Matches(selectors) {
rules = append(rules, i+1)
}
}
strategy := h.Resolver
if strategy == "" {
if h.Origin == "static" {
strategy = "static address"
} else {
strategy = "not recorded in this cache entry"
}
}
return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{
"target": h.Name, "instance": selectors.Instance, "address": h.IP, "source": h.Origin, "cached_at": h.CachedAt,
"status": h.Status, "site": h.Site.Name, "role": h.Role.Name, "platform": h.Platform.Name, "tenant": h.Tenant.Name, "netbox_id": h.ID, "location": h.LocationPath(),
"resolver_order": cfg.Resolver.Strategies, "resolver_used": strategy, "matching_rules": rules, "user": user, "port": port, "ssh": opts,
})
}}
}
func favoritesCmd() *cobra.Command {
cmd := &cobra.Command{Use: "favorites", Short: "List or change favorite and pinned hosts", RunE: func(cmd *cobra.Command, _ []string) error {
s, err := activity.Read()
if err != nil {
return err
}
var names []string
for n := range s.Favorites {
if s.Favorites[n] {
names = append(names, n)
}
}
sort.Strings(names)
for _, n := range names {
marker := "favorite"
if s.Pinned[n] {
marker = "pinned"
}
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", n, marker)
}
return nil
}}
for _, action := range []string{"add", "remove", "pin", "unpin"} {
cmd.AddCommand(&cobra.Command{Use: action + " HOST", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
target := args[0]
if action == "add" || action == "pin" {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
target = h.Name
}
return activity.Update(func(s *activity.State) {
switch action {
case "add":
s.Favorites[target] = true
case "pin":
s.Favorites[target] = true
s.Pinned[target] = true
case "unpin":
delete(s.Pinned, target)
case "remove":
delete(s.Favorites, target)
delete(s.Pinned, target)
}
})
}})
}
return cmd
}
func historyCmd() *cobra.Command {
cmd := &cobra.Command{Use: "history", Short: "Show optional local action history", RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if err := activity.Update(func(s *activity.State) { activity.Prune(s, cfg.Activity) }); err != nil {
return err
}
s, err := activity.Read()
if err != nil {
return err
}
for i := len(s.Records) - 1; i >= 0; i-- {
r := s.Records[i]
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\texit=%d\t%s\n", r.Time.Format(time.RFC3339), r.Host, r.Command, r.Code, r.Duration.Round(time.Millisecond))
}
return nil
}}
cmd.AddCommand(&cobra.Command{Use: "clear", Short: "Delete recorded actions, preserving favorites", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error {
return activity.Update(func(s *activity.State) { s.Records = nil })
}})
return cmd
}
+258
View File
@@ -0,0 +1,258 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func writeOperationsConfig(t *testing.T, extra string) {
t.Helper()
prepareTransferTest(t)
data := `hosts:
- name: router
address: 192.0.2.1
tags: [router]
- name: fail
address: 192.0.2.2
- name: okay
address: 192.0.2.3
resolver:
strategies: [primary_ip]
` + extra
if err := os.WriteFile(config.Path(), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
func TestPostHooksFiltersAndConfirmation(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "post")
writeOperationsConfig(t, fmt.Sprintf(`
commands:
success:
args: [sh, -c, "exit 0", "{host}"]
post_run: 'printf "%%s:%%s" "$NETSSH_HOST" "$NETSSH_EXIT_CODE" > %s'
failure:
args: [sh, -c, "exit 7", "{host}"]
post_run: 'printf "%%s" "$NETSSH_EXIT_CODE" > %s; exit 9'
postfail:
args: [sh, -c, "exit 0", "{host}"]
post_run: exit 9
protected:
args: [sh, -c, "exit 0", "{host}"]
confirm: true
match: {tag: router, kind: static, name: "rou*"}
timeout:
args: [sh, -c, "sleep 20", "{host}"]
timeout: 50ms
activity:
enabled: true
retention_days: 30
max_entries: 50
`, marker, marker))
if out, err := runNetssh(t, "run", "--dry-run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("dry-run executed post hook")
}
if out, err := runNetssh(t, "run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(marker)
if string(data) != "router:0" {
t.Fatal(string(data))
}
for _, tc := range []struct {
name string
code int
}{{"failure", 7}, {"postfail", 9}, {"timeout", 124}} {
_, err := runNetssh(t, "run", tc.name, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != tc.code {
t.Fatalf("%s: %v", tc.name, err)
}
}
data, _ = os.ReadFile(marker)
if string(data) != "7" {
t.Fatal(string(data))
}
if out, err := runNetssh(t, "run", "protected", "router"); err == nil || !strings.Contains(out, "--yes") {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "router"); err != nil {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "okay"); err == nil || !strings.Contains(out, "not allowed") {
t.Fatalf("%q %v", out, err)
}
state, err := activity.Read()
if err != nil || len(state.Records) != 5 {
t.Fatalf("%+v %v", state, err)
}
}
func TestSSHPostDisconnect(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "after")
writeOperationsConfig(t, fmt.Sprintf("ssh:\n post_disconnect: 'printf \"%%s\" \"$NETSSH_EXIT_CODE\" > %s'\n", marker))
if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nexit 6\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
_, err := runNetssh(t, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 6 {
t.Fatal(err)
}
data, _ := os.ReadFile(marker)
if string(data) != "6" {
t.Fatalf("post: %s", data)
}
}
func TestExplainAndFavorites(t *testing.T) {
writeOperationsConfig(t, "tui:\n history_limit: 25\nssh:\n rules:\n - match: {tag: router}\n post_disconnect: echo done\n")
out, err := runNetssh(t, "explain", "router")
if err != nil {
t.Fatalf("%s %v", out, err)
}
var result map[string]any
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatal(err)
}
if result["source"] != "static" || result["address"] != "192.0.2.1" {
t.Fatal(result)
}
for _, args := range [][]string{{"favorites", "pin", "router"}, {"favorites", "add", "okay"}} {
if out, err := runNetssh(t, args...); err != nil {
t.Fatalf("%s %v", out, err)
}
}
state, err := activity.Read()
if err != nil || !state.Pinned["router"] || !state.Favorites["okay"] {
t.Fatalf("%+v %v", state, err)
}
if out, err := runNetssh(t, "favorites", "remove", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
state, _ = activity.Read()
if state.Pinned["router"] || state.Favorites["router"] {
t.Fatal(state)
}
}
func TestPortableConfigOmitsAllExecutableSecrets(t *testing.T) {
c := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://user:URLSECRET@netbox.example", Token: "TOKEN", SSH: config.SSHOptions{PreConnect: "HOOKSECRET"}}},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{Options: map[string]string{"ProxyCommand": "OPTIONSECRET"}, PostDisconnect: "POSTSECRET"}},
Commands: map[string]config.HostCommand{"check": {Args: []string{"echo", "COMMANDSECRET", "{host}"}}},
Hosts: []config.StaticHost{{Name: "router", Address: "192.0.2.1", SSH: config.SSHOptions{PreConnect: "STATICSECRET"}}},
TUI: config.TUIConfig{HistoryLimit: 25},
}
data, err := json.Marshal(portableConfig(c))
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"URLSECRET", "TOKEN", "HOOKSECRET", "OPTIONSECRET", "POSTSECRET", "COMMANDSECRET", "STATICSECRET"} {
if bytes.Contains(data, []byte(secret)) {
t.Fatalf("export leaked %s", secret)
}
}
parsed, err := decodePortable(data)
if err != nil {
t.Fatal(err)
}
if parsed.TUI.HistoryLimit != 25 || len(parsed.NetBoxes) != 1 || parsed.NetBoxes[0].URL != "https://netbox.example" {
t.Fatalf("%+v", parsed)
}
hostile := []byte("netbox:\n url: https://netbox.example\n token: bad\nssh:\n pre_connect: touch /tmp/never\ncommands:\n check:\n args: [sh, -c, evil]\n")
parsed, err = decodePortable(hostile)
if err != nil || parsed.NetBox.Token != "" || parsed.SSH.PreConnect != "" || len(parsed.Commands) != 0 {
t.Fatalf("%+v %v", parsed, err)
}
}
func TestBatchRetryFailedOnly(t *testing.T) {
bin := filepath.Join(t.TempDir(), "netssh")
build := exec.Command("go", "build", "-o", bin, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build: %s %v", out, err)
}
old := batchExecutable
batchExecutable = func() (string, error) { return bin, nil }
t.Cleanup(func() { batchExecutable = old })
dir := t.TempDir()
script := filepath.Join(dir, "check.sh")
ready := filepath.Join(dir, "ready")
if err := os.WriteFile(script, []byte(fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = fail ] && [ ! -f %q ]; then exit 3; fi\nprintf 'ran %%s\\n' \"$1\"\n", ready)), 0700); err != nil {
t.Fatal(err)
}
writeOperationsConfig(t, fmt.Sprintf("commands:\n check:\n args: [%q, \"{host}\"]\n", script))
run := func(args ...string) (string, error) {
cmd := batchCmd()
cmd.SetArgs(args)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
err := cmd.Execute()
return out.String(), err
}
out, err := run("--parallel", "2", "check", "router", "fail", "okay")
if err == nil || !strings.Contains(out, "2 succeeded, 1 failed") {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(batchPath())
var retry batchRetry
if err := json.Unmarshal(data, &retry); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(retry.Hosts, []string{"fail"}) {
t.Fatalf("%+v", retry)
}
if err := os.WriteFile(ready, nil, 0600); err != nil {
t.Fatal(err)
}
out, err = run("--retry-failed")
if err != nil || !strings.Contains(out, "1 succeeded, 0 failed") || strings.Contains(out, "ran router") {
t.Fatalf("%s %v", out, err)
}
}
func TestImportPreservesOnlyMatchingCredentials(t *testing.T) {
writeOperationsConfig(t, "")
original := []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: LOCALPROD\n - name: lab\n url: https://lab.example\n token: LOCALLAB\ncommands:\n local:\n args: [echo, \"{host}\"]\n")
if err := os.WriteFile(config.Path(), original, 0600); err != nil {
t.Fatal(err)
}
shared := filepath.Join(t.TempDir(), "shared.yaml")
if err := os.WriteFile(shared, []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: UNTRUSTED\n - name: lab\n url: https://other.example\ntui:\n history_limit: 25\nssh:\n pre_connect: evil\n"), 0600); err != nil {
t.Fatal(err)
}
if out, err := runNetssh(t, "config", "import", shared, "--dry-run"); err != nil {
t.Fatalf("%s %v", out, err)
}
after, _ := os.ReadFile(config.Path())
if !bytes.Equal(original, after) {
t.Fatal("preview changed config")
}
if out, err := runNetssh(t, "config", "import", shared, "--yes"); err != nil {
t.Fatalf("%s %v", out, err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
if cfg.NetBoxes[0].Token != "LOCALPROD" || cfg.NetBoxes[1].Token != "" || cfg.SSH.PreConnect != "" || len(cfg.Commands) != 1 || cfg.TUI.HistoryLimit != 25 {
t.Fatalf("incorrect imported settings: names=%d tui=%d", len(cfg.NetBoxes), cfg.TUI.HistoryLimit)
}
backup, _ := os.ReadFile(config.Path() + ".before-import")
if !bytes.Equal(backup, original) {
t.Fatal("backup differs")
}
}
+164
View File
@@ -0,0 +1,164 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Portable config deliberately omits arbitrary command/hook/SSH option strings:
// secrets may be embedded there, and cannot reliably be detected by key name.
func portableConfig(c config.Config) map[string]any {
cleanURL := func(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
u.User = nil
u.RawQuery = ""
u.Fragment = ""
return u.String()
}
sources := []map[string]any{}
for _, s := range c.NetBoxes {
sources = append(sources, map[string]any{"name": s.Name, "url": cleanURL(s.URL), "disable_prefix": s.DisablePrefix})
}
hosts := []map[string]any{}
for _, h := range c.Hosts {
hosts = append(hosts, map[string]any{"name": h.Name, "address": h.Address, "user": h.User, "port": h.Port, "tags": h.Tags})
}
rewrites := []map[string]string{}
for _, r := range c.Shortcuts.Rewrites {
rewrites = append(rewrites, map[string]string{"pattern": r.Pattern, "replace": r.Replace})
}
out := map[string]any{
"hosts": hosts, "groups": c.Groups,
"ssh": map[string]any{"default_user": c.SSH.DefaultUser, "default_port": c.SSH.DefaultPort},
"resolver": map[string]any{"strategies": c.Resolver.Strategies, "management_subnets": c.Resolver.ManagementSubnets, "interface_name": c.Resolver.InterfaceName, "hostname_domain": c.Resolver.HostnameDomain},
"shortcuts": map[string]any{"domains": c.Shortcuts.Domains, "rewrites": rewrites, "strip_hyphens": c.Shortcuts.StripHyphens, "show": c.Shortcuts.Show},
"completion": map[string]any{"max_results": c.Completion.MaxResults},
"tui": map[string]any{"history_limit": c.TUI.HistoryLimit},
}
if len(sources) > 0 {
out["netboxes"] = sources
} else if c.NetBox.URL != "" {
out["netbox"] = map[string]string{"url": cleanURL(c.NetBox.URL)}
}
return out
}
func decodePortable(data []byte) (config.Config, error) {
v := viper.New()
v.SetConfigType("yaml")
v.SetDefault("tui.history_limit", 10)
var c config.Config
if err := v.ReadConfig(bytes.NewReader(data)); err != nil {
return c, err
}
if err := v.Unmarshal(&c); err != nil {
return c, err
}
// Strip executable settings and credentials even from externally edited files.
safe, _ := json.Marshal(portableConfig(c))
v = viper.New()
v.SetConfigType("json")
if err := v.ReadConfig(bytes.NewReader(safe)); err != nil {
return c, err
}
c = config.Config{}
err := v.Unmarshal(&c)
return c, err
}
func configCmd() *cobra.Command {
cmd := &cobra.Command{Use: "config", Short: "Share configuration without credentials or executable settings"}
export := &cobra.Command{Use: "export [FILE]", Short: "Export a secret-free JSON configuration (also valid YAML)", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
data, err := json.MarshalIndent(portableConfig(*cfg), "", " ")
if err != nil {
return err
}
if len(args) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), string(data))
return nil
}
return storage.WriteFile(args[0], append(data, '\n'), 0600)
}}
var yes, dry bool
imp := &cobra.Command{Use: "import FILE", Short: "Import shared host settings; preserve matching local credentials and commands", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
data, err := os.ReadFile(args[0])
if err != nil {
return err
}
incoming, err := decodePortable(data)
if err != nil {
return err
}
current, err := config.Load()
if err != nil {
return err
}
same := func(a, b string) bool { return strings.TrimRight(a, "/") == strings.TrimRight(b, "/") }
for i := range incoming.NetBoxes {
for _, old := range current.NetBoxes {
s := &incoming.NetBoxes[i]
if strings.EqualFold(s.Name, old.Name) && same(s.URL, old.URL) {
s.Token = old.Token
s.TokenVersion = old.TokenVersion
s.SSH = old.SSH
}
}
}
if incoming.NetBox.URL != "" && same(incoming.NetBox.URL, current.NetBox.URL) {
incoming.NetBox.Token = current.NetBox.Token
incoming.NetBox.TokenVersion = current.NetBox.TokenVersion
incoming.NetBox.SSH = current.NetBox.SSH
}
incoming.Commands = current.Commands
incoming.Activity = current.Activity
incoming.Cache = current.Cache
incoming.Multi = current.Multi
incoming.Shell = current.Shell
incoming.SSH.SSHOptions = current.SSH.SSHOptions
incoming.SSH.Rules = current.SSH.Rules
for i := range incoming.Hosts {
for _, old := range current.Hosts {
if incoming.Hosts[i].Name == old.Name && incoming.Hosts[i].Address == old.Address {
incoming.Hosts[i].SSH = old.SSH
}
}
}
for _, validate := range []func() error{incoming.ValidateNetBoxes, incoming.ValidateHosts, incoming.ValidateSSH, incoming.ValidateCommands, incoming.ValidateOperations, incoming.Shortcuts.Validate, incoming.ValidateMulti} {
if err := validate(); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "Import: %d named instances, %d static hosts. Local commands and matching credentials are retained.\n", len(incoming.NetBoxes), len(incoming.Hosts))
if dry {
return nil
}
if err := confirmAction("Replace shared configuration settings", yes); err != nil {
return err
}
if existing, err := os.ReadFile(config.Path()); err == nil {
if err := storage.WriteFile(config.Path()+".before-import", existing, 0600); err != nil {
return err
}
}
return setup.Save(incoming)
}}
imp.Flags().BoolVar(&yes, "yes", false, "Approve replacing shared configuration settings")
imp.Flags().BoolVar(&dry, "dry-run", false, "Validate and preview without writing")
cmd.AddCommand(export, imp)
return cmd
}
+31 -8
View File
@@ -3,13 +3,13 @@ package main
import ( import (
"fmt" "fmt"
"os" "os"
"os/exec"
"sort" "sort"
"strings" "strings"
"syscall" "time"
"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/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -25,7 +25,7 @@ func expandHostCommand(command config.HostCommand, host resolvedHost, extra []st
} }
func runCmd() *cobra.Command { func runCmd() *cobra.Command {
var dryRun bool var dryRun, yes, status bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]", Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
Short: "Run a configured local command for a NetBox or static host", Short: "Run a configured local command for a NetBox or static host",
@@ -39,9 +39,18 @@ func runCmd() *cobra.Command {
if !ok { if !ok {
return fmt.Errorf("unknown configured command %q", args[0]) return fmt.Errorf("unknown configured command %q", args[0])
} }
host := resolveTarget(cfg, args[1]) host, err := resolveTargetE(cfg, args[1], !dryRun)
if err != nil {
return err
}
if !command.Allowed(commandHost(host)) {
return fmt.Errorf("command %q is not allowed for %s", args[0], host.Name)
}
argv := expandHostCommand(command, host, args[2:]) argv := expandHostCommand(command, host, args[2:])
if dryRun { if dryRun {
if post := config.HookCommand(command.PostRun); post != "" {
fmt.Fprintf(cmd.ErrOrStderr(), "# post_run (skipped in --dry-run): %s\n", post)
}
for i, arg := range argv { for i, arg := range argv {
if i > 0 { if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ") fmt.Fprint(cmd.OutOrStdout(), " ")
@@ -51,11 +60,19 @@ func runCmd() *cobra.Command {
fmt.Fprintln(cmd.OutOrStdout()) fmt.Fprintln(cmd.OutOrStdout())
return nil return nil
} }
path, err := exec.LookPath(argv[0]) if command.Confirm {
if err != nil { if err := confirmAction("Run "+args[0]+" on "+host.Name, yes); err != nil {
return fmt.Errorf("%s not found in PATH: %w", argv[0], err) return err
} }
return syscall.Exec(path, argv, os.Environ()) }
timeout, _ := time.ParseDuration(command.Timeout)
code := supervise(cfg, host, args[0], argv, command.PostRun, timeout, status || term.IsTerminal(os.Stderr.Fd()), os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr())
if code != 0 {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
return &commandExit{code}
}
return nil
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 { if len(args) == 0 {
@@ -78,6 +95,12 @@ func runCmd() *cobra.Command {
return nil, cobra.ShellCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}, },
} }
cmd.Flags().BoolVar(&yes, "yes", false, "Approve an action requiring confirmation")
cmd.Flags().BoolVar(&status, "status", false, "Show elapsed runtime")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
return cmd return cmd
} }
type commandExit struct{ code int }
func (e *commandExit) Error() string { return fmt.Sprintf("command exited with status %d", e.code) }
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"github.com/charmbracelet/x/term"
)
func commandHost(h resolvedHost) config.SSHHost {
instance, name := netbox.SplitTarget(h.Name)
return config.SSHHost{Instance: instance, Name: name, Kind: h.Kind, Tags: h.Tags, Status: h.Status, Site: h.Site, Role: h.Role, Platform: h.Platform, Tenant: h.Tenant}
}
func confirmAction(message string, yes bool) error {
if yes {
return nil
}
if !term.IsTerminal(os.Stdin.Fd()) {
return fmt.Errorf("%s requires confirmation; use --yes for unattended execution", message)
}
fmt.Fprintf(os.Stderr, "%s? [y/N] ", message)
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return err
}
if strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes") {
return nil
}
return fmt.Errorf("cancelled")
}
func supervise(cfg *config.Config, h resolvedHost, name string, argv []string, post string, timeout time.Duration, status bool, stdin io.Reader, stdout, stderr io.Writer) int {
start := time.Now()
env := append(preConnectEnv(h, name), "NETSSH_COMMAND="+name)
result := runner.Run(context.Background(), argv, runner.Options{Stdin: stdin, Stdout: stdout, Stderr: stderr, Env: env, Timeout: timeout, Status: status, Label: name + " " + h.Name})
code := result.Code
if result.Started && config.HookCommand(post) != "" {
hook := runner.Run(context.Background(), []string{"sh", "-c", post}, runner.Options{Stdin: nil, Stdout: stderr, Stderr: stderr, Env: append(env, "NETSSH_EXIT_CODE="+strconv.Itoa(code)), Timeout: 30 * time.Second})
if hook.Code != 0 {
fmt.Fprintf(stderr, "post hook failed (exit %d)\n", hook.Code)
if code == 0 {
code = hook.Code
}
}
}
if err := activity.Append(cfg.Activity, activity.Record{Time: start, Host: h.Name, Command: name, Code: code, Duration: time.Since(start)}); err != nil {
fmt.Fprintf(stderr, "activity: %v\n", err)
}
return code
}
+14
View File
@@ -0,0 +1,14 @@
package main
import (
"os"
"testing"
)
// Integration helpers run this test binary as netssh. An automatic refresh
// would otherwise launch the test binary again with "cache refresh", rerunning
// the entire suite. Explicit cache-refresh tests still exercise the real command.
func TestMain(m *testing.M) {
_ = os.Setenv("NETSSH_NO_REFRESH", "1")
os.Exit(m.Run())
}
+260
View File
@@ -0,0 +1,260 @@
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"text/tabwriter"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra"
"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/secret"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
)
var (
tokenMu sync.Mutex
tokenCache = map[string]string{}
)
// resolveToken returns the API token of an instance: the configured value,
// or the keyring entry when the value is "keyring". Lookups are cached per
// process, since each one can be a D-Bus round trip.
func resolveToken(n config.NetBoxConfig) (string, error) {
if !config.IsKeyringToken(n.Token) {
return n.Token, nil
}
account := n.KeyringAccount()
tokenMu.Lock()
defer tokenMu.Unlock()
if token, ok := tokenCache[account]; ok {
return token, nil
}
token, err := secret.Get(account)
if err != nil {
return "", err
}
tokenCache[account] = token
return token, nil
}
// clientToken resolves a token for a client; a failure is reported once and
// leaves the token empty, so NetBox answers with a clear authentication error.
func clientToken(n config.NetBoxConfig) (string, int) {
token, err := resolveToken(n)
if err != nil {
label := n.Name
if label == "" {
label = "netbox"
}
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", label, err)
return "", n.TokenVersion
}
version := n.TokenVersion
if config.IsKeyringToken(n.Token) {
version = netbox.TokenVersion(token)
}
return token, version
}
// instanceConfigs returns the configured NetBox instances, including the
// legacy unnamed one.
func instanceConfigs(cfg *config.Config) []*config.NetBoxConfig {
var out []*config.NetBoxConfig
for i := range cfg.NetBoxes {
out = append(out, &cfg.NetBoxes[i])
}
if len(out) == 0 && cfg.NetBox.URL != "" {
out = append(out, &cfg.NetBox)
}
return out
}
// selectInstance finds the instance named in args, or the only one.
func selectInstance(cfg *config.Config, args []string) (*config.NetBoxConfig, error) {
instances := instanceConfigs(cfg)
if len(instances) == 0 {
return nil, errors.New("no NetBox is configured (netssh configure)")
}
if len(args) == 0 {
if len(instances) == 1 {
return instances[0], nil
}
return nil, fmt.Errorf("name the NetBox instance: %s", strings.Join(instanceNames(cfg), ", "))
}
for _, instance := range instances {
if strings.EqualFold(instance.Name, args[0]) || (instance.Name == "" && strings.EqualFold(args[0], "default")) {
return instance, nil
}
}
return nil, fmt.Errorf("unknown NetBox instance %q", args[0])
}
// readToken reads a token without echo from a terminal, or a line from stdin.
func readToken(label string, stdin io.Reader) (string, error) {
if f, ok := stdin.(*os.File); ok && term.IsTerminal(f.Fd()) {
fmt.Fprintf(os.Stderr, "NetBox API token for %s: ", label)
data, err := term.ReadPassword(f.Fd())
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
line, err := bufio.NewReader(stdin).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
return strings.TrimSpace(line), nil
}
// saveConfig is replaced in tests.
var saveConfig = setup.Save
func tokenCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token",
Short: "Keep NetBox API tokens in the system keyring",
Long: `Store NetBox API tokens in the system keyring (Secret Service / GNOME Keyring /
KWallet on Linux, Keychain on macOS) instead of the config file. The config
then contains token: keyring, and netssh reads the token from the keyring.
NETSSH_NETBOX_TOKEN still overrides the token of the unnamed instance.`,
}
cmd.AddCommand(tokenSetCmd(), tokenMigrateCmd(), tokenDeleteCmd(), tokenStatusCmd())
return cmd
}
func tokenSetCmd() *cobra.Command {
return &cobra.Command{
Use: "set [INSTANCE]",
Short: "Store a token in the keyring and switch the config to token: keyring",
Long: "Read the token without echo (or from stdin) and store it in the keyring.\nExample for scripts: echo \"$TOKEN\" | netssh token set prod",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
instance, err := selectInstance(cfg, args)
if err != nil {
return err
}
token, err := readToken(instance.KeyringAccount(), cmd.InOrStdin())
if err != nil {
return err
}
if token == "" || config.IsKeyringToken(token) {
return errors.New("no token given")
}
if err := secret.Set(instance.KeyringAccount(), token); err != nil {
return err
}
instance.Token, instance.TokenVersion = config.KeyringToken, netbox.TokenVersion(token)
if err := saveConfig(*cfg); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "Token for %s stored in the system keyring.\n", instance.KeyringAccount())
return nil
},
}
}
func tokenMigrateCmd() *cobra.Command {
return &cobra.Command{
Use: "migrate",
Short: "Move all tokens from the config file into the keyring",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
moved := 0
for _, instance := range instanceConfigs(cfg) {
if instance.Token == "" || config.IsKeyringToken(instance.Token) {
continue
}
if err := secret.Set(instance.KeyringAccount(), instance.Token); err != nil {
return err
}
instance.TokenVersion = netbox.TokenVersion(instance.Token)
instance.Token = config.KeyringToken
moved++
fmt.Fprintf(cmd.OutOrStdout(), "%s: moved to the keyring\n", instance.KeyringAccount())
}
if moved == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No tokens in the config file.")
return nil
}
return saveConfig(*cfg)
},
}
}
func tokenDeleteCmd() *cobra.Command {
return &cobra.Command{
Use: "delete [INSTANCE]",
Short: "Remove a token from the keyring",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
instance, err := selectInstance(cfg, args)
if err != nil {
return err
}
if err := secret.Delete(instance.KeyringAccount()); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "Token for %s removed from the keyring.\n", instance.KeyringAccount())
if config.IsKeyringToken(instance.Token) {
fmt.Fprintln(cmd.OutOrStdout(), "The config still says token: keyring; store a new one with netssh token set.")
}
return nil
},
}
}
func tokenStatusCmd() *cobra.Command {
return &cobra.Command{
Use: "status",
Short: "Show where each instance's token comes from",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "INSTANCE\tTOKEN")
for _, instance := range instanceConfigs(cfg) {
fmt.Fprintf(w, "%s\t%s\n", instance.KeyringAccount(), tokenSource(*instance))
}
return w.Flush()
},
}
}
func tokenSource(n config.NetBoxConfig) string {
switch {
case n.Token == "":
return "missing"
case config.IsKeyringToken(n.Token):
if _, err := resolveToken(n); err != nil {
return "keyring (not readable: " + err.Error() + ")"
}
return "keyring"
default:
return "config file (plain text; move it with netssh token migrate)"
}
}
+6
View File
@@ -136,6 +136,12 @@ func completeHosts(toComplete string) []string {
c := newCache(cfg) c := newCache(cfg)
_ = c.Load() _ = c.Load()
hosts := hostCompletions(c.All(), toComplete, cfg.Shortcuts) hosts := hostCompletions(c.All(), toComplete, cfg.Shortcuts)
for name := range cfg.Links {
if strings.HasPrefix(strings.ToLower(name), strings.ToLower(toComplete)) {
hosts = append(hosts, strings.ToLower(name))
}
}
sort.Strings(hosts)
if limit := cfg.Completion.MaxResults; limit > 0 && len(hosts) > limit { if limit := cfg.Completion.MaxResults; limit > 0 && len(hosts) > limit {
hosts = hosts[:limit] hosts = hosts[:limit]
} }
+87
View File
@@ -0,0 +1,87 @@
package main
import (
"context"
"fmt"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/tui"
)
// configureTUIExtras wires reachability, the detail view and opening NetBox
// pages into the TUI. known enriches a listed host from the cache.
func configureTUIExtras(m *tui.Model, cfg *config.Config, client *netbox.Client, known func(name, kind string, tags []string) resolvedHost) {
m.SetColumns(cfg.TUI.EffectiveColumns())
if cfg.TUI.ReachabilityEnabled() {
m.SetReachability(cfg.TUI.ReachabilityTimeoutDuration(), func(name, kind string, tags []string) (int, bool) {
h := known(name, kind, tags)
if usesJumpHost(hostOptions(cfg, h), internalssh.WrapperFlags{}) {
return 0, false
}
_, port := hostDefaults(cfg, h)
if port <= 0 {
port = 22
}
return port, true
})
}
lookup := func(ctx context.Context, name, kind string, id int) (netbox.HostEntry, resolvedHost, error) {
h := known(name, kind, nil)
if kind == config.StaticKind {
return netbox.HostEntry{}, h, fmt.Errorf("%s is a static host and has no NetBox record", name)
}
if client == nil {
return netbox.HostEntry{}, h, fmt.Errorf("no NetBox is configured")
}
if id <= 0 {
id = h.ID
}
entry, _, h, err := netboxEntry(ctx, client, name, kind, id, h)
return entry, h, err
}
m.SetOpener(func(name, kind string, id int) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
entry, _, err := lookup(ctx, name, kind, id)
if err != nil {
return err
}
url, err := client.WebURL(entry)
if err != nil {
return err
}
return openBrowser(url)
})
m.SetDetails(func(name, kind string, id int) (string, error) {
if kind == config.StaticKind {
h := known(name, kind, nil)
user, port := hostDefaults(cfg, h)
text := fmt.Sprintf("%s (static host from hosts:)\n Address %s\n", name, h.IP)
if user != "" {
text += " User " + user + "\n"
}
if port > 0 {
text += fmt.Sprintf(" Port %d\n", port)
}
return text, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
entry, h, err := lookup(ctx, name, kind, id)
if err != nil {
return "", err
}
details, err := client.GetDetails(ctx, entry)
if err != nil && details.Name == "" {
return "", err
}
text := formatDetails(details, h)
if err != nil {
text += "\nwarning: " + err.Error() + "\n"
}
return text, nil
})
}
+3 -3
View File
@@ -204,10 +204,10 @@ func uninstallCmd() *cobra.Command {
- netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles - netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles
- shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias) - shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias)
- the cache directory with hosts, aliases, and per-instance caches - the cache directory with hosts, aliases, and per-instance caches
- the config file (a private backup is kept) and local server notes - the config file (a private backup is kept) and local notes, favorites, action history and batch retry state
- the netssh binary - the netssh binary
Use --keep-config to keep the config file and notes for a reinstall.`, Use --keep-config to keep the config file and local state for a reinstall.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load() cfg, err := config.Load()
@@ -244,7 +244,7 @@ Use --keep-config to keep the config file and notes for a reinstall.`,
return err return err
}, },
} }
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local notes") cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local state")
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation") cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed")
return cmd return cmd
+6 -2
View File
@@ -7,12 +7,16 @@ require (
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.1
github.com/charmbracelet/x/term v0.2.2
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
github.com/zalando/go-keyring v0.2.6
go.yaml.in/yaml/v3 v3.0.6
golang.org/x/sys v0.50.0 golang.org/x/sys v0.50.0
) )
require ( require (
al.essio.dev/pkg/shellescape v1.5.1 // indirect
github.com/atotto/clipboard v0.1.4 // indirect github.com/atotto/clipboard v0.1.4 // indirect
github.com/catppuccin/go v0.3.0 // indirect github.com/catppuccin/go v0.3.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect
@@ -21,15 +25,16 @@ require (
github.com/charmbracelet/x/exp/golden v0.1.0 // indirect github.com/charmbracelet/x/exp/golden v0.1.0 // indirect
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
github.com/charmbracelet/x/exp/strings v0.1.0 // indirect github.com/charmbracelet/x/exp/strings v0.1.0 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/charmbracelet/x/xpty v0.1.4 // indirect github.com/charmbracelet/x/xpty v0.1.4 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/danieljoos/wincred v1.2.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect github.com/dustin/go-humanize v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/google/go-cmp v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
@@ -47,7 +52,6 @@ require (
github.com/stretchr/testify v1.12.1 // indirect github.com/stretchr/testify v1.12.1 // indirect
github.com/subosito/gotenv v1.6.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect
github.com/xo/terminfo v1.3.1 // indirect github.com/xo/terminfo v1.3.1 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/sync v0.25.0 // indirect golang.org/x/sync v0.25.0 // indirect
golang.org/x/text v0.44.0 // indirect golang.org/x/text v0.44.0 // indirect
) )
+12
View File
@@ -1,3 +1,5 @@
al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho=
al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890=
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU= charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU= charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
@@ -43,6 +45,8 @@ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJ
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0=
github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -51,8 +55,12 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -91,12 +99,16 @@ github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/xo/terminfo v1.3.1 h1:4ZwPCuu4PEFw0PkNp3Hv/x3gqvgLCzYhurszsj101cM= github.com/xo/terminfo v1.3.1 h1:4ZwPCuu4PEFw0PkNp3Hv/x3gqvgLCzYhurszsj101cM=
github.com/xo/terminfo v1.3.1/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio= github.com/xo/terminfo v1.3.1/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s=
github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+94
View File
@@ -0,0 +1,94 @@
// Package activity stores local preferences and optional execution metadata.
// No command arguments, environment variables, tokens or command output are logged.
package activity
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"golang.org/x/sys/unix"
)
type Record struct {
Time time.Time `json:"time"`
Host string `json:"host"`
Command string `json:"command"`
Code int `json:"exit_code"`
Duration time.Duration `json:"duration_ns"`
}
type State struct {
Favorites map[string]bool `json:"favorites,omitempty"`
Pinned map[string]bool `json:"pinned,omitempty"`
Records []Record `json:"records,omitempty"`
}
func Path() string { return filepath.Join(filepath.Dir(config.Path()), "netssh", "activity.json") }
func Read() (State, error) {
var s State
data, err := os.ReadFile(Path())
if os.IsNotExist(err) {
err = nil
} else if err == nil {
err = json.Unmarshal(data, &s)
}
if s.Favorites == nil {
s.Favorites = map[string]bool{}
}
if s.Pinned == nil {
s.Pinned = map[string]bool{}
}
return s, err
}
func Update(change func(*State)) error {
p := Path()
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
return err
}
f, err := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
defer f.Close()
if err = unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
s, err := Read()
if err != nil {
return fmt.Errorf("local state: %w", err)
}
change(&s)
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return storage.WriteFile(p, data, 0600)
}
func Prune(s *State, c config.ActivityConfig) {
if c.RetentionDays > 0 {
cutoff := time.Now().Add(-time.Duration(c.RetentionDays) * 24 * time.Hour)
keep := s.Records[:0]
for _, r := range s.Records {
if !r.Time.Before(cutoff) {
keep = append(keep, r)
}
}
s.Records = keep
}
sort.SliceStable(s.Records, func(i, j int) bool { return s.Records[i].Time.Before(s.Records[j].Time) })
if c.MaxEntries > 0 && len(s.Records) > c.MaxEntries {
s.Records = s.Records[len(s.Records)-c.MaxEntries:]
}
}
func Append(c config.ActivityConfig, r Record) error {
if !c.Enabled {
return nil
}
return Update(func(s *State) { s.Records = append(s.Records, r); Prune(s, c) })
}
+59
View File
@@ -0,0 +1,59 @@
package activity
import (
"fmt"
"os"
"sync"
"testing"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestConcurrentActivityAndRetention(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.ActivityConfig{Enabled: true, RetentionDays: 1, MaxEntries: 10}
if err := Update(func(s *State) {
s.Favorites["prod/web"] = true
s.Pinned["prod/web"] = true
s.Records = []Record{{Time: time.Now().Add(-48 * time.Hour), Host: "old"}}
}); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := Append(cfg, Record{Time: time.Now(), Host: fmt.Sprint(i), Command: "test"}); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
s, err := Read()
if err != nil {
t.Fatal(err)
}
if len(s.Records) != 10 || !s.Favorites["prod/web"] || !s.Pinned["prod/web"] {
t.Fatalf("%+v", s)
}
for _, r := range s.Records {
if r.Host == "old" {
t.Fatal("expired record retained")
}
}
info, _ := os.Stat(Path())
if info.Mode().Perm() != 0600 {
t.Fatal(info.Mode())
}
}
func TestDisabledHistoryDoesNotWrite(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := Append(config.ActivityConfig{}, Record{}); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(Path()); !os.IsNotExist(err) {
t.Fatal("disabled history wrote data")
}
}
+29
View File
@@ -17,11 +17,24 @@ import (
) )
type Entry struct { type Entry struct {
Resolver string `json:"resolver,omitempty"`
Name string `json:"name"` Name string `json:"name"`
IP string `json:"ip"` IP string `json:"ip"`
Kind string `json:"kind"` Kind string `json:"kind"`
Tags []string `json:"tags,omitempty"` Tags []string `json:"tags,omitempty"`
Cluster string `json:"cluster,omitempty"` Cluster string `json:"cluster,omitempty"`
// ID, Status, Site, Role, Platform and Tenant come from NetBox; entries
// written by older versions lack them until the next refresh.
ID int `json:"id,omitempty"`
Status string `json:"status,omitempty"`
Site *config.Ref `json:"site,omitempty"`
Role *config.Ref `json:"role,omitempty"`
Platform *config.Ref `json:"platform,omitempty"`
Tenant *config.Ref `json:"tenant,omitempty"`
// Location is the chain of nested locations below the site, outermost first.
Location []config.Ref `json:"location,omitempty"`
Rack string `json:"rack,omitempty"`
Position string `json:"position,omitempty"`
CachedAt time.Time `json:"cached_at"` CachedAt time.Time `json:"cached_at"`
LastUsed time.Time `json:"last_used,omitempty"` LastUsed time.Time `json:"last_used,omitempty"`
// Static marks a host from the config's hosts: list. It never expires; // Static marks a host from the config's hosts: list. It never expires;
@@ -426,3 +439,19 @@ func (c *Cache) All() []Entry {
} }
return out return out
} }
// RefPtr returns nil for an empty reference, keeping the cache file small.
func RefPtr(r config.Ref) *config.Ref {
if r == (config.Ref{}) {
return nil
}
return &r
}
// RefOf returns the referenced value, or an empty Ref.
func RefOf(r *config.Ref) config.Ref {
if r == nil {
return config.Ref{}
}
return *r
}
+19
View File
@@ -4,10 +4,15 @@ import (
"fmt" "fmt"
"regexp" "regexp"
"strings" "strings"
"time"
) )
// HostCommand defines a local command and the prefix of its generated host aliases. // HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct { type HostCommand struct {
PostRun string `mapstructure:"post_run"`
Match SSHMatch `mapstructure:"match"`
Confirm bool `mapstructure:"confirm"`
Timeout string `mapstructure:"timeout"`
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"` AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
Args []string `mapstructure:"args" yaml:"args"` Args []string `mapstructure:"args" yaml:"args"`
} }
@@ -15,6 +20,20 @@ type HostCommand struct {
func (c *Config) ValidateCommands() error { func (c *Config) ValidateCommands() error {
prefixes := make(map[string]bool) prefixes := make(map[string]bool)
for name, command := range c.Commands { for name, command := range c.Commands {
if strings.ContainsRune(command.PostRun, 0) {
return fmt.Errorf("commands.%s.post_run contains NUL", name)
}
if command.Match != (SSHMatch{}) {
if err := command.Match.Validate("commands." + name); err != nil {
return err
}
}
if command.Timeout != "" {
d, err := time.ParseDuration(command.Timeout)
if err != nil || d <= 0 {
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
}
}
if name == "" || ValidateCommandAlias(name) != nil { if name == "" || ValidateCommandAlias(name) != nil {
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name) return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
} }
+84 -3
View File
@@ -6,11 +6,14 @@ import (
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"time"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type Config struct { type Config struct {
TUI TUIConfig `mapstructure:"tui"`
Activity ActivityConfig `mapstructure:"activity"`
Commands map[string]HostCommand `mapstructure:"commands"` Commands map[string]HostCommand `mapstructure:"commands"`
Shell ShellConfig `mapstructure:"shell"` Shell ShellConfig `mapstructure:"shell"`
NetBox NetBoxConfig `mapstructure:"netbox"` NetBox NetBoxConfig `mapstructure:"netbox"`
@@ -23,6 +26,11 @@ type Config struct {
Hosts []StaticHost `mapstructure:"hosts"` Hosts []StaticHost `mapstructure:"hosts"`
// Groups name lists of hosts and selectors for netssh multi (@name). // Groups name lists of hosts and selectors for netssh multi (@name).
Groups map[string][]string `mapstructure:"groups"` Groups map[string][]string `mapstructure:"groups"`
// Links map a short name to a host selector: netssh NAME connects to it,
// and the shell gets an alias NAME. Created after a DNS suggestion or
// with netssh link add.
Links map[string]string `mapstructure:"links"`
DNS DNSConfig `mapstructure:"dns"`
Multi MultiConfig `mapstructure:"multi"` Multi MultiConfig `mapstructure:"multi"`
} }
@@ -40,6 +48,11 @@ type NetBoxConfig struct {
} }
type ResolverConfig struct { type ResolverConfig struct {
// Fallback tries the addresses of the other strategies when the chosen
// address does not accept TCP connections on the SSH port.
Fallback bool `mapstructure:"fallback"`
// FallbackTimeout is the per-address connect timeout in milliseconds; 0 = 1000.
FallbackTimeout int `mapstructure:"fallback_timeout"`
Strategies []string `mapstructure:"strategies"` Strategies []string `mapstructure:"strategies"`
ManagementSubnets []string `mapstructure:"management_subnets"` ManagementSubnets []string `mapstructure:"management_subnets"`
InterfaceName string `mapstructure:"interface_name"` InterfaceName string `mapstructure:"interface_name"`
@@ -55,6 +68,9 @@ type CacheConfig struct {
type SSHConfig struct { type SSHConfig struct {
DefaultUser string `mapstructure:"default_user"` DefaultUser string `mapstructure:"default_user"`
DefaultPort int `mapstructure:"default_port"` DefaultPort int `mapstructure:"default_port"`
// WarnStatus lists NetBox status values that ask before connecting;
// nil means DefaultWarnStatus, an empty list disables the question.
WarnStatus []string `mapstructure:"warn_status"`
SSHOptions `mapstructure:",squash"` SSHOptions `mapstructure:",squash"`
Rules []SSHRule `mapstructure:"rules"` Rules []SSHRule `mapstructure:"rules"`
} }
@@ -98,6 +114,51 @@ func (s ShortcutsConfig) Validate() error {
return nil return nil
} }
// DefaultWarnStatus are the NetBox status values that ask before connecting.
var DefaultWarnStatus = []string{"offline", "planned", "staged", "failed", "inventory", "decommissioning"}
// KeyringToken as a token value reads the token from the system keyring.
const KeyringToken = "keyring"
// IsKeyringToken reports whether token refers to the system keyring.
func IsKeyringToken(token string) bool {
return strings.EqualFold(strings.TrimSpace(token), KeyringToken)
}
// KeyringAccount is the keyring entry of a NetBox instance; the unnamed
// single-instance configuration uses "default".
func (n NetBoxConfig) KeyringAccount() string {
if n.Name == "" {
return "default"
}
return strings.ToLower(n.Name)
}
// WarnsStatus reports whether status is configured to ask before connecting.
func (s SSHConfig) WarnsStatus(status string) bool {
if status == "" {
return false
}
list := s.WarnStatus
if list == nil {
list = DefaultWarnStatus
}
for _, warn := range list {
if strings.EqualFold(strings.TrimSpace(warn), status) {
return true
}
}
return false
}
// FallbackTimeoutDuration returns resolver.fallback_timeout, 1s by default.
func (r ResolverConfig) FallbackTimeoutDuration() time.Duration {
if r.FallbackTimeout <= 0 {
return time.Second
}
return time.Duration(r.FallbackTimeout) * time.Millisecond
}
// Path returns the canonical config file path. // Path returns the canonical config file path.
func Path() string { func Path() string {
configDir, err := os.UserConfigDir() configDir, err := os.UserConfigDir()
@@ -113,6 +174,9 @@ func Load() (*Config, error) {
v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"}) v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"})
v.SetDefault("resolver.management_subnets", []string{}) v.SetDefault("resolver.management_subnets", []string{})
v.SetDefault("cache.ttl", 3600) v.SetDefault("cache.ttl", 3600)
v.SetDefault("tui.history_limit", 10)
v.SetDefault("activity.retention_days", 30)
v.SetDefault("activity.max_entries", 1000)
configDir, err := os.UserConfigDir() configDir, err := os.UserConfigDir()
if err == nil { if err == nil {
@@ -126,7 +190,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", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window", "ssh.warn_status", "tui.columns", "tui.reachability_timeout", "resolver.fallback", "resolver.fallback_timeout", "dns.suggest", "dns.save_link"} {
if err := v.BindEnv(key); err != nil { if err := v.BindEnv(key); err != nil {
return nil, err return nil, err
} }
@@ -142,6 +206,14 @@ func Load() (*Config, error) {
if err := v.Unmarshal(&cfg); err != nil { if err := v.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err) return nil, fmt.Errorf("parsing config: %w", err)
} }
// "columns: []" shows only the hostname; only a missing key means the default.
if cfg.TUI.Columns == nil && v.IsSet("tui.columns") {
cfg.TUI.Columns = []string{}
}
// "warn_status: []" disables the question; only a missing key means the default.
if cfg.SSH.WarnStatus == nil && v.IsSet("ssh.warn_status") {
cfg.SSH.WarnStatus = []string{}
}
// Legacy environment variables must not invent an additional unnamed source // Legacy environment variables must not invent an additional unnamed source
// when a file explicitly configures named instances (including wizard migration). // when a file explicitly configures named instances (including wizard migration).
if len(cfg.NetBoxes) > 0 && !v.InConfig("netbox.url") { if len(cfg.NetBoxes) > 0 && !v.InConfig("netbox.url") {
@@ -152,7 +224,7 @@ func Load() (*Config, error) {
return nil, err return nil, err
} }
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" { if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" && !IsKeyringToken(cfg.NetBox.Token) {
if strings.HasPrefix(cfg.NetBox.Token, "nbt_") { if strings.HasPrefix(cfg.NetBox.Token, "nbt_") {
cfg.NetBox.TokenVersion = 2 cfg.NetBox.TokenVersion = 2
} else { } else {
@@ -172,6 +244,15 @@ 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.ValidateLinks(); err != nil {
return nil, err
}
if err := cfg.ValidateDNS(); err != nil {
return nil, err
}
if err := cfg.ValidateOperations(); err != nil {
return nil, err
}
if err := cfg.ValidateCommands(); err != nil { if err := cfg.ValidateCommands(); err != nil {
return nil, err return nil, err
} }
@@ -181,7 +262,7 @@ func Load() (*Config, error) {
for i := range cfg.NetBoxes { for i := range cfg.NetBoxes {
source := &cfg.NetBoxes[i] source := &cfg.NetBoxes[i]
source.Name = strings.ToLower(source.Name) source.Name = strings.ToLower(source.Name)
if source.TokenVersion == 0 && source.Token != "" { if source.TokenVersion == 0 && source.Token != "" && !IsKeyringToken(source.Token) {
source.TokenVersion = 1 source.TokenVersion = 1
if strings.HasPrefix(source.Token, "nbt_") { if strings.HasPrefix(source.Token, "nbt_") {
source.TokenVersion = 2 source.TokenVersion = 2
+96
View File
@@ -0,0 +1,96 @@
package config
import (
"fmt"
"path"
"strings"
)
// DNSConfig controls what netssh does with names that are neither in NetBox
// nor in the cache: resolve them through DNS and suggest the owning host.
type DNSConfig struct {
// Suggest is ask (default), always (take the first suggestion without
// asking, also in scripts) or never (no DNS lookup, plain "not found").
Suggest string `mapstructure:"suggest"`
// SaveLink is ask (default), always (save the shortcut without asking)
// or never, for the link offered after a suggestion.
SaveLink string `mapstructure:"save_link"`
// Domains are appended to names without a dot that match the rule.
Domains []DNSDomain `mapstructure:"domains"`
}
// DNSDomain appends Domain to names matching Match (a shell glob such as
// "mx*"; empty matches every name).
type DNSDomain struct {
Match string `mapstructure:"match"`
Domain string `mapstructure:"domain"`
}
// DNS modes for dns.suggest and dns.save_link.
const (
DNSAsk = "ask"
DNSAlways = "always"
DNSNever = "never"
)
// SuggestMode returns dns.suggest, ask by default.
func (d DNSConfig) SuggestMode() string { return dnsMode(d.Suggest) }
// SaveLinkMode returns dns.save_link, ask by default.
func (d DNSConfig) SaveLinkMode() string { return dnsMode(d.SaveLink) }
func dnsMode(mode string) string {
if mode == "" {
return DNSAsk
}
return strings.ToLower(mode)
}
// Names lists the DNS names to try for what the user typed. A name with a
// dot is used as is. A name without a dot gets the domain of every rule it
// matches, in order; only when no rule matches is the bare name looked up.
func (d DNSConfig) Names(query string) []string {
if strings.Contains(query, ".") {
return []string{query}
}
var names []string
seen := map[string]bool{}
lower := strings.ToLower(query)
for _, rule := range d.Domains {
if rule.Match != "" {
if ok, _ := path.Match(strings.ToLower(rule.Match), lower); !ok {
continue
}
}
name := query + "." + strings.Trim(strings.TrimSpace(rule.Domain), ".")
if !seen[strings.ToLower(name)] {
seen[strings.ToLower(name)] = true
names = append(names, name)
}
}
if len(names) == 0 {
return []string{query}
}
return names
}
// ValidateDNS rejects unknown modes, broken patterns and empty domains.
func (c *Config) ValidateDNS() error {
for key, mode := range map[string]string{"dns.suggest": c.DNS.Suggest, "dns.save_link": c.DNS.SaveLink} {
switch dnsMode(mode) {
case DNSAsk, DNSAlways, DNSNever:
default:
return fmt.Errorf("%s must be ask, always, or never", key)
}
}
for i, rule := range c.DNS.Domains {
if _, err := path.Match(rule.Match, ""); err != nil {
return fmt.Errorf("dns.domains[%d]: invalid match pattern %q", i, rule.Match)
}
domain := strings.Trim(strings.TrimSpace(rule.Domain), ".")
if domain == "" || strings.ContainsAny(domain, " \t/@*?") || strings.HasPrefix(domain, "-") {
return fmt.Errorf("dns.domains[%d]: invalid domain %q", i, rule.Domain)
}
}
return nil
}
+31
View File
@@ -60,3 +60,34 @@ func (c *Config) StaticHost(name string) *StaticHost {
} }
return nil return nil
} }
// Link returns the target of the link named name (case-insensitive).
func (c *Config) Link(name string) (string, bool) {
for key, target := range c.Links {
if strings.EqualFold(key, name) {
return target, true
}
}
return "", false
}
// ValidateLinks keeps link names usable as selectors and shell aliases and
// rejects chains, which could loop.
func (c *Config) ValidateLinks() error {
for name, target := range c.Links {
if !staticHostName.MatchString(name) || strings.Contains(name, "/") {
return fmt.Errorf("links: name %q must start with a letter or digit and contain only letters, digits, dots, underscores, or hyphens", name)
}
if c.StaticHost(name) != nil {
return fmt.Errorf("links: %q is also a static host", name)
}
target = strings.TrimSpace(target)
if target == "" || strings.HasPrefix(target, "-") || strings.ContainsAny(target, " \t\n\r@") {
return fmt.Errorf("links.%s: invalid target %q", name, target)
}
if _, chained := c.Link(target); chained {
return fmt.Errorf("links.%s: target %q is another link", name, target)
}
}
return nil
}
+120
View File
@@ -0,0 +1,120 @@
package config
import (
"os"
"strings"
"testing"
)
func TestSSHRuleMatchesNetBoxAttributes(t *testing.T) {
host := SSHHost{Name: "sw1", Kind: "device", Status: "active",
Site: Ref{Name: "Falkenstein 1", Slug: "fsn1"}, Role: Ref{Name: "Core Switch", Slug: "core-switch"},
Platform: Ref{Name: "Juniper Junos", Slug: "junos"}, Tenant: Ref{Name: "ACME"}}
for _, tc := range []struct {
match SSHMatch
want bool
}{
{SSHMatch{Platform: "junos"}, true},
{SSHMatch{Platform: "juniper junos"}, true},
{SSHMatch{Platform: "eos"}, false},
{SSHMatch{Site: "fsn1", Role: "core-switch"}, true},
{SSHMatch{Role: "Core Switch"}, true},
{SSHMatch{Site: "falkenstein-1"}, true},
{SSHMatch{Tenant: "acme"}, true},
{SSHMatch{Status: "ACTIVE"}, true},
{SSHMatch{Status: "offline"}, false},
{SSHMatch{Platform: "junos", Kind: "vm"}, false},
} {
if got := tc.match.matches(host); got != tc.want {
t.Errorf("%+v: got %v, want %v", tc.match, got, tc.want)
}
}
if err := (SSHMatch{Platform: "junos"}).Validate("rule"); err != nil {
t.Fatalf("platform-only match rejected: %v", err)
}
}
func TestSSHOptionsForPlatformRule(t *testing.T) {
cfg := &Config{SSH: SSHConfig{Rules: []SSHRule{{Match: SSHMatch{Platform: "junos"}, SSHOptions: SSHOptions{Options: map[string]string{"KexAlgorithms": "+diffie-hellman-group14-sha1"}}}}}}
opts := cfg.SSHOptionsFor(SSHHost{Name: "sw1", Kind: "device", Platform: Ref{Slug: "junos"}})
if opts.Options["kexalgorithms"] != "+diffie-hellman-group14-sha1" {
t.Fatalf("platform rule not applied: %+v", opts.Options)
}
if opts := cfg.SSHOptionsFor(SSHHost{Name: "web", Kind: "vm"}); len(opts.Options) != 0 {
t.Fatalf("rule applied to other platform: %+v", opts.Options)
}
}
func TestWarnStatusDefaultsAndOverrides(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
if cfg.SSH.WarnStatus != nil || !cfg.SSH.WarnsStatus("offline") || cfg.SSH.WarnsStatus("active") || cfg.SSH.WarnsStatus("") {
t.Fatalf("default warn_status wrong: %#v", cfg.SSH.WarnStatus)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: []\n"))
if cfg.SSH.WarnStatus == nil || cfg.SSH.WarnsStatus("offline") {
t.Fatalf("empty warn_status should disable the question: %#v", cfg.SSH.WarnStatus)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: [planned]\n"))
if !cfg.SSH.WarnsStatus("Planned") || cfg.SSH.WarnsStatus("offline") {
t.Fatalf("custom warn_status wrong: %#v", cfg.SSH.WarnStatus)
}
}
func TestReachabilityAndFallbackDefaults(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
if cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 300 {
t.Fatalf("reachability must be opt-in: %+v", cfg.TUI)
}
if strings.Join(cfg.TUI.EffectiveColumns(), ",") != "alias,ip,source,status" {
t.Fatalf("default columns: %v", cfg.TUI.EffectiveColumns())
}
if cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 1000 {
t.Fatalf("fallback defaults wrong: %+v", cfg.Resolver)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: [Reachability, ip, platform]\n reachability_timeout: 800\nresolver:\n fallback: true\n fallback_timeout: 250\n"))
if !cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 800 || strings.Join(cfg.TUI.Columns, ",") != "reachability,ip,platform" {
t.Fatalf("reachability settings ignored: %+v", cfg.TUI)
}
if !cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 250 {
t.Fatalf("fallback settings ignored: %+v", cfg.Resolver)
}
}
func TestKeyringTokenKeepsVersionUndetected(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n token: keyring\nnetboxes: []\n"))
if !IsKeyringToken(cfg.NetBox.Token) || cfg.NetBox.TokenVersion != 0 {
t.Fatalf("keyring token treated as literal: %+v", cfg.NetBox)
}
if cfg.NetBox.KeyringAccount() != "default" || (NetBoxConfig{Name: "Prod"}).KeyringAccount() != "prod" {
t.Fatal("unexpected keyring account names")
}
}
func TestTUIColumnsValidation(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: []\n"))
if cfg.TUI.Columns == nil || len(cfg.TUI.EffectiveColumns()) != 0 {
t.Fatalf("empty columns should show only the hostname: %#v", cfg.TUI.Columns)
}
for _, bad := range []string{"[ip, colour]", "[ip, ip]"} {
dir := writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: "+bad+"\n")
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
_, err := Load()
os.Setenv("XDG_CONFIG_HOME", orig)
if err == nil || !strings.Contains(err.Error(), "tui.columns") {
t.Errorf("%s accepted: %v", bad, err)
}
}
}
func TestDNSConfigValidation(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ndns:\n suggest: Always\n domains:\n - match: \"mx*\"\n domain: easysahre.de\n"))
if cfg.DNS.SuggestMode() != DNSAlways || cfg.DNS.SaveLinkMode() != DNSAsk || len(cfg.DNS.Domains) != 1 {
t.Fatalf("dns: %+v", cfg.DNS)
}
for _, bad := range []DNSConfig{{Suggest: "sometimes"}, {SaveLink: "yes"}, {Domains: []DNSDomain{{Match: "[", Domain: "a.de"}}}, {Domains: []DNSDomain{{Domain: " "}}}, {Domains: []DNSDomain{{Domain: "a b.de"}}}} {
if err := (&Config{DNS: bad}).ValidateDNS(); err == nil {
t.Errorf("%+v accepted", bad)
}
}
}
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"fmt"
"strings"
"time"
)
type TUIConfig struct {
HistoryLimit int `mapstructure:"history_limit"`
// Columns selects what the TUI shows next to each hostname, in order;
// nil means DefaultTUIColumns. "reachability" enables the TCP check.
Columns []string `mapstructure:"columns"`
// ReachabilityTimeout is the probe timeout in milliseconds; 0 = 300.
ReachabilityTimeout int `mapstructure:"reachability_timeout"`
}
// TUIColumns are the values tui.columns accepts.
var TUIColumns = []string{"alias", "ip", "kind", "source", "status", "site", "location", "role", "platform", "tenant", "cluster", "tags", "reachability"}
// DefaultTUIColumns is the layout without tui.columns. The TCP reachability
// check is opt-in, since it opens connections to every listed host.
var DefaultTUIColumns = []string{"alias", "ip", "source", "status"}
// EffectiveColumns returns tui.columns, or the default layout.
func (t TUIConfig) EffectiveColumns() []string {
if t.Columns == nil {
return DefaultTUIColumns
}
return t.Columns
}
// ReachabilityEnabled reports whether the TUI probes listed hosts.
func (t TUIConfig) ReachabilityEnabled() bool {
for _, column := range t.EffectiveColumns() {
if column == "reachability" {
return true
}
}
return false
}
// ReachabilityTimeoutDuration returns tui.reachability_timeout, 300ms by default.
func (t TUIConfig) ReachabilityTimeoutDuration() time.Duration {
if t.ReachabilityTimeout <= 0 {
return 300 * time.Millisecond
}
return time.Duration(t.ReachabilityTimeout) * time.Millisecond
}
type ActivityConfig struct {
Enabled bool `mapstructure:"enabled"`
RetentionDays int `mapstructure:"retention_days"`
MaxEntries int `mapstructure:"max_entries"`
}
func (c *Config) ValidateOperations() error {
if c.TUI.HistoryLimit < 0 {
return fmt.Errorf("tui.history_limit must be >= 0 (0 = all)")
}
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
}
seen := map[string]bool{}
for i, column := range c.TUI.Columns {
column = strings.ToLower(strings.TrimSpace(column))
c.TUI.Columns[i] = column
known := false
for _, valid := range TUIColumns {
known = known || column == valid
}
if !known {
return fmt.Errorf("tui.columns: unknown column %q; use %s", column, strings.Join(TUIColumns, ", "))
}
if seen[column] {
return fmt.Errorf("tui.columns: %q is listed twice", column)
}
seen[column] = true
}
if c.TUI.ReachabilityTimeout < 0 || c.TUI.ReachabilityTimeout > 10000 {
return fmt.Errorf("tui.reachability_timeout must be between 0 and 10000 milliseconds")
}
if c.Resolver.FallbackTimeout < 0 || c.Resolver.FallbackTimeout > 30000 {
return fmt.Errorf("resolver.fallback_timeout must be between 0 and 30000 milliseconds")
}
for _, status := range c.SSH.WarnStatus {
if strings.TrimSpace(status) == "" || strings.ContainsAny(status, " \t\n") {
return fmt.Errorf("ssh.warn_status: invalid status %q", status)
}
}
return nil
}
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
func (c HostCommand) Allowed(host SSHHost) bool { return c.Match.Matches(host) }
func HookCommand(s string) string {
s = strings.TrimSpace(s)
if strings.EqualFold(s, "none") {
return ""
}
return s
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"os"
"path/filepath"
"testing"
)
func TestOperationsDefaultsEnvironmentAndValidation(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte("hosts:\n - name: router\n address: 192.0.2.1\n"), 0600); err != nil {
t.Fatal(err)
}
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.TUI.HistoryLimit != 10 || cfg.Activity.Enabled || cfg.Activity.RetentionDays != 30 || cfg.Activity.MaxEntries != 1000 {
t.Fatalf("%+v %+v", cfg.TUI, cfg.Activity)
}
t.Setenv("NETSSH_TUI_HISTORY_LIMIT", "25")
t.Setenv("NETSSH_SSH_POST_DISCONNECT", "echo done")
cfg, err = Load()
if err != nil || cfg.TUI.HistoryLimit != 25 || cfg.SSH.PostDisconnect != "echo done" {
t.Fatalf("%+v %v", cfg, err)
}
cfg.TUI.HistoryLimit = -1
if cfg.ValidateOperations() == nil {
t.Fatal("negative history accepted")
}
for _, timeout := range []string{"-1s", "0s", "invalid"} {
cfg.Commands = map[string]HostCommand{"check": {Args: []string{"echo", "{host}"}, Timeout: timeout}}
if cfg.ValidateCommands() == nil {
t.Fatalf("accepted %q", timeout)
}
}
}
func TestPostDisconnectLayering(t *testing.T) {
cfg := Config{
SSH: SSHConfig{SSHOptions: SSHOptions{PostDisconnect: "global"}, Rules: []SSHRule{{Match: SSHMatch{Tag: "lab"}, SSHOptions: SSHOptions{PostDisconnect: "none"}}}},
NetBoxes: []NetBoxConfig{{Name: "prod", SSH: SSHOptions{PostDisconnect: "instance"}}},
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Name: "web"}, "global"},
{SSHHost{Name: "web", Instance: "prod"}, "instance"},
{SSHHost{Name: "web", Instance: "prod", Tags: []string{"lab"}}, ""},
} {
if got := HookCommand(cfg.SSHOptionsFor(tc.host).PostDisconnect); got != tc.want {
t.Fatalf("%q want %q", got, tc.want)
}
}
}
+75 -1
View File
@@ -27,6 +27,7 @@ type SSHOptions struct {
// PreConnect is a shell command run locally before connecting; a non-zero // 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. // exit aborts the connection. "none" disables a hook set by a broader layer.
PreConnect string `mapstructure:"pre_connect"` PreConnect string `mapstructure:"pre_connect"`
PostDisconnect string `mapstructure:"post_disconnect"`
} }
// PreConnectNone disables an inherited pre_connect hook. // PreConnectNone disables an inherited pre_connect hook.
@@ -93,6 +94,57 @@ type SSHMatch struct {
Instance string `mapstructure:"instance"` Instance string `mapstructure:"instance"`
Kind string `mapstructure:"kind"` Kind string `mapstructure:"kind"`
Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com" Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com"
// Site, Role, Platform and Tenant match the NetBox name or slug.
Site string `mapstructure:"site"`
Role string `mapstructure:"role"`
Platform string `mapstructure:"platform"`
Tenant string `mapstructure:"tenant"`
// Status matches the NetBox status value, e.g. active or offline.
Status string `mapstructure:"status"`
}
// Ref is a NetBox object referenced by a host, such as its site or platform.
type Ref struct {
Name string `json:"name,omitempty"`
Slug string `json:"slug,omitempty"`
}
// Matches compares want with the name or slug, ignoring case.
func (r Ref) Matches(want string) bool {
return want != "" && (strings.EqualFold(r.Name, want) || strings.EqualFold(r.Slug, want) || strings.EqualFold(tagSlug(r.Name), want))
}
// Key returns the slug, or the name when NetBox sent no slug.
func (r Ref) Key() string {
if r.Slug != "" {
return r.Slug
}
return r.Name
}
// LocationPath renders a host's place as "site › location › … › rack › U20",
// leaving out levels that are not set.
func LocationPath(site Ref, locations []Ref, rack, position string) string {
var parts []string
if site.Name != "" {
parts = append(parts, site.Name)
} else if site.Slug != "" {
parts = append(parts, site.Slug)
}
for _, location := range locations {
if location.Name != "" {
parts = append(parts, location.Name)
} else if location.Slug != "" {
parts = append(parts, location.Slug)
}
}
if rack != "" {
parts = append(parts, rack)
}
if position != "" {
parts = append(parts, "U"+position)
}
return strings.Join(parts, " › ")
} }
// SSHHost identifies the resolved host that SSH options are computed for. // SSHHost identifies the resolved host that SSH options are computed for.
@@ -101,6 +153,11 @@ type SSHHost struct {
Name string // NetBox name without the instance prefix Name string // NetBox name without the instance prefix
Kind string Kind string
Tags []string Tags []string
Status string
Site Ref
Role Ref
Platform Ref
Tenant Ref
} }
var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`) var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`)
@@ -137,7 +194,7 @@ func (r SSHRule) Validate(scope string) error {
// Validate requires at least one selector and a well-formed name pattern. // Validate requires at least one selector and a well-formed name pattern.
func (m SSHMatch) Validate(scope string) error { func (m SSHMatch) Validate(scope string) error {
if m == (SSHMatch{}) { if m == (SSHMatch{}) {
return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name", scope) return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name, site, role, platform, tenant, status", scope)
} }
if _, err := path.Match(m.Name, ""); err != nil { if _, err := path.Match(m.Name, ""); err != nil {
return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name) return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name)
@@ -170,6 +227,9 @@ 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.PostDisconnect, 0) {
return fmt.Errorf("%s.post_disconnect must not contain NUL bytes", scope)
}
if strings.ContainsRune(o.PreConnect, 0) { if strings.ContainsRune(o.PreConnect, 0) {
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope) return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
} }
@@ -239,6 +299,9 @@ 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.PostDisconnect) != "" {
out.PostDisconnect = override.PostDisconnect
}
if strings.TrimSpace(override.PreConnect) != "" { if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect out.PreConnect = override.PreConnect
} }
@@ -257,6 +320,17 @@ func (m SSHMatch) matches(host SSHHost) bool {
return false return false
} }
} }
for _, ref := range []struct {
want string
have Ref
}{{m.Site, host.Site}, {m.Role, host.Role}, {m.Platform, host.Platform}, {m.Tenant, host.Tenant}} {
if ref.want != "" && !ref.have.Matches(ref.want) {
return false
}
}
if m.Status != "" && !strings.EqualFold(m.Status, host.Status) {
return false
}
if m.Tag != "" { if m.Tag != "" {
found := false found := false
for _, tag := range host.Tags { for _, tag := range host.Tags {
+27
View File
@@ -129,6 +129,20 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
out = append(out, AliasEntry{Name: cfg.Shell.Alias}) out = append(out, AliasEntry{Name: cfg.Shell.Alias})
} }
// Links are names the user chose explicitly: they come before host aliases.
validLink := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
links := make([]string, 0, len(cfg.Links))
for name := range cfg.Links {
links = append(links, strings.ToLower(name))
}
sort.Strings(links)
for _, name := range links {
if !seen[name] && validLink.MatchString(name) {
seen[name] = true
out = append(out, AliasEntry{Name: name, Host: name})
}
}
withoutPrefix := make(map[string]bool, len(cfg.NetBoxes)) withoutPrefix := make(map[string]bool, len(cfg.NetBoxes))
for _, source := range cfg.NetBoxes { for _, source := range cfg.NetBoxes {
withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix
@@ -165,6 +179,16 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
// Build from the final SSH aliases, preserving per-instance prefix and // Build from the final SSH aliases, preserving per-instance prefix and
// collision handling. Never replace an existing SSH or command alias. // collision handling. Never replace an existing SSH or command alias.
hostAliases := append([]AliasEntry(nil), out...) hostAliases := append([]AliasEntry(nil), out...)
hostMetadata := map[string]config.SSHHost{}
for _, e := range entries {
instance, hostname, ok := strings.Cut(e.Name, "/")
if !ok {
hostname = instance
instance = ""
}
hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags, Status: e.Status,
Site: cache.RefOf(e.Site), Role: cache.RefOf(e.Role), Platform: cache.RefOf(e.Platform), Tenant: cache.RefOf(e.Tenant)}
}
var commands []string var commands []string
for name := range cfg.Commands { for name := range cfg.Commands {
commands = append(commands, name) commands = append(commands, name)
@@ -181,6 +205,9 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
if host.Host == "" { if host.Host == "" {
continue continue
} }
if !cfg.Commands[name].Allowed(hostMetadata[host.Host]) {
continue
}
alias := prefix + host.Name alias := prefix + host.Name
commandCounts[alias]++ commandCounts[alias]++
candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name}) candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name})
+19
View File
@@ -416,3 +416,22 @@ func TestCustomAliasShellArgumentQuoting(t *testing.T) {
}) })
} }
} }
func TestCommandAliasesHonourNetBoxAttributes(t *testing.T) {
cfg := config.Config{Commands: map[string]config.HostCommand{
"cli": {AliasPrefix: "c", Args: []string{"cli", "{address}"}, Match: config.SSHMatch{Platform: "junos"}},
}}
entries := []cache.Entry{
{Name: "sw1", Kind: "device", Platform: &config.Ref{Name: "Junos", Slug: "junos"}},
{Name: "web1", Kind: "vm", Platform: &config.Ref{Slug: "ubuntu"}},
}
var got []string
for _, a := range hook.BuildAliasEntries(entries, cfg) {
if a.Command == "cli" {
got = append(got, a.Name)
}
}
if len(got) != 1 || got[0] != "csw1" {
t.Fatalf("command aliases %v", got)
}
}
+35
View File
@@ -12,6 +12,8 @@ import (
"strings" "strings"
"sync" "sync"
"time" "time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
) )
type Client struct { type Client struct {
@@ -20,6 +22,9 @@ type Client struct {
token string token string
tokenVersion int tokenVersion int
httpClient *http.Client httpClient *http.Client
locMu sync.Mutex
locations map[int]locationNode // location ID → name and parent, per client
} }
// NewClient creates a NetBox API client. Pass tokenVersion=0 to auto-detect // NewClient creates a NetBox API client. Pass tokenVersion=0 to auto-detect
@@ -227,6 +232,7 @@ func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEn
for _, d := range resp.Results { for _, d := range resp.Results {
entries = append(entries, deviceToEntry(d)) entries = append(entries, deviceToEntry(d))
} }
c.fillLocations(ctx, entries)
return entries, nil return entries, nil
} }
@@ -278,6 +284,7 @@ func (c *Client) fetchAllDevices(ctx context.Context, query, filters string) ([]
break break
} }
} }
c.fillLocations(ctx, all)
return all, nil return all, nil
} }
@@ -370,6 +377,20 @@ func deviceToEntry(d netboxDevice) HostEntry {
if d.Cluster != nil { if d.Cluster != nil {
e.Cluster = d.Cluster.Name e.Cluster = d.Cluster.Name
} }
e.Status = d.Status.value()
e.Site, e.Platform, e.Tenant = d.Site.ref(), d.Platform.ref(), d.Tenant.ref()
e.Role = d.Role.ref()
if d.Role == nil {
e.Role = d.DeviceRole.ref()
}
if d.Location != nil {
e.locationID = d.Location.ID
e.Location = []config.Ref{{Name: d.Location.Name, Slug: d.Location.Slug}}
}
if d.Rack != nil {
e.Rack = d.Rack.Name
}
e.Position = rackUnit(d.Position)
return e return e
} }
@@ -387,6 +408,20 @@ func vmToEntry(v netboxVM) HostEntry {
if v.Cluster != nil { if v.Cluster != nil {
e.Cluster = v.Cluster.Name e.Cluster = v.Cluster.Name
} }
e.Status = v.Status.value()
e.Site, e.Platform, e.Tenant = v.Site.ref(), v.Platform.ref(), v.Tenant.ref()
e.Role = v.Role.ref()
if v.Role == nil {
e.Role = v.DeviceRole.ref()
}
if v.Location != nil {
e.locationID = v.Location.ID
e.Location = []config.Ref{{Name: v.Location.Name, Slug: v.Location.Slug}}
}
if v.Rack != nil {
e.Rack = v.Rack.Name
}
e.Position = rackUnit(v.Position)
return e return e
} }
+365
View File
@@ -0,0 +1,365 @@
package netbox
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
)
// HostDetails is everything netssh info shows about a device or VM.
type HostDetails struct {
HostEntry
URL string `json:"url"`
StatusLabel string `json:"status_label,omitempty"`
HeightU string `json:"height_u,omitempty"` // rack units the device occupies
Face string `json:"face,omitempty"` // front | rear
DeviceType string `json:"device_type,omitempty"`
Serial string `json:"serial,omitempty"`
AssetTag string `json:"asset_tag,omitempty"`
Description string `json:"description,omitempty"`
VCPUs string `json:"vcpus,omitempty"`
MemoryMB int `json:"memory_mb,omitempty"`
DiskGB int `json:"disk_gb,omitempty"`
IPs []IPAssignment `json:"ips"`
}
// IPAssignment is one IP address of a host with the interface it is on.
type IPAssignment struct {
Address string `json:"address"` // CIDR notation
Interface string `json:"interface,omitempty"`
DNSName string `json:"dns_name,omitempty"`
Status string `json:"status,omitempty"`
Role string `json:"role,omitempty"`
VRF string `json:"vrf,omitempty"`
Primary bool `json:"primary,omitempty"`
}
// IPOwner is a NetBox IP address found by LookupIP, with the host and
// interface it is assigned to.
type IPOwner struct {
Source string `json:"instance,omitempty"`
Address string `json:"address"`
Status string `json:"status,omitempty"`
DNSName string `json:"dns_name,omitempty"`
Description string `json:"description,omitempty"`
VRF string `json:"vrf,omitempty"`
Interface string `json:"interface,omitempty"`
HostKind string `json:"kind,omitempty"` // device | vm; empty when unassigned
HostName string `json:"host,omitempty"`
HostID int `json:"host_id,omitempty"`
}
// Target returns the selector of the owning host, or "" when unassigned.
func (o IPOwner) Target() string {
if o.HostName == "" {
return ""
}
return HostEntry{Source: o.Source, Name: o.HostName}.Target()
}
// PrefixInfo is a NetBox prefix that contains an address.
type PrefixInfo struct {
Source string `json:"instance,omitempty"`
Prefix string `json:"prefix"`
Status string `json:"status,omitempty"`
Role string `json:"role,omitempty"`
Site string `json:"site,omitempty"`
VLAN string `json:"vlan,omitempty"`
VRF string `json:"vrf,omitempty"`
Description string `json:"description,omitempty"`
}
type netboxHostDetail struct {
netboxDevice
Face *netboxStatus `json:"face"`
Serial string `json:"serial"`
AssetTag *string `json:"asset_tag"`
DeviceType *struct {
ID int `json:"id"`
Model string `json:"model"`
Manufacturer *netboxRef `json:"manufacturer"`
} `json:"device_type"`
Description string `json:"description"`
VCPUs json.Number `json:"vcpus"`
Memory *int `json:"memory"`
Disk *int `json:"disk"`
}
type netboxIPAddress struct {
Address string `json:"address"`
Status *netboxStatus `json:"status"`
Role *netboxStatus `json:"role"`
DNSName string `json:"dns_name"`
Description string `json:"description"`
VRF *netboxRef `json:"vrf"`
ObjectType string `json:"assigned_object_type"`
Object *struct {
Name string `json:"name"`
Device *struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"device"`
VirtualMachine *struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"virtual_machine"`
} `json:"assigned_object"`
}
type netboxPrefix struct {
Prefix string `json:"prefix"`
Status *netboxStatus `json:"status"`
Role *netboxRef `json:"role"`
Site *netboxRef `json:"site"`
Scope *netboxRef `json:"scope"`
VRF *netboxRef `json:"vrf"`
Description string `json:"description"`
VLAN *struct {
VID int `json:"vid"`
Name string `json:"name"`
} `json:"vlan"`
}
func hostPath(kind string) (string, error) {
switch kind {
case "device":
return "dcim/devices", nil
case "vm":
return "virtualization/virtual-machines", nil
}
return "", fmt.Errorf("invalid host kind %q", kind)
}
// WebURL returns the page of a host in the NetBox web interface.
func (c *Client) WebURL(host HostEntry) (string, error) {
source, host, err := c.sourceForHost(host)
if err != nil {
return "", err
}
path, err := hostPath(host.Kind)
if err != nil {
return "", err
}
if host.ID <= 0 {
return "", fmt.Errorf("NetBox ID of %s is unknown", host.Target())
}
return fmt.Sprintf("%s/%s/%d/", source.baseURL, path, host.ID), nil
}
// GetDetails fetches the full record and all IP addresses of a host.
func (c *Client) GetDetails(ctx context.Context, host HostEntry) (HostDetails, error) {
source, host, err := c.sourceForHost(host)
if err != nil {
return HostDetails{}, err
}
apiURL, err := source.hostURL(host)
if err != nil {
return HostDetails{}, err
}
var raw netboxHostDetail
if err := source.get(ctx, apiURL, &raw); err != nil {
return HostDetails{}, err
}
entry := deviceToEntry(raw.netboxDevice)
entry.Kind, entry.Source = host.Kind, host.Source
entries := []HostEntry{entry}
source.fillLocations(ctx, entries)
entry = entries[0]
d := HostDetails{HostEntry: entry, Serial: raw.Serial, Description: raw.Description}
d.URL, _ = c.WebURL(entry)
if raw.Status != nil {
d.StatusLabel = raw.Status.Label
}
if raw.Face != nil {
d.Face = raw.Face.Value
}
if raw.AssetTag != nil {
d.AssetTag = *raw.AssetTag
}
if raw.DeviceType != nil && entry.Position != "" && raw.DeviceType.ID > 0 {
var deviceType struct {
UHeight json.Number `json:"u_height"`
}
if err := source.get(ctx, fmt.Sprintf("%s/api/dcim/device-types/%d/", source.baseURL, raw.DeviceType.ID), &deviceType); err == nil {
d.HeightU = rackUnit(deviceType.UHeight)
}
}
if raw.DeviceType != nil {
d.DeviceType = raw.DeviceType.Model
if raw.DeviceType.Manufacturer != nil && raw.DeviceType.Manufacturer.Name != "" {
d.DeviceType = raw.DeviceType.Manufacturer.Name + " " + d.DeviceType
}
}
if raw.VCPUs != "" {
d.VCPUs = strings.TrimSuffix(strings.TrimSuffix(raw.VCPUs.String(), ".00"), ".0")
}
if raw.Memory != nil {
d.MemoryMB = *raw.Memory
}
if raw.Disk != nil {
d.DiskGB = *raw.Disk
}
filter := fmt.Sprintf("device_id=%d", host.ID)
if host.Kind == "vm" {
filter = fmt.Sprintf("virtual_machine_id=%d", host.ID)
}
addresses, err := source.fetchIPAddresses(ctx, filter)
if err != nil {
return d, fmt.Errorf("IP addresses: %w", err)
}
for _, a := range addresses {
ip := IPAssignment{Address: a.Address, DNSName: a.DNSName, Status: a.Status.value(), Role: a.Role.value()}
if a.VRF != nil {
ip.VRF = a.VRF.Name
}
if a.Object != nil {
ip.Interface = a.Object.Name
}
addr := stripPrefix(a.Address)
ip.Primary = addr == entry.PrimaryIP4 || addr == entry.PrimaryIP6
d.IPs = append(d.IPs, ip)
}
sort.SliceStable(d.IPs, func(i, j int) bool {
if d.IPs[i].Primary != d.IPs[j].Primary {
return d.IPs[i].Primary
}
return d.IPs[i].Interface < d.IPs[j].Interface
})
return d, nil
}
func (c *Client) fetchIPAddresses(ctx context.Context, filter string) ([]netboxIPAddress, error) {
const pageSize = 100
var out []netboxIPAddress
for offset := 0; ; offset += pageSize {
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filter, pageSize, offset)
var resp netboxListResponse[netboxIPAddress]
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
out = append(out, resp.Results...)
if len(resp.Results) < pageSize || len(out) >= resp.Count {
return out, nil
}
}
}
// eachSource runs fn for every configured instance in name order, or once
// for a single-instance client. It keeps going after an error, so one
// unreachable instance does not hide answers from the others.
func (c *Client) eachSource(fn func(name string, source *Client) error) error {
if c.sources == nil {
return fn("", c)
}
names := make([]string, 0, len(c.sources))
for name := range c.sources {
names = append(names, name)
}
sort.Strings(names)
var errs []error
for _, name := range names {
if err := fn(name, c.sources[name]); err != nil {
errs = append(errs, fmt.Errorf("NetBox %s: %w", name, err))
}
}
return errors.Join(errs...)
}
// LookupIP finds the NetBox IP address records of ip in every instance.
func (c *Client) LookupIP(ctx context.Context, ip string) ([]IPOwner, error) {
var out []IPOwner
err := c.eachSource(func(name string, source *Client) error {
found, err := source.fetchIPAddresses(ctx, "address="+url.QueryEscape(ip))
if err != nil {
return err
}
for _, a := range found {
owner := IPOwner{Source: name, Address: a.Address, Status: a.Status.value(), DNSName: a.DNSName, Description: a.Description}
if a.VRF != nil {
owner.VRF = a.VRF.Name
}
if a.Object != nil {
owner.Interface = a.Object.Name
switch {
case a.Object.Device != nil:
owner.HostKind, owner.HostName, owner.HostID = "device", a.Object.Device.Name, a.Object.Device.ID
case a.Object.VirtualMachine != nil:
owner.HostKind, owner.HostName, owner.HostID = "vm", a.Object.VirtualMachine.Name, a.Object.VirtualMachine.ID
}
}
out = append(out, owner)
}
return nil
})
return out, err
}
// PrefixesContaining returns the prefixes containing ip, most specific last.
func (c *Client) PrefixesContaining(ctx context.Context, ip string) ([]PrefixInfo, error) {
var out []PrefixInfo
err := c.eachSource(func(name string, source *Client) error {
apiURL := fmt.Sprintf("%s/api/ipam/prefixes/?contains=%s&limit=100", source.baseURL, url.QueryEscape(ip))
var resp netboxListResponse[netboxPrefix]
if err := source.get(ctx, apiURL, &resp); err != nil {
return err
}
for _, p := range resp.Results {
info := PrefixInfo{Source: name, Prefix: p.Prefix, Status: p.Status.value(), Description: p.Description}
if p.Role != nil {
info.Role = p.Role.Name
}
if p.Site != nil {
info.Site = p.Site.Name
} else if p.Scope != nil {
info.Site = p.Scope.Name
}
if p.VRF != nil {
info.VRF = p.VRF.Name
}
if p.VLAN != nil {
info.VLAN = strconv.Itoa(p.VLAN.VID)
if p.VLAN.Name != "" {
info.VLAN += " (" + p.VLAN.Name + ")"
}
}
out = append(out, info)
}
return nil
})
sort.SliceStable(out, func(i, j int) bool { return prefixLen(out[i].Prefix) < prefixLen(out[j].Prefix) })
return out, err
}
func prefixLen(prefix string) int {
_, bits, _ := strings.Cut(prefix, "/")
n, _ := strconv.Atoi(bits)
return n
}
// RackUnits renders the occupied units, e.g. "U20-21 (2U, front)".
func (d HostDetails) RackUnits() string {
if d.Position == "" {
return ""
}
units := "U" + d.Position
var extra []string
if height, err := strconv.ParseFloat(d.HeightU, 64); err == nil && height > 0 {
if start, err := strconv.ParseFloat(d.Position, 64); err == nil && height > 1 {
units += "-" + strconv.FormatFloat(start+height-1, 'f', -1, 64)
}
extra = append(extra, d.HeightU+"U")
}
if d.Face != "" {
extra = append(extra, d.Face)
}
if len(extra) > 0 {
units += " (" + strings.Join(extra, ", ") + ")"
}
return units
}
+101
View File
@@ -0,0 +1,101 @@
package netbox
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func detailServer(t *testing.T) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/api/dcim/devices/7/":
fmt.Fprint(w, `{"id":7,"name":"sw1","status":{"value":"offline","label":"Offline"},
"site":{"name":"Falkenstein 1","slug":"fsn1"},"rack":{"name":"R12"},"position":20.0,
"device_role":{"name":"Core Switch","slug":"core-switch"},"platform":{"name":"Junos","slug":"junos"},
"tenant":null,"serial":"ABC","asset_tag":null,"device_type":{"model":"QFX5120","manufacturer":{"name":"Juniper"}},
"primary_ip4":{"address":"10.0.0.7/24"},"tags":[{"name":"core"}]}`)
case r.URL.Path == "/api/ipam/ip-addresses/" && r.URL.Query().Get("device_id") == "7":
fmt.Fprint(w, `{"count":2,"results":[
{"address":"192.0.2.7/24","assigned_object":{"name":"xe-0/0/1"},"status":{"value":"active"}},
{"address":"10.0.0.7/24","assigned_object":{"name":"em0"},"dns_name":"sw1.example.com","status":{"value":"active"}}]}`)
case r.URL.Path == "/api/ipam/ip-addresses/" && r.URL.Query().Get("address") != "":
fmt.Fprint(w, `{"count":1,"results":[{"address":"10.0.0.7/24","status":{"value":"active"},
"assigned_object_type":"dcim.interface","assigned_object":{"name":"em0","device":{"id":7,"name":"sw1"}}}]}`)
case r.URL.Path == "/api/ipam/prefixes/":
if r.URL.Query().Get("contains") != "10.0.0.7" {
t.Errorf("unexpected contains %q", r.URL.Query().Get("contains"))
}
fmt.Fprint(w, `{"count":2,"results":[
{"prefix":"10.0.0.0/24","status":{"value":"active"},"vlan":{"vid":100,"name":"mgmt"},"site":{"name":"FSN1"}},
{"prefix":"10.0.0.0/8","description":"internal"}]}`)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv
}
func TestDeviceAttributesAndDetails(t *testing.T) {
srv := detailServer(t)
c := NewClient(srv.URL, "token", 0)
d, err := c.GetDetails(context.Background(), HostEntry{ID: 7, Name: "sw1", Kind: "device"})
if err != nil {
t.Fatal(err)
}
if d.Status != "offline" || d.StatusLabel != "Offline" || d.Site.Slug != "fsn1" || d.Role.Slug != "core-switch" || d.Platform.Slug != "junos" {
t.Fatalf("attributes not parsed: %+v", d.HostEntry)
}
if d.Rack != "R12" || d.Position != "20" || d.DeviceType != "Juniper QFX5120" || d.Serial != "ABC" {
t.Fatalf("details not parsed: %+v", d)
}
if d.URL != srv.URL+"/dcim/devices/7/" {
t.Fatalf("web URL %q", d.URL)
}
if len(d.IPs) != 2 || !d.IPs[0].Primary || d.IPs[0].Interface != "em0" || d.IPs[0].DNSName != "sw1.example.com" {
t.Fatalf("IPs not sorted primary first: %+v", d.IPs)
}
}
func TestWebURLForInstances(t *testing.T) {
c := NewMultiClient([]Source{{Name: "prod", URL: "https://nb.example/", Token: "t"}})
got, err := c.WebURL(HostEntry{Source: "prod", Name: "web", Kind: "vm", ID: 3})
if err != nil || got != "https://nb.example/virtualization/virtual-machines/3/" {
t.Fatalf("got %q, %v", got, err)
}
if _, err := c.WebURL(HostEntry{Source: "prod", Name: "web", Kind: "vm"}); err == nil {
t.Fatal("missing ID accepted")
}
}
func TestLookupIPAndPrefixes(t *testing.T) {
srv := detailServer(t)
c := NewMultiClient([]Source{{Name: "prod", URL: srv.URL, Token: "t"}})
owners, err := c.LookupIP(context.Background(), "10.0.0.7")
if err != nil || len(owners) != 1 || owners[0].Target() != "prod/sw1" || owners[0].Interface != "em0" || owners[0].HostKind != "device" {
t.Fatalf("owners %+v, %v", owners, err)
}
prefixes, err := c.PrefixesContaining(context.Background(), "10.0.0.7")
if err != nil || len(prefixes) != 2 || prefixes[0].Prefix != "10.0.0.0/8" || prefixes[1].VLAN != "100 (mgmt)" || prefixes[1].Source != "prod" {
t.Fatalf("prefixes %+v, %v", prefixes, err)
}
}
func TestLookupIPReportsFailingInstanceButKeepsOthers(t *testing.T) {
good := detailServer(t)
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusBadGateway)
}))
defer bad.Close()
c := NewMultiClient([]Source{{Name: "a", URL: bad.URL, Token: "t"}, {Name: "b", URL: good.URL, Token: "t"}})
owners, err := c.LookupIP(context.Background(), "10.0.0.7")
if err == nil || !strings.Contains(err.Error(), "NetBox a") || len(owners) != 1 {
t.Fatalf("owners %+v, err %v", owners, err)
}
}
+92
View File
@@ -0,0 +1,92 @@
package netbox
import (
"context"
"encoding/json"
"fmt"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// maxLocationDepth stops walking up a broken (cyclic) location tree.
const maxLocationDepth = 16
type locationNode struct {
ref config.Ref
parent int
}
type netboxLocation struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Parent *struct {
ID int `json:"id"`
} `json:"parent"`
}
// rackUnit formats a NetBox rack position (a decimal such as 20.0 or 20.5).
func rackUnit(n json.Number) string {
if n == "" {
return ""
}
s := n.String()
if strings.Contains(s, ".") {
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
}
return s
}
// locationChain returns the locations from the outermost to id. NetBox nests
// locations through "parent"; each location is fetched once per client.
func (c *Client) locationChain(ctx context.Context, id int) ([]config.Ref, error) {
var chain []config.Ref
for depth := 0; id > 0 && depth < maxLocationDepth; depth++ {
node, err := c.location(ctx, id)
if err != nil {
return nil, err
}
chain = append([]config.Ref{node.ref}, chain...)
id = node.parent
}
return chain, nil
}
func (c *Client) location(ctx context.Context, id int) (locationNode, error) {
c.locMu.Lock()
node, ok := c.locations[id]
c.locMu.Unlock()
if ok {
return node, nil
}
var raw netboxLocation
if err := c.get(ctx, fmt.Sprintf("%s/api/dcim/locations/%d/", c.baseURL, id), &raw); err != nil {
return locationNode{}, err
}
node = locationNode{ref: config.Ref{Name: raw.Name, Slug: raw.Slug}}
if raw.Parent != nil {
node.parent = raw.Parent.ID
}
c.locMu.Lock()
if c.locations == nil {
c.locations = map[int]locationNode{}
}
c.locations[id] = node
c.locMu.Unlock()
return node, nil
}
// fillLocations replaces each device's own location with the full chain of
// parent locations. A failed lookup keeps the device's own location: the
// location is informational and must not break a search or a connection.
func (c *Client) fillLocations(ctx context.Context, entries []HostEntry) {
for i := range entries {
if entries[i].locationID <= 0 {
continue
}
if chain, err := c.locationChain(ctx, entries[i].locationID); err == nil && len(chain) > 0 {
entries[i].Location = chain
}
}
}
+101
View File
@@ -0,0 +1,101 @@
package netbox
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
// locationServer serves a site with Building A › Floor 2 › Room 2.04 and two
// racked devices in Room 2.04, plus a location loop 90 ↔ 91.
func locationServer(t *testing.T, calls *int32) *httptest.Server {
t.Helper()
locations := map[string]string{
"1": `{"id":1,"name":"Building A","slug":"building-a","parent":null}`,
"2": `{"id":2,"name":"Floor 2","slug":"floor-2","parent":{"id":1}}`,
"3": `{"id":3,"name":"Room 2.04","slug":"room-2-04","parent":{"id":2}}`,
"90": `{"id":90,"name":"Loop A","slug":"loop-a","parent":{"id":91}}`,
"91": `{"id":91,"name":"Loop B","slug":"loop-b","parent":{"id":90}}`,
}
device := func(id int, name string, location int, position string) string {
return fmt.Sprintf(`{"id":%d,"name":%q,"site":{"name":"FSN1","slug":"fsn1"},"location":{"id":%d,"name":"x","slug":"x"},
"rack":{"name":"R12"},"position":%s,"face":{"value":"front"},"device_type":{"id":9,"model":"R640"}}`, id, name, location, position)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasPrefix(r.URL.Path, "/api/dcim/locations/"):
atomic.AddInt32(calls, 1)
id := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/dcim/locations/"), "/")
if body, ok := locations[id]; ok {
fmt.Fprint(w, body)
return
}
http.NotFound(w, r)
case r.URL.Path == "/api/dcim/devices/":
fmt.Fprintf(w, `{"count":3,"results":[%s,%s,%s]}`, device(1, "srv1", 3, "20.0"), device(2, "srv2", 3, "22"), device(3, "loopy", 90, "null"))
case r.URL.Path == "/api/dcim/devices/1/":
fmt.Fprint(w, device(1, "srv1", 3, "20.0"))
case r.URL.Path == "/api/dcim/device-types/9/":
fmt.Fprint(w, `{"id":9,"u_height":2.0}`)
case r.URL.Path == "/api/virtualization/virtual-machines/", r.URL.Path == "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv
}
func TestSearchAllResolvesNestedLocations(t *testing.T) {
var calls int32
srv := locationServer(t, &calls)
entries, err := NewClient(srv.URL, "t", 0).SearchAll(context.Background(), "", SearchOptions{Kind: "device"})
if err != nil {
t.Fatal(err)
}
byName := map[string]HostEntry{}
for _, e := range entries {
byName[e.Name] = e
}
srv1 := byName["srv1"]
if got := srv1.LocationPath(); got != "FSN1 › Building A › Floor 2 › Room 2.04 › R12 › U20" {
t.Fatalf("path %q", got)
}
if srv1.Location[0].Slug != "building-a" || srv1.Location[2].Slug != "room-2-04" {
t.Fatalf("chain order: %+v", srv1.Location)
}
// Room, floor and building are fetched once for both devices, the loop
// stops at the depth limit instead of hanging.
if n := atomic.LoadInt32(&calls); n != 5 {
t.Fatalf("location requests: %d", n)
}
if len(byName["loopy"].Location) != maxLocationDepth || byName["loopy"].Position != "" {
t.Fatalf("loop not bounded: %d", len(byName["loopy"].Location))
}
}
func TestDetailsShowRackUnits(t *testing.T) {
var calls int32
srv := locationServer(t, &calls)
d, err := NewClient(srv.URL, "t", 0).GetDetails(context.Background(), HostEntry{ID: 1, Name: "srv1", Kind: "device"})
if err != nil {
t.Fatal(err)
}
if d.Rack != "R12" || d.Position != "20" || d.HeightU != "2" || d.RackUnits() != "U20-21 (2U, front)" {
t.Fatalf("rack: %q %q %q %q", d.Rack, d.Position, d.HeightU, d.RackUnits())
}
if len(d.Location) != 3 {
t.Fatalf("details lack location chain: %+v", d.Location)
}
if (HostDetails{HostEntry: HostEntry{Position: "7"}, HeightU: "1"}).RackUnits() != "U7 (1U)" {
t.Fatal("single unit")
}
if (HostDetails{}).RackUnits() != "" {
t.Fatal("unracked device should have no units")
}
}
+83 -1
View File
@@ -1,6 +1,12 @@
package netbox package netbox
import "strings" import (
"encoding/json"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// SearchOptions filters a Search or SearchAll query. // SearchOptions filters a Search or SearchAll query.
// Zero value means no filtering (return all kinds, no tag filter). // Zero value means no filtering (return all kinds, no tag filter).
@@ -13,6 +19,9 @@ type SearchOptions struct {
// HostEntry is a unified model for both devices and virtual machines from NetBox. // HostEntry is a unified model for both devices and virtual machines from NetBox.
type HostEntry struct { type HostEntry struct {
Cached bool
CachedAt time.Time
Static bool
Source string // named NetBox instance; empty for the legacy single-instance config Source string // named NetBox instance; empty for the legacy single-instance config
ID int ID int
Name string Name string
@@ -21,6 +30,49 @@ type HostEntry struct {
PrimaryIP6 string PrimaryIP6 string
Tags []string Tags []string
Cluster string // virtualization cluster name, if assigned Cluster string // virtualization cluster name, if assigned
Status string // NetBox status value, e.g. "active"
Site config.Ref
Role config.Ref
Platform config.Ref
Tenant config.Ref
// Location is the chain of nested NetBox locations from the outermost
// (directly below the site) to the device's own location.
Location []config.Ref
Rack string
Position string // lowest rack unit, e.g. "20"; empty when not racked
locationID int // the device's own location, before the chain is resolved
}
// LocationPath renders site › locations › rack › U position.
func (h HostEntry) LocationPath() string {
return config.LocationPath(h.Site, h.Location, h.Rack, h.Position)
}
// netboxRef is a nested NetBox object with a name and slug.
type netboxRef struct {
Name string `json:"name"`
Slug string `json:"slug"`
}
func (r *netboxRef) ref() config.Ref {
if r == nil {
return config.Ref{}
}
return config.Ref{Name: r.Name, Slug: r.Slug}
}
// netboxStatus is a NetBox choice field such as status.
type netboxStatus struct {
Value string `json:"value"`
Label string `json:"label"`
}
func (s *netboxStatus) value() string {
if s == nil {
return ""
}
return s.Value
} }
// netboxCluster is the nested cluster of a device or virtual machine. // netboxCluster is the nested cluster of a device or virtual machine.
@@ -44,6 +96,21 @@ type netboxDevice struct {
PrimaryIP4 *netboxIP `json:"primary_ip4"` PrimaryIP4 *netboxIP `json:"primary_ip4"`
PrimaryIP6 *netboxIP `json:"primary_ip6"` PrimaryIP6 *netboxIP `json:"primary_ip6"`
Cluster *netboxCluster `json:"cluster"` Cluster *netboxCluster `json:"cluster"`
Status *netboxStatus `json:"status"`
Site *netboxRef `json:"site"`
Role *netboxRef `json:"role"`
DeviceRole *netboxRef `json:"device_role"` // NetBox < 3.6
Platform *netboxRef `json:"platform"`
Tenant *netboxRef `json:"tenant"`
Location *struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
} `json:"location"`
Rack *struct {
Name string `json:"name"`
} `json:"rack"`
Position json.Number `json:"position"`
} }
// netboxVM matches the relevant fields of the NetBox /virtualization/virtual-machines/ response. // netboxVM matches the relevant fields of the NetBox /virtualization/virtual-machines/ response.
@@ -56,6 +123,21 @@ type netboxVM struct {
PrimaryIP4 *netboxIP `json:"primary_ip4"` PrimaryIP4 *netboxIP `json:"primary_ip4"`
PrimaryIP6 *netboxIP `json:"primary_ip6"` PrimaryIP6 *netboxIP `json:"primary_ip6"`
Cluster *netboxCluster `json:"cluster"` Cluster *netboxCluster `json:"cluster"`
Status *netboxStatus `json:"status"`
Site *netboxRef `json:"site"`
Role *netboxRef `json:"role"`
DeviceRole *netboxRef `json:"device_role"` // NetBox < 3.6
Platform *netboxRef `json:"platform"`
Tenant *netboxRef `json:"tenant"`
Location *struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
} `json:"location"`
Rack *struct {
Name string `json:"name"`
} `json:"rack"`
Position json.Number `json:"position"`
} }
type netboxListResponse[T any] struct { type netboxListResponse[T any] struct {
+30
View File
@@ -0,0 +1,30 @@
package resolver
import (
"context"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestCandidatesListsEveryStrategyOnce(t *testing.T) {
chain, err := New(config.ResolverConfig{Strategies: []string{"primary_ip", "hostname"}, HostnameDomain: "example.com"})
if err != nil {
t.Fatal(err)
}
entry := &netbox.HostEntry{Name: "web", Kind: "vm", PrimaryIP4: "10.0.0.1", PrimaryIP6: "2001:db8::1"}
got, err := chain.Candidates(context.Background(), entry, nil)
if err != nil {
t.Fatal(err)
}
want := []Candidate{{"10.0.0.1", "primary_ip"}, {"web.example.com", "hostname"}, {"2001:db8::1", "primary_ip"}}
if len(got) != len(want) {
t.Fatalf("got %+v", got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("got %+v, want %+v", got, want)
}
}
}
+48 -3
View File
@@ -28,19 +28,24 @@ func New(cfg config.ResolverConfig) (*Chain, error) {
} }
func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) { func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) {
address, _, err := c.ResolveWithStrategy(ctx, entry, client)
return address, err
}
func (c *Chain) ResolveWithStrategy(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, string, error) {
for _, s := range c.strategies { for _, s := range c.strategies {
ip, err := s.Resolve(ctx, entry, client) ip, err := s.Resolve(ctx, entry, client)
if err == nil { if err == nil {
return ip, nil return ip, s.Name(), nil
} }
// Only "this strategy has no address" moves on. After an API failure // Only "this strategy has no address" moves on. After an API failure
// the next strategy would connect to (and cache) a different address // the next strategy would connect to (and cache) a different address
// than the configured order asks for. // than the configured order asks for.
if !errors.Is(err, ErrNoIP) { if !errors.Is(err, ErrNoIP) {
return "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err) return "", "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err)
} }
} }
return "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name) return "", "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
} }
func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) { func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
@@ -64,3 +69,43 @@ func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
return nil, fmt.Errorf("unknown strategy %q", name) return nil, fmt.Errorf("unknown strategy %q", name)
} }
} }
// Candidate is an address one strategy resolved for a host.
type Candidate struct {
Address string
Strategy string
}
// Candidates runs every strategy and returns their distinct addresses in the
// configured order. Unlike Resolve, an API failure of one strategy does not
// stop the others: candidates are only used as fallbacks for an address that
// was already chosen by Resolve and turned out to be unreachable.
func (c *Chain) Candidates(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) ([]Candidate, error) {
var out []Candidate
var errs []error
seen := map[string]bool{}
for _, s := range c.strategies {
ip, err := s.Resolve(ctx, entry, client)
if err != nil {
if !errors.Is(err, ErrNoIP) {
errs = append(errs, fmt.Errorf("%s: %w", s.Name(), err))
}
continue
}
if !seen[ip] {
seen[ip] = true
out = append(out, Candidate{Address: ip, Strategy: s.Name()})
}
}
// Both addresses of a dual-stack host are worth trying.
for _, ip := range []string{entry.PrimaryIP4, entry.PrimaryIP6} {
if ip != "" && !seen[ip] {
seen[ip] = true
out = append(out, Candidate{Address: ip, Strategy: "primary_ip"})
}
}
if len(out) == 0 {
return nil, errors.Join(errs...)
}
return out, nil
}
+146
View File
@@ -0,0 +1,146 @@
// Package runner supervises local commands while retaining terminal I/O.
package runner
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/charmbracelet/x/term"
)
type Options struct {
Stdin io.Reader
Stdout, Stderr io.Writer
Env []string
Timeout time.Duration
Status bool
Label string
}
type Result struct {
Code int
Started bool
Duration time.Duration
}
func Run(ctx context.Context, argv []string, o Options) Result {
if o.Stderr == nil {
o.Stderr = io.Discard
}
if o.Stdout == nil {
o.Stdout = io.Discard
}
start := time.Now()
result := Result{Code: 1}
if ctx.Err() != nil {
result.Code = 130
return result
}
if len(argv) == 0 {
return result
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr
cmd.Env = append(os.Environ(), o.Env...)
interactive := false
if f, ok := o.Stdin.(*os.File); ok {
interactive = term.IsTerminal(f.Fd())
}
// Interactive SSH must share the foreground terminal process group.
// Background jobs get an isolated group so cancellation reaches descendants.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: !interactive}
if err := cmd.Start(); err != nil {
fmt.Fprintf(o.Stderr, "%s: %v\n", argv[0], err)
return result
}
result.Started = true
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
sigs := make(chan os.Signal, 4)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
defer signal.Stop(sigs)
var timeout <-chan time.Time
if o.Timeout > 0 {
timer := time.NewTimer(o.Timeout)
defer timer.Stop()
timeout = timer.C
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var killTimer *time.Timer
var kill <-chan time.Time
defer func() {
if killTimer != nil {
killTimer.Stop()
}
}()
send := func(sig syscall.Signal) {
if interactive {
_ = cmd.Process.Signal(sig)
} else {
_ = syscall.Kill(-cmd.Process.Pid, sig)
}
}
forced := 0
cancelCh := ctx.Done()
stop := func(code int, sig syscall.Signal) {
if forced != 0 {
return
}
forced = code
send(sig)
killTimer = time.NewTimer(2 * time.Second)
kill = killTimer.C
}
for {
select {
case err := <-done:
result.Duration = time.Since(start)
result.Code = 0
if err != nil {
result.Code = 1
if e, ok := err.(*exec.ExitError); ok {
result.Code = e.ExitCode()
if s, ok := e.Sys().(syscall.WaitStatus); ok && s.Signaled() {
result.Code = 128 + int(s.Signal())
}
}
}
if forced != 0 {
result.Code = forced
}
// Kill descendants left behind after cancellation even if the parent exited.
if forced != 0 && !interactive {
send(syscall.SIGKILL)
}
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] finished in %s (exit %d)\n", o.Label, result.Duration.Round(time.Millisecond), result.Code)
}
return result
case sig := <-sigs:
s := sig.(syscall.Signal)
if interactive && (s == syscall.SIGINT || s == syscall.SIGQUIT) {
continue
} // terminal delivered it to child too
stop(128+int(s), s)
case <-cancelCh:
cancelCh = nil
stop(130, syscall.SIGTERM)
case <-timeout:
timeout = nil
stop(124, syscall.SIGTERM)
case <-kill:
kill = nil
send(syscall.SIGKILL)
case <-ticker.C:
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] running %s (Ctrl+C cancels)\n", o.Label, time.Since(start).Round(time.Second))
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package runner
import (
"bytes"
"context"
"io"
"strings"
"testing"
"time"
)
func TestExitAndTimeout(t *testing.T) {
var out bytes.Buffer
r := Run(context.Background(), []string{"sh", "-c", "printf result; exit 7"}, Options{Stdout: &out, Stderr: io.Discard})
if !r.Started || r.Code != 7 || out.String() != "result" {
t.Fatalf("%+v %q", r, out.String())
}
start := time.Now()
r = Run(context.Background(), []string{"sh", "-c", "trap '' TERM; sleep 30 & wait"}, Options{Stdout: io.Discard, Stderr: io.Discard, Timeout: 50 * time.Millisecond})
if r.Code != 124 || time.Since(start) > 4*time.Second {
t.Fatalf("timeout: %+v", r)
}
}
func TestCancellationAndNoStart(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
r := Run(ctx, []string{"sh", "-c", "exit 0"}, Options{Stderr: io.Discard})
if r.Started || r.Code != 130 {
t.Fatalf("%+v", r)
}
var errOut bytes.Buffer
r = Run(context.Background(), []string{"/no/such/netssh-test-executable"}, Options{Stderr: &errOut})
if r.Started || r.Code == 0 || !strings.Contains(errOut.String(), "no such") {
t.Fatalf("%+v %s", r, errOut.String())
}
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
time.AfterFunc(50*time.Millisecond, cancel)
r = Run(ctx, []string{"sh", "-c", "sleep 30"}, Options{Stdout: io.Discard, Stderr: io.Discard})
if r.Code != 130 {
t.Fatalf("%+v", r)
}
}
+48
View File
@@ -0,0 +1,48 @@
// Package secret keeps NetBox API tokens in the operating system's keyring
// (Secret Service on Linux, Keychain on macOS) instead of the config file.
package secret
import (
"errors"
"fmt"
"github.com/zalando/go-keyring"
)
// Service is the keyring service name of all netssh entries.
const Service = "netssh"
// ErrNotFound means the keyring has no token for the account.
var ErrNotFound = errors.New("no token in the system keyring")
// Get returns the token stored for account.
func Get(account string) (string, error) {
token, err := keyring.Get(Service, account)
if errors.Is(err, keyring.ErrNotFound) {
return "", fmt.Errorf("%w for %q (store one with: netssh token set %s)", ErrNotFound, account, account)
}
if err != nil {
return "", fmt.Errorf("system keyring: %w", err)
}
return token, nil
}
// Set stores token for account, replacing an existing one.
func Set(account, token string) error {
if err := keyring.Set(Service, account, token); err != nil {
return fmt.Errorf("system keyring: %w", err)
}
return nil
}
// Delete removes the token of account; a missing entry is not an error.
func Delete(account string) error {
err := keyring.Delete(Service, account)
if err != nil && !errors.Is(err, keyring.ErrNotFound) {
return fmt.Errorf("system keyring: %w", err)
}
return nil
}
// MockInit replaces the system keyring with an in-memory one, for tests.
func MockInit() { keyring.MockInit() }
+12
View File
@@ -64,10 +64,22 @@ func editCommands(cfg *config.Config) error {
huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix), 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.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary),
huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments), huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments),
huh.NewConfirm().Title("Confirm before running?").Value(&command.Confirm),
huh.NewInput().Title("Timeout").Description("Optional positive duration, e.g. 30s or 5m.").Value(&command.Timeout),
huh.NewInput().Title("Post-run script").Description("Local command after completion; receives NETSSH_EXIT_CODE.").Value(&command.PostRun),
huh.NewInput().Title("Only for tag").Value(&command.Match.Tag),
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
huh.NewInput().Title("Only for site").Description("NetBox site name or slug.").Value(&command.Match.Site),
huh.NewInput().Title("Only for role").Description("NetBox device/VM role name or slug.").Value(&command.Match.Role),
huh.NewInput().Title("Only for platform").Description("NetBox platform name or slug, e.g. junos.").Value(&command.Match.Platform),
huh.NewInput().Title("Only for status").Description("NetBox status value, e.g. active.").Value(&command.Match.Status),
).Title("Local command")).Run() ).Title("Local command")).Run()
if err != nil { if err != nil {
return err return err
} }
command.Match = trimMatch(command.Match)
command.Args = []string{binary} command.Args = []string{binary}
if arguments != "" { if arguments != "" {
command.Args = append(command.Args, strings.Split(arguments, "\n")...) command.Args = append(command.Args, strings.Split(arguments, "\n")...)
+84
View File
@@ -0,0 +1,84 @@
package setup
import (
"fmt"
"strconv"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editOperations(cfg *config.Config) error {
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
enabled := cfg.Activity.Enabled
columns := append([]string(nil), cfg.TUI.EffectiveColumns()...)
timeout := strconv.Itoa(int(cfg.TUI.ReachabilityTimeoutDuration().Milliseconds()))
columnOptions := make([]huh.Option[string], 0, len(config.TUIColumns))
for _, column := range config.TUIColumns {
columnOptions = append(columnOptions, huh.NewOption(columnLabels[column], column).Selected(contains(columns, column)))
}
valid := func(s string) error {
n, err := strconv.Atoi(s)
if err != nil || n < 0 {
return fmt.Errorf("enter a non-negative number")
}
return nil
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Recent hosts shown").Description("10 by default; 0 shows all. Favorites are additional.").Value(&history).Validate(valid),
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
).Title("History & activity"), huh.NewGroup(
huh.NewMultiSelect[string]().Title("Shown in the TUI next to each host").
Description("Reachability opens a TCP connection to every listed host's SSH port.").
Options(columnOptions...).Value(&columns),
huh.NewInput().Title("Reachability timeout (ms)").Description("300 by default").Value(&timeout).Validate(valid),
).Title("TUI display")).Run()
if err != nil {
return err
}
cfg.TUI.Columns = orderColumns(cfg.TUI.EffectiveColumns(), columns)
if ms, _ := strconv.Atoi(timeout); ms != 300 {
cfg.TUI.ReachabilityTimeout = ms
} else {
cfg.TUI.ReachabilityTimeout = 0
}
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
cfg.Activity.Enabled = enabled
return nil
}
var columnLabels = map[string]string{
"alias": "Shortcut alias", "ip": "IP address", "kind": "Kind (device/vm/static)", "source": "Source (live/cache/static)",
"status": "NetBox status (if not active)", "site": "Site", "location": "Location (site › locations › rack › U)", "role": "Role", "platform": "Platform", "tenant": "Tenant",
"cluster": "Cluster", "tags": "Tags", "reachability": "Reachability (TCP check ✓/✗)",
}
func contains(list []string, value string) bool {
for _, item := range list {
if item == value {
return true
}
}
return false
}
// orderColumns keeps an existing custom order and appends new selections in
// the canonical order; the multi-select itself does not preserve order.
func orderColumns(previous, selected []string) []string {
out := []string{}
for _, column := range previous {
if contains(selected, column) {
out = append(out, column)
}
}
for _, column := range config.TUIColumns {
if contains(selected, column) && !contains(out, column) {
out = append(out, column)
}
}
return out
}
+31 -6
View File
@@ -24,6 +24,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
options := formatOptions(o.Options) options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards) forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect preConnect := o.PreConnect
postDisconnect := o.PostDisconnect
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
@@ -70,6 +71,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s) _, err := parseForwards(s)
return err return err
}), }),
huh.NewInput().Title("Post-disconnect script").Description("Local command after the client exits; none disables inheritance.").Value(&postDisconnect),
huh.NewInput(). huh.NewInput().
Title("Pre-connect hook"). Title("Pre-connect hook").
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+ Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
@@ -94,6 +96,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
ExtraArgs: parseLines(extraArgs), ExtraArgs: parseLines(extraArgs),
Options: parsed, Options: parsed,
PreConnect: strings.TrimSpace(preConnect), PreConnect: strings.TrimSpace(preConnect),
PostDisconnect: strings.TrimSpace(postDisconnect),
}, nil }, nil
} }
@@ -259,22 +262,36 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
Title("Kind"). Title("Kind").
Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")). Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")).
Value(&match.Kind), Value(&match.Kind),
huh.NewInput().
Title("Site").
Description("NetBox site name or slug, e.g. fsn1").
Value(&match.Site),
huh.NewInput().
Title("Role").
Description("NetBox device/VM role name or slug, e.g. core-switch").
Value(&match.Role),
huh.NewInput().
Title("Platform").
Description("NetBox platform name or slug, e.g. junos").
Value(&match.Platform),
huh.NewInput().
Title("Status").
Description("NetBox status value, e.g. active").
Value(&match.Status),
huh.NewInput(). huh.NewInput().
Title("Name pattern"). Title("Name pattern").
Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com"). Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com").
Value(&match.Name). Value(&match.Name).
Validate(func(s string) error { Validate(func(s string) error {
candidate := match candidate := match
candidate.Tag = strings.TrimSpace(candidate.Tag) candidate.Name = s
candidate.Name = strings.TrimSpace(s) return trimMatch(candidate).Validate("rule")
return candidate.Validate("rule")
}), }),
).Title("Rule match")).Run() ).Title("Rule match")).Run()
if err != nil { if err != nil {
return rule, err return rule, err
} }
match.Tag = strings.TrimSpace(match.Tag) match = trimMatch(match)
match.Name = strings.TrimSpace(match.Name)
options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions) options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions)
if err != nil { if err != nil {
@@ -285,10 +302,18 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
func describeMatch(m config.SSHMatch) string { func describeMatch(m config.SSHMatch) string {
var parts []string var parts []string
for _, field := range [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name}} { for _, field := range matchFields(m) {
if field[1] != "" { if field[1] != "" {
parts = append(parts, field[0]+"="+field[1]) parts = append(parts, field[0]+"="+field[1])
} }
} }
return "[" + strings.Join(parts, " ") + "]" return "[" + strings.Join(parts, " ") + "]"
} }
// trimMatch removes surrounding spaces from every selector.
func trimMatch(m config.SSHMatch) config.SSHMatch {
for _, field := range []*string{&m.Tag, &m.Instance, &m.Kind, &m.Name, &m.Site, &m.Role, &m.Platform, &m.Tenant, &m.Status} {
*field = strings.TrimSpace(*field)
}
return m
}
+169 -7
View File
@@ -3,6 +3,7 @@ package setup
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@@ -95,6 +96,7 @@ func runMenu(cfg *config.Config) error {
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("Custom commands — mtr, ping, scripts", "commands"),
huh.NewOption("History & activity logging", "operations"),
huh.NewOption("Completion", "completion"), huh.NewOption("Completion", "completion"),
huh.NewOption("Save and exit", "save"), huh.NewOption("Save and exit", "save"),
). ).
@@ -125,6 +127,8 @@ func runMenu(cfg *config.Config) error {
err = editShortcuts(cfg) err = editShortcuts(cfg)
case "commands": case "commands":
err = editCommands(cfg) err = editCommands(cfg)
case "operations":
err = editOperations(cfg)
case "completion": case "completion":
err = editCompletion(cfg) err = editCompletion(cfg)
case "save": case "save":
@@ -178,6 +182,11 @@ func editResolverCache(cfg *config.Config) error {
hostnameDomain := cfg.Resolver.HostnameDomain hostnameDomain := cfg.Resolver.HostnameDomain
cacheTTL := strconv.Itoa(cfg.Cache.TTL) cacheTTL := strconv.Itoa(cfg.Cache.TTL)
cachePath := cfg.Cache.Path cachePath := cfg.Cache.Path
dnsSuggest, dnsSaveLink := cfg.DNS.SuggestMode(), cfg.DNS.SaveLinkMode()
dnsDomains := formatDNSDomains(cfg.DNS.Domains)
modes := func(ask, always, never string) []huh.Option[string] {
return []huh.Option[string]{huh.NewOption(ask, config.DNSAsk), huh.NewOption(always, config.DNSAlways), huh.NewOption(never, config.DNSNever)}
}
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
Title("Resolver strategies"). Title("Resolver strategies").
@@ -211,7 +220,25 @@ func editResolverCache(cfg *config.Config) error {
Title("Cache file"). Title("Cache file").
Description("Where resolved hosts are stored. Leave empty for the default location."). Description("Where resolved hosts are stored. Leave empty for the default location.").
Value(&cachePath), Value(&cachePath),
).Title("Resolver & cache")).Run() ).Title("Resolver & cache"), huh.NewGroup(
huh.NewSelect[string]().
Title("Unknown names: suggest the host behind the DNS address?").
Options(modes("ask", "always take the first suggestion (also in scripts)", "never (no DNS lookup)")...).
Value(&dnsSuggest),
huh.NewSelect[string]().
Title("Save a shortcut (link) after a suggestion?").
Options(modes("ask", "always", "never")...).
Value(&dnsSaveLink),
huh.NewText().
Title("DNS domains for short names").
Description("One rule per line: PATTERN = DOMAIN, e.g.\nmx* = easysahre.de\nah* = jhfduwia.de\nA line with only a domain applies to every name.").
Lines(5).
Value(&dnsDomains).
Validate(func(s string) error {
_, err := parseDNSDomains(s)
return err
}),
).Title("DNS names")).Run()
if err != nil { if err != nil {
return err return err
} }
@@ -221,9 +248,49 @@ func editResolverCache(cfg *config.Config) error {
cfg.Resolver.HostnameDomain = strings.Trim(strings.TrimSpace(hostnameDomain), ".") cfg.Resolver.HostnameDomain = strings.Trim(strings.TrimSpace(hostnameDomain), ".")
cfg.Cache.TTL, _ = strconv.Atoi(cacheTTL) cfg.Cache.TTL, _ = strconv.Atoi(cacheTTL)
cfg.Cache.Path = strings.TrimSpace(cachePath) cfg.Cache.Path = strings.TrimSpace(cachePath)
cfg.DNS.Domains, _ = parseDNSDomains(dnsDomains)
cfg.DNS.Suggest, cfg.DNS.SaveLink = keepDefault(dnsSuggest), keepDefault(dnsSaveLink)
return nil return nil
} }
// keepDefault stores "ask" as unset, so the config only lists changes.
func keepDefault(mode string) string {
if mode == config.DNSAsk {
return ""
}
return mode
}
func formatDNSDomains(rules []config.DNSDomain) string {
lines := make([]string, 0, len(rules))
for _, rule := range rules {
if rule.Match == "" {
lines = append(lines, rule.Domain)
} else {
lines = append(lines, rule.Match+" = "+rule.Domain)
}
}
return strings.Join(lines, "\n")
}
// parseDNSDomains reads "PATTERN = DOMAIN" lines; a bare domain matches all names.
func parseDNSDomains(text string) ([]config.DNSDomain, error) {
var rules []config.DNSDomain
for _, line := range strings.Split(text, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
rule := config.DNSDomain{Domain: line}
if match, domain, ok := strings.Cut(line, "="); ok {
rule = config.DNSDomain{Match: strings.TrimSpace(match), Domain: strings.TrimSpace(domain)}
}
rules = append(rules, rule)
}
err := (&config.Config{DNS: config.DNSConfig{Domains: rules}}).ValidateDNS()
return rules, err
}
func editShortcuts(cfg *config.Config) error { func editShortcuts(cfg *config.Config) error {
shortcutDomains := strings.Join(cfg.Shortcuts.Domains, ", ") shortcutDomains := strings.Join(cfg.Shortcuts.Domains, ", ")
stripHyphens := cfg.Shortcuts.StripHyphens stripHyphens := cfg.Shortcuts.StripHyphens
@@ -364,9 +431,15 @@ func validateStrategies(s string) error {
func parseStrategies(s string) []string { return splitList(s) } func parseStrategies(s string) []string { return splitList(s) }
// Save validates cfg and writes it to the config file, replacing the old file. // Save validates cfg and writes it to the config file, replacing the old file.
func Save(cfg config.Config) error { return save(cfg) } func Save(cfg config.Config) error { return SaveTo(cfg, os.Stdout) }
func save(cfg config.Config) error { // SaveTo is Save with the confirmation written to w; callers that run
// before a connection pass os.Stderr to keep stdout clean.
func SaveTo(cfg config.Config, w io.Writer) error { return saveTo(cfg, w) }
func save(cfg config.Config) error { return saveTo(cfg, os.Stdout) }
func saveTo(cfg config.Config, w io.Writer) error {
if err := config.ValidateCommandAlias(cfg.Shell.Alias); err != nil { if err := config.ValidateCommandAlias(cfg.Shell.Alias); err != nil {
return err return err
} }
@@ -382,6 +455,15 @@ 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.ValidateLinks(); err != nil {
return err
}
if err := cfg.ValidateDNS(); err != nil {
return err
}
if err := cfg.ValidateOperations(); err != nil {
return err
}
if err := cfg.ValidateCommands(); err != nil { if err := cfg.ValidateCommands(); err != nil {
return err return err
} }
@@ -420,6 +502,12 @@ func save(cfg config.Config) error {
for _, s := range cfg.Resolver.Strategies { for _, s := range cfg.Resolver.Strategies {
fmt.Fprintf(&b, " - %s\n", s) fmt.Fprintf(&b, " - %s\n", s)
} }
if cfg.Resolver.Fallback {
b.WriteString(" fallback: true\n")
}
if cfg.Resolver.FallbackTimeout > 0 {
fmt.Fprintf(&b, " fallback_timeout: %d\n", cfg.Resolver.FallbackTimeout)
}
if len(cfg.Resolver.ManagementSubnets) > 0 { if len(cfg.Resolver.ManagementSubnets) > 0 {
b.WriteString(" management_subnets:\n") b.WriteString(" management_subnets:\n")
for _, s := range cfg.Resolver.ManagementSubnets { for _, s := range cfg.Resolver.ManagementSubnets {
@@ -446,12 +534,19 @@ func save(cfg config.Config) error {
if cfg.SSH.DefaultPort > 0 { if cfg.SSH.DefaultPort > 0 {
fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort) fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort)
} }
if cfg.SSH.WarnStatus != nil && !sameStrings(cfg.SSH.WarnStatus, config.DefaultWarnStatus) {
quoted := make([]string, 0, len(cfg.SSH.WarnStatus))
for _, status := range cfg.SSH.WarnStatus {
quoted = append(quoted, strconv.Quote(status))
}
fmt.Fprintf(&b, " warn_status: [%s]\n", strings.Join(quoted, ", "))
}
writeSSHOptions(&b, " ", cfg.SSH.SSHOptions) writeSSHOptions(&b, " ", cfg.SSH.SSHOptions)
if len(cfg.SSH.Rules) > 0 { if len(cfg.SSH.Rules) > 0 {
b.WriteString(" rules:\n") b.WriteString(" rules:\n")
for _, rule := range cfg.SSH.Rules { for _, rule := range cfg.SSH.Rules {
b.WriteString(" - match:\n") b.WriteString(" - match:\n")
for _, field := range [][2]string{{"tag", rule.Match.Tag}, {"instance", rule.Match.Instance}, {"kind", rule.Match.Kind}, {"name", rule.Match.Name}} { for _, field := range matchFields(rule.Match) {
if field[1] != "" { if field[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", field[0], field[1]) fmt.Fprintf(&b, " %s: %q\n", field[0], field[1])
} }
@@ -483,6 +578,38 @@ func save(cfg config.Config) error {
} }
} }
if cfg.DNS.Suggest != "" || cfg.DNS.SaveLink != "" || len(cfg.DNS.Domains) > 0 {
b.WriteString("\ndns:\n")
if cfg.DNS.Suggest != "" {
fmt.Fprintf(&b, " suggest: %s\n", cfg.DNS.SuggestMode())
}
if cfg.DNS.SaveLink != "" {
fmt.Fprintf(&b, " save_link: %s\n", cfg.DNS.SaveLinkMode())
}
if len(cfg.DNS.Domains) > 0 {
b.WriteString(" domains:\n")
for _, rule := range cfg.DNS.Domains {
if rule.Match != "" {
fmt.Fprintf(&b, " - match: %q\n domain: %q\n", rule.Match, rule.Domain)
} else {
fmt.Fprintf(&b, " - domain: %q\n", rule.Domain)
}
}
}
}
if len(cfg.Links) > 0 {
b.WriteString("\nlinks:\n")
names := make([]string, 0, len(cfg.Links))
for name := range cfg.Links {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Fprintf(&b, " %s: %q\n", strings.ToLower(name), cfg.Links[name])
}
}
if len(cfg.Groups) > 0 { if len(cfg.Groups) > 0 {
b.WriteString("\ngroups:\n") b.WriteString("\ngroups:\n")
names := make([]string, 0, len(cfg.Groups)) names := make([]string, 0, len(cfg.Groups))
@@ -552,9 +679,26 @@ func save(cfg config.Config) error {
for _, arg := range command.Args { for _, arg := range command.Args {
fmt.Fprintf(&b, " - %q\n", arg) fmt.Fprintf(&b, " - %q\n", arg)
} }
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
if command.Match != (config.SSHMatch{}) {
b.WriteString(" match:\n")
for _, pair := range matchFields(command.Match) {
if pair[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
}
}
}
} }
} }
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\n", cfg.TUI.HistoryLimit)
if cfg.TUI.Columns != nil && !sameStrings(cfg.TUI.Columns, config.DefaultTUIColumns) {
fmt.Fprintf(&b, " columns: [%s]\n", strings.Join(cfg.TUI.Columns, ", "))
}
if cfg.TUI.ReachabilityTimeout > 0 {
fmt.Fprintf(&b, " reachability_timeout: %d\n", cfg.TUI.ReachabilityTimeout)
}
fmt.Fprintf(&b, "activity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
if cfg.Shell.Alias != "" { if cfg.Shell.Alias != "" {
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias) fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
} }
@@ -563,17 +707,17 @@ func save(cfg config.Config) error {
return fmt.Errorf("writing config: %w", err) return fmt.Errorf("writing config: %w", err)
} }
fmt.Printf("\nConfig saved → %s\n", path) fmt.Fprintf(w, "\nConfig saved → %s\n", path)
return nil return nil
} }
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 && o.PreConnect == "" && o.PostDisconnect == ""
} }
// 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}, {"pre_connect", o.PreConnect}, {"post_disconnect", o.PostDisconnect}} {
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])
} }
@@ -612,3 +756,21 @@ func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
} }
} }
} }
// matchFields lists the selectors of a rule or command match in config order.
func matchFields(m config.SSHMatch) [][2]string {
return [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name},
{"site", m.Site}, {"role", m.Role}, {"platform", m.Platform}, {"tenant", m.Tenant}, {"status", m.Status}}
}
func sameStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !strings.EqualFold(a[i], b[i]) {
return false
}
}
return true
}
+99
View File
@@ -698,3 +698,102 @@ func TestSaveCommandsRoundTrip(t *testing.T) {
t.Fatalf("commands lost: %+v", got.Commands) t.Fatalf("commands lost: %+v", got.Commands)
} }
} }
func TestOperationsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "token"},
TUI: config.TUIConfig{HistoryLimit: 25},
Activity: config.ActivityConfig{Enabled: true, RetentionDays: 7, MaxEntries: 50},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PostDisconnect: "echo done"}, Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "lab"}, SSHOptions: config.SSHOptions{PostDisconnect: "none"}}}},
Commands: map[string]config.HostCommand{"mtr": {Args: []string{"mtr", "{address}"}, AliasPrefix: "m", Timeout: "10s", Confirm: true, PostRun: "echo done", Match: config.SSHMatch{Tag: "router", Instance: "prod"}}},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got.TUI, cfg.TUI) || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
t.Fatalf("round trip lost operations: %+v", got)
}
}
func TestSaveRoundtripNetBoxInsightSettings(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://nb.example", Token: "keyring"},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}, Fallback: true, FallbackTimeout: 400},
TUI: config.TUIConfig{HistoryLimit: 10, Columns: []string{"ip", "platform", "reachability"}, ReachabilityTimeout: 900},
SSH: config.SSHConfig{WarnStatus: []string{"planned"}, Rules: []config.SSHRule{{
Match: config.SSHMatch{Platform: "junos", Site: "fsn1", Role: "core", Tenant: "acme", Status: "active"},
SSHOptions: config.SSHOptions{ProxyJump: "jump"},
}}},
Commands: map[string]config.HostCommand{"cli": {Args: []string{"cli", "{address}"}, Match: config.SSHMatch{Platform: "eos"}}},
}
if err := Save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !loaded.Resolver.Fallback || loaded.Resolver.FallbackTimeout != 400 {
t.Fatalf("resolver lost: %+v", loaded.Resolver)
}
if !reflect.DeepEqual(loaded.TUI.Columns, []string{"ip", "platform", "reachability"}) || !loaded.TUI.ReachabilityEnabled() || loaded.TUI.ReachabilityTimeout != 900 {
t.Fatalf("tui lost: %+v", loaded.TUI)
}
if !loaded.SSH.WarnsStatus("planned") || loaded.SSH.WarnsStatus("offline") {
t.Fatalf("warn_status lost: %v", loaded.SSH.WarnStatus)
}
if got := loaded.SSH.Rules[0].Match; got != cfg.SSH.Rules[0].Match {
t.Fatalf("rule match lost: %+v", got)
}
if loaded.Commands["cli"].Match.Platform != "eos" {
t.Fatalf("command match lost: %+v", loaded.Commands["cli"].Match)
}
if !config.IsKeyringToken(loaded.NetBox.Token) || loaded.NetBox.TokenVersion != 0 {
t.Fatalf("keyring token changed: %+v", loaded.NetBox)
}
// Defaults stay implicit, so later default changes reach existing configs.
cfg = config.Config{NetBox: config.NetBoxConfig{URL: "https://nb.example"}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}}
if err := Save(cfg); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
for _, key := range []string{"warn_status", "columns", "reachability", "fallback"} {
if strings.Contains(string(data), key) {
t.Errorf("default %s written:\n%s", key, data)
}
}
}
func TestDNSDomainsTextAndSave(t *testing.T) {
rules, err := parseDNSDomains("mx* = easysahre.de\n\nah* = jhfduwia.de\nfallback.de\n")
if err != nil || len(rules) != 3 || rules[0] != (config.DNSDomain{Match: "mx*", Domain: "easysahre.de"}) || rules[2].Match != "" {
t.Fatalf("parsed %+v, %v", rules, err)
}
if formatDNSDomains(rules) != "mx* = easysahre.de\nah* = jhfduwia.de\nfallback.de" {
t.Fatalf("format: %q", formatDNSDomains(rules))
}
if _, err := parseDNSDomains("mx* = "); err == nil {
t.Fatal("empty domain accepted")
}
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{NetBox: config.NetBoxConfig{URL: "https://nb.example"}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
DNS: config.DNSConfig{Suggest: "never", SaveLink: "always", Domains: rules}, Links: map[string]string{"mx123": "prod/web07"}}
if err := Save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded.DNS, cfg.DNS) || loaded.Links["mx123"] != "prod/web07" {
t.Fatalf("lost: %+v %v", loaded.DNS, loaded.Links)
}
}
+4
View File
@@ -21,6 +21,8 @@ type WrapperFlags struct {
ForwardArgs []string ForwardArgs []string
// Tunnel runs ssh without a remote command (-N), for netssh tunnel. // Tunnel runs ssh without a remote command (-N), for netssh tunnel.
Tunnel bool Tunnel bool
// Force connects without asking about a NetBox status in ssh.warn_status.
Force bool
} }
// ExtractWrapperFlags removes netssh's long options that appear before the // ExtractWrapperFlags removes netssh's long options that appear before the
@@ -40,6 +42,8 @@ func (c Client) ExtractWrapperFlags(args []string) (WrapperFlags, []string, erro
flags.DryRun = true flags.DryRun = true
case arg == "--no-jump": case arg == "--no-jump":
flags.NoJump = true flags.NoJump = true
case arg == "--force":
flags.Force = true
case arg == "--jump": case arg == "--jump":
if i+1 >= len(args) { if i+1 >= len(args) {
return flags, nil, fmt.Errorf("--jump requires a host") return flags, nil, fmt.Errorf("--jump requires a host")
+233
View File
@@ -0,0 +1,233 @@
package tui
import (
"errors"
"net"
"strconv"
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestFilterByNetBoxAttributes(t *testing.T) {
entries := []netbox.HostEntry{
{Name: "sw1", Kind: "device", Status: "active", Site: config.Ref{Name: "FSN 1", Slug: "fsn1"}, Platform: config.Ref{Slug: "junos"}, Role: config.Ref{Slug: "core"}},
{Name: "sw2", Kind: "device", Status: "offline", Site: config.Ref{Slug: "nbg1"}, Platform: config.Ref{Slug: "junos"}},
{Name: "web", Kind: "vm", Status: "active", Site: config.Ref{Slug: "fsn1"}, Tenant: config.Ref{Name: "ACME"}},
}
for filter, want := range map[string]string{
"status:active": "sw1 web",
"site:fsn1": "sw1 web",
"site:FSN-1": "sw1",
"platform:junos status:active": "sw1",
"role:core": "sw1",
"tenant:acme kind:vm": "web",
"bogus": "sw1 sw2 web",
} {
var names []string
for _, e := range applyFilter(entries, parseFilter(filter)) {
names = append(names, e.Name)
}
if got := strings.Join(names, " "); got != want {
t.Errorf("%q: got %q, want %q", filter, got, want)
}
}
}
func TestStatusBadgeShownForInactiveHosts(t *testing.T) {
m := New(nil, nil, "")
m.updateListItems([]netbox.HostEntry{{Name: "a", Status: "active"}, {Name: "b", Status: "offline"}})
var out strings.Builder
for i, it := range m.list.Items() {
compactDelegate{marked: map[string]bool{}}.Render(&out, m.list, i, it)
out.WriteString("\n")
}
if strings.Contains(out.String(), "[active]") || !strings.Contains(out.String(), "[offline]") {
t.Fatalf("unexpected badges:\n%s", out.String())
}
}
func TestReachabilityProbesListedHosts(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
defer ln.Close()
port := ln.Addr().(*net.TCPAddr).Port
m := New(nil, nil, "")
m.SetReachability(time.Second, func(name, kind string, tags []string) (int, bool) {
return port, name != "behind-jump"
})
_, cmd := m.Update(searchResultMsg{query: "", recent: true, entries: []netbox.HostEntry{
{Name: "up", PrimaryIP4: "127.0.0.1"},
{Name: "behind-jump", PrimaryIP4: "127.0.0.1"},
}})
if cmd == nil {
t.Fatal("no probe started")
}
for _, msg := range runBatch(cmd) {
m.Update(msg)
}
up := hostItem{name: "up"}.key()
skipped := hostItem{name: "behind-jump"}.key()
if m.reach[up] != reachUp || m.reach[skipped] != reachSkipped {
t.Fatalf("states: %v", m.reach)
}
var out strings.Builder
m.list.Select(0)
compactDelegate{marked: m.marked, reach: m.reach}.Render(&out, m.list, 0, m.list.Items()[0])
if !strings.Contains(out.String(), "✓") {
t.Fatalf("reachable mark missing: %q", out.String())
}
// A second result list does not probe hosts that already have a state.
_, cmd = m.Update(searchResultMsg{query: "", recent: true, entries: []netbox.HostEntry{{Name: "up", PrimaryIP4: "127.0.0.1"}}})
if len(runBatch(cmd)) != 0 {
t.Fatal("host probed twice")
}
}
func TestUnreachableHostMarked(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
port := ln.Addr().(*net.TCPAddr).Port
ln.Close()
m := New(nil, nil, "")
m.SetReachability(200*time.Millisecond, func(string, string, []string) (int, bool) { return port, true })
_, cmd := m.Update(searchResultMsg{recent: true, entries: []netbox.HostEntry{{Name: "down", PrimaryIP4: "127.0.0.1"}}})
for _, msg := range runBatch(cmd) {
m.Update(msg)
}
if m.reach[hostItem{name: "down"}.key()] != reachDown {
t.Fatalf("states: %v", m.reach)
}
}
// runBatch executes a command and the commands of a batch it returns.
func runBatch(cmd tea.Cmd) []tea.Msg {
if cmd == nil {
return nil
}
msg := cmd()
if batch, ok := msg.(tea.BatchMsg); ok {
var out []tea.Msg
for _, c := range batch {
out = append(out, runBatch(c)...)
}
return out
}
if msg == nil {
return nil
}
return []tea.Msg{msg}
}
func TestDetailViewLoadsAndConnects(t *testing.T) {
m := New(nil, nil, "")
var asked string
m.SetDetails(func(name, kind string, id int) (string, error) {
asked = name + "/" + strconv.Itoa(id)
return "sw1 (device)\n Site FSN1\n", nil
})
m.updateListItems([]netbox.HostEntry{{Name: "sw1", ID: 7, Kind: "device", PrimaryIP4: "10.0.0.7"}})
_, cmd := m.Update(tea.KeyPressMsg{Code: 'l', Mod: tea.ModCtrl})
if m.detailHost == nil || !strings.Contains(m.viewContent(), "Loading") {
t.Fatal("detail view not opened")
}
m.Update(cmd())
if asked != "sw1/7" || !strings.Contains(m.viewContent(), "Site FSN1") {
t.Fatalf("details not shown (asked %q):\n%s", asked, m.viewContent())
}
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.selected == nil || m.selected.Name != "sw1" {
t.Fatalf("enter in detail view should connect: %+v", m.selected)
}
}
func TestDetailViewShowsErrorAndEscCloses(t *testing.T) {
m := New(nil, nil, "")
m.SetDetails(func(string, string, int) (string, error) { return "", errors.New("boom") })
m.updateListItems([]netbox.HostEntry{{Name: "sw1"}})
_, cmd := m.Update(tea.KeyPressMsg{Code: 'l', Mod: tea.ModCtrl})
m.Update(cmd())
if !strings.Contains(m.viewContent(), "Error: boom") {
t.Fatalf("error not shown:\n%s", m.viewContent())
}
m.Update(tea.KeyPressMsg{Code: tea.KeyEscape})
if m.detailHost != nil || m.selected != nil {
t.Fatal("esc should close the detail view without selecting")
}
}
func TestCtrlGOpensNetBoxPage(t *testing.T) {
m := New(nil, nil, "")
var opened string
m.SetOpener(func(name, kind string, id int) error { opened = name; return nil })
m.updateListItems([]netbox.HostEntry{{Name: "web", Kind: "vm"}})
_, cmd := m.Update(tea.KeyPressMsg{Code: 'g', Mod: tea.ModCtrl})
if cmd == nil || m.selected != nil {
t.Fatal("ctrl+g must not quit the TUI")
}
m.Update(cmd())
if opened != "web" || !strings.Contains(m.viewContent(), "opened web in NetBox") {
t.Fatalf("opened %q:\n%s", opened, m.viewContent())
}
}
func TestConfiguredColumns(t *testing.T) {
m := New(nil, nil, "")
m.SetColumns([]string{"platform", "site", "tags", "kind"})
m.updateListItems([]netbox.HostEntry{{Name: "sw1", Kind: "device", PrimaryIP4: "10.0.0.7", Status: "offline", Tags: []string{"core", "dc"},
Site: config.Ref{Name: "FSN 1", Slug: "fsn1"}, Platform: config.Ref{Slug: "junos"}}})
var out strings.Builder
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
got := out.String()
for _, want := range []string{"platform:junos", "site:fsn1", "#core #dc", "[device]"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in %q", want, got)
}
}
if strings.Contains(got, "10.0.0.7") || strings.Contains(got, "[offline]") || strings.Contains(got, "[live]") {
t.Fatalf("columns not configured must be hidden: %q", got)
}
if strings.Index(got, "platform:") > strings.Index(got, "site:") {
t.Fatalf("configured order not kept: %q", got)
}
m.SetColumns(nil)
out.Reset()
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
if got := out.String(); !strings.HasSuffix(strings.TrimSpace(got), "sw1") {
t.Fatalf("empty column list should show only the name: %q", got)
}
}
func TestLocationColumnAndFilter(t *testing.T) {
entries := []netbox.HostEntry{
{Name: "srv1", Site: config.Ref{Name: "FSN1"}, Location: []config.Ref{{Name: "Building A", Slug: "building-a"}, {Name: "Room 2.04", Slug: "room-2-04"}}, Rack: "R12", Position: "20"},
{Name: "srv2", Site: config.Ref{Name: "NBG1"}, Location: []config.Ref{{Name: "Hall 1", Slug: "hall-1"}}, Rack: "B03"},
}
for filter, want := range map[string]string{"location:building-a": "srv1", "location:room-2-04": "srv1", "rack:b03": "srv2", "location:hall-1": "srv2"} {
var names []string
for _, e := range applyFilter(entries, parseFilter(filter)) {
names = append(names, e.Name)
}
if got := strings.Join(names, " "); got != want {
t.Errorf("%q: got %q, want %q", filter, got, want)
}
}
m := New(nil, nil, "")
m.SetColumns([]string{"location"})
m.updateListItems(entries[:1])
var out strings.Builder
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
if !strings.Contains(out.String(), "FSN1 › Building A › Room 2.04 › R12 › U20") {
t.Fatalf("location column: %q", out.String())
}
}
+541 -20
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"net"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -22,6 +23,7 @@ import (
// SelectedHost is returned when the user confirms a host in the TUI. // SelectedHost is returned when the user confirms a host in the TUI.
type SelectedHost struct { type SelectedHost struct {
Command string
Kind string Kind string
Name string Name string
IP string IP string
@@ -52,6 +54,25 @@ type noteResultMsg struct {
saved bool saved bool
} }
// reachMsg is the result of probing a listed host's SSH port.
type reachMsg struct {
key string
state reachState
}
// detailMsg carries the text of the detail view (ctrl+l).
type detailMsg struct {
key string
text string
err error
}
// flashMsg is a short notice in the footer, e.g. after opening NetBox.
type flashMsg struct {
text string
err error
}
type searchResultMsg struct { type searchResultMsg struct {
query string query string
seq int seq int
@@ -63,6 +84,8 @@ type searchResultMsg struct {
// --- list item --- // --- list item ---
type hostItem struct { type hostItem struct {
provenance string
favorite, pinned bool
label string // display only; name remains the canonical target label string // display only; name remains the canonical target
alias string // shortcut alias shown next to the name (shortcuts.show) alias string // shortcut alias shown next to the name (shortcuts.show)
name string name string
@@ -70,6 +93,11 @@ type hostItem struct {
ip string ip string
kind string kind string
tags []string tags []string
status string
site, role string
platform, tenant string
cluster string
location string // site › locations › rack › U
} }
func (h hostItem) Title() string { func (h hostItem) Title() string {
@@ -83,8 +111,85 @@ func (h hostItem) FilterValue() string { return h.name }
// --- compact list delegate --- // --- compact list delegate ---
// reachState is the result of the reachability probe of a host.
type reachState uint8
const (
reachUnknown reachState = iota
reachPending
reachUp
reachDown
reachSkipped // behind a jump host: not probed
)
// compactDelegate shares the model's marks so marked hosts show a dot. // compactDelegate shares the model's marks so marked hosts show a dot.
type compactDelegate struct{ marked map[string]bool } // With reach set, a column shows whether the SSH port answers.
type compactDelegate struct {
marked map[string]bool
reach map[string]reachState
columns []string // nil = defaultColumns
}
// defaultColumns matches config.DefaultTUIColumns.
var defaultColumns = []string{"alias", "ip", "source", "status"}
var (
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
attrStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
aliasStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("109"))
statusStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("214"))
)
// column renders one configured column of a host, or "" when it is empty.
func (h hostItem) column(name string) string {
attr := func(key, value string) string {
if value == "" {
return ""
}
return attrStyle.Render(key + ":" + value)
}
switch name {
case "alias":
if h.alias != "" {
return aliasStyle.Render("→ " + h.alias)
}
case "ip":
if h.ip != "" {
return dimStyle.Render(h.ip)
}
case "kind":
if h.kind != "" {
return "[" + h.kind + "]"
}
case "source":
if h.provenance != "" {
return "[" + h.provenance + "]"
}
case "status":
if h.status != "" && !strings.EqualFold(h.status, "active") {
return statusStyle.Render("[" + h.status + "]")
}
case "site":
return attr("site", h.site)
case "location":
if h.location != "" {
return attrStyle.Render("⌂ " + h.location)
}
case "role":
return attr("role", h.role)
case "platform":
return attr("platform", h.platform)
case "tenant":
return attr("tenant", h.tenant)
case "cluster":
return attr("cluster", h.cluster)
case "tags":
if len(h.tags) > 0 {
return attrStyle.Render("#" + strings.Join(h.tags, " #"))
}
}
return ""
}
func (d compactDelegate) Height() int { return 1 } func (d compactDelegate) Height() int { return 1 }
func (d compactDelegate) Spacing() int { return 0 } func (d compactDelegate) Spacing() int { return 0 }
@@ -98,11 +203,36 @@ 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() badge := ""
if h.alias != "" { if h.pinned {
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+h.alias) badge = "◆ "
} else if h.favorite {
badge = "★ "
}
columns := d.columns
if columns == nil {
columns = defaultColumns
}
// The reachability mark is a fixed-width prefix so names stay aligned.
reach := ""
if d.reach != nil {
switch d.reach[h.key()] {
case reachUp:
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("2")).Render("✓") + " "
case reachDown:
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("✗") + " "
case reachPending:
reach = dimStyle.Render("·") + " "
default:
reach = " "
}
}
line := " " + mark + reach + badge + h.Title()
for _, name := range columns {
if text := h.column(name); text != "" {
line += " " + text
}
} }
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, " "))
} }
@@ -114,22 +244,45 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
type filterOpts struct { type filterOpts struct {
tags []string tags []string
kind string kind string
status, site, role, platform, tenant string
location string
}
func (f filterOpts) empty() bool {
return len(f.tags) == 0 && f.kind == "" && f.status == "" && f.site == "" && f.role == "" && f.platform == "" && f.tenant == "" && f.location == ""
} }
func parseFilter(s string) filterOpts { func parseFilter(s string) filterOpts {
var f filterOpts var f filterOpts
for _, part := range strings.Fields(s) { for _, part := range strings.Fields(s) {
if after, ok := strings.CutPrefix(part, "tag:"); ok { key, value, ok := strings.Cut(part, ":")
f.tags = append(f.tags, after) if !ok {
} else if after, ok := strings.CutPrefix(part, "kind:"); ok { continue
f.kind = after }
switch strings.ToLower(key) {
case "tag":
f.tags = append(f.tags, value)
case "kind":
f.kind = value
case "status":
f.status = value
case "site":
f.site = value
case "role":
f.role = value
case "platform":
f.platform = value
case "tenant":
f.tenant = value
case "location", "rack":
f.location = value
} }
} }
return f return f
} }
func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry { func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
if len(f.tags) == 0 && f.kind == "" { if f.empty() {
return entries return entries
} }
out := make([]netbox.HostEntry, 0, len(entries)) out := make([]netbox.HostEntry, 0, len(entries))
@@ -137,6 +290,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
if f.kind != "" && e.Kind != f.kind { if f.kind != "" && e.Kind != f.kind {
continue continue
} }
if f.status != "" && !strings.EqualFold(e.Status, f.status) {
continue
}
if f.site != "" && !e.Site.Matches(f.site) || f.role != "" && !e.Role.Matches(f.role) ||
f.platform != "" && !e.Platform.Matches(f.platform) || f.tenant != "" && !e.Tenant.Matches(f.tenant) ||
f.location != "" && !inLocation(e, f.location) {
continue
}
if len(f.tags) > 0 { if len(f.tags) > 0 {
tagSet := make(map[string]bool, len(e.Tags)) tagSet := make(map[string]bool, len(e.Tags))
for _, t := range e.Tags { for _, t := range e.Tags {
@@ -161,6 +322,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
// --- Model --- // --- Model ---
type Model struct { type Model struct {
historyLimit int
favorites, pinned map[string]bool
savePreferences func(map[string]bool, map[string]bool) error
commandsFor func(string, string, []string) []string
actionHost *hostItem
actionNames []string
actionIndex int
noteErr error noteErr error
editHost *hostItem editHost *hostItem
noteInput textarea.Model noteInput textarea.Model
@@ -195,6 +364,17 @@ type Model struct {
hostLabel func(string) string hostLabel func(string) string
aliasFor func(string) string // shortcut alias per target, "" for none 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
columns []string // nil = defaultColumns
reach map[string]reachState // probe results by hostItem.key()
reachTimeout time.Duration
reachPort func(name, kind string, tags []string) (port int, probe bool)
opener func(name, kind string, id int) error
details func(name, kind string, id int) (string, error)
detailHost *hostItem
detailText string
detailErr error
flash string
} }
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model { func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
@@ -203,7 +383,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ti.Focus() ti.Focus()
fi := textinput.New() fi := textinput.New()
fi.Placeholder = "tag:prod kind:vm" fi.Placeholder = "tag:prod kind:vm status:active site:fsn1 location:room-2 role:router platform:junos"
fi.Prompt = "Filter: " fi.Prompt = "Filter: "
ei := textinput.New() ei := textinput.New()
@@ -229,6 +409,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ni.CharLimit = 0 ni.CharLimit = 0
ni.SetHeight(10) ni.SetHeight(10)
return &Model{ return &Model{
historyLimit: 10, favorites: map[string]bool{}, pinned: map[string]bool{},
noteInput: ni, noteInput: ni,
defaultPort: port, defaultPort: port,
input: ti, input: ti,
@@ -250,14 +431,40 @@ func (m *Model) Init() tea.Cmd {
// loadRecent returns a Cmd that immediately resolves to the recently-used host list. // loadRecent returns a Cmd that immediately resolves to the recently-used host list.
func (m *Model) loadRecent() tea.Cmd { func (m *Model) loadRecent() tea.Cmd {
favoriteNames, pinned, limit := copyBools(m.favorites), copyBools(m.pinned), m.historyLimit
return func() tea.Msg { return func() tea.Msg {
if m.cache == nil { if m.cache == nil {
return searchResultMsg{query: "", entries: nil, recent: true} return searchResultMsg{query: "", entries: nil, recent: true}
} }
recent := m.cache.RecentlyUsed(10) recent := m.cache.RecentlyUsed(limit)
seen := map[string]bool{}
var favorites []cache.Entry
for name, enabled := range favoriteNames {
if !enabled {
continue
}
e, _ := m.cache.Get(name)
if e.Name == "" {
e.Name = name
}
favorites = append(favorites, e)
seen[name] = true
}
sort.Slice(favorites, func(i, j int) bool {
if pinned[favorites[i].Name] != pinned[favorites[j].Name] {
return pinned[favorites[i].Name]
}
return favorites[i].Name < favorites[j].Name
})
for _, e := range recent {
if !seen[e.Name] {
favorites = append(favorites, e)
}
}
recent = favorites
entries := make([]netbox.HostEntry, len(recent)) entries := make([]netbox.HostEntry, len(recent))
for i, e := range recent { for i, e := range recent {
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags} entries[i] = entryFromCache(e, false)
} }
return searchResultMsg{query: "", entries: entries, recent: true} return searchResultMsg{query: "", entries: entries, recent: true}
} }
@@ -281,6 +488,25 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
} }
return m, nil return m, nil
case reachMsg:
if m.reach != nil {
m.reach[msg.key] = msg.state
}
return m, nil
case detailMsg:
if m.detailHost != nil && m.detailHost.key() == msg.key {
m.detailText, m.detailErr = msg.text, msg.err
}
return m, nil
case flashMsg:
m.flash = msg.text
if msg.err != nil {
m.flash = "error: " + msg.err.Error()
}
return m, nil
case tea.WindowSizeMsg: case tea.WindowSizeMsg:
m.width = msg.Width m.width = msg.Width
m.height = msg.Height m.height = msg.Height
@@ -294,6 +520,51 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.String() == "ctrl+c" { if msg.String() == "ctrl+c" {
return m, tea.Quit return m, tea.Quit
} }
if m.flash != "" {
m.flash = ""
}
if m.detailHost != nil {
switch msg.String() {
case "esc", "ctrl+l", "q":
m.detailHost = nil
m.input.Focus()
case "enter":
h := m.detailHost
m.selected = &SelectedHost{Name: h.name, IP: h.ip, Kind: h.kind}
return m, tea.Quit
case "ctrl+g":
return m, m.openCmd(*m.detailHost)
}
return m, nil
}
if m.actionHost != nil {
switch msg.String() {
case "esc":
m.actionHost = nil
case "up":
if m.actionIndex > 0 {
m.actionIndex--
}
case "down":
if m.actionIndex+1 < len(m.actionNames) {
m.actionIndex++
}
case "enter":
h := m.actionHost
if m.actionIndex == 0 {
if len(m.markOrder) > 0 {
m.selected = &SelectedHost{Action: ActionMulti, Targets: append([]string(nil), m.markOrder...)}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip}
}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip, Command: m.actionNames[m.actionIndex], Targets: append([]string(nil), m.markOrder...)}
}
return m, tea.Quit
}
return m, nil
}
if m.noteMode { if m.noteMode {
if m.noteBusy { if m.noteBusy {
return m, nil return m, nil
@@ -403,6 +674,43 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "ctrl+c", "esc": case "ctrl+c", "esc":
return m, tea.Quit return m, tea.Quit
case "ctrl+r":
if h, ok := m.list.SelectedItem().(hostItem); ok {
m.actionHost = &h
m.actionIndex = 0
m.actionNames = []string{"SSH"}
if m.commandsFor != nil {
m.actionNames = append(m.actionNames, m.commandsFor(h.name, h.kind, h.tags)...)
}
}
return m, nil
case "ctrl+d", "ctrl+p":
if h, ok := m.list.SelectedItem().(hostItem); ok {
favorites, pinned := copyBools(m.favorites), copyBools(m.pinned)
if msg.String() == "ctrl+p" {
pinned[h.name] = !pinned[h.name]
if pinned[h.name] {
favorites[h.name] = true
}
} else {
favorites[h.name] = !favorites[h.name]
if !favorites[h.name] {
delete(pinned, h.name)
}
}
if m.savePreferences != nil {
if err := m.savePreferences(favorites, pinned); err != nil {
m.err = err
return m, nil
}
}
m.favorites, m.pinned = favorites, pinned
m.updateListItems(m.lastResults)
if m.recentMode && m.input.Value() == "" {
return m, m.loadRecent()
}
}
return m, nil
case "ctrl+f": case "ctrl+f":
m.filterOpen = true m.filterOpen = true
m.input.Blur() m.input.Blur()
@@ -442,6 +750,25 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Quit return m, tea.Quit
} }
case "ctrl+g":
if item, ok := m.list.SelectedItem().(hostItem); ok {
return m, m.openCmd(item)
}
return m, nil
case "ctrl+l":
if item, ok := m.list.SelectedItem().(hostItem); ok && m.details != nil {
m.detailHost = &item
m.detailText, m.detailErr = "", nil
m.input.Blur()
details, key := m.details, item.key()
return m, func() tea.Msg {
text, err := details(item.name, item.kind, item.id)
return detailMsg{key: key, text: text, err: err}
}
}
return m, nil
case "ctrl+t": case "ctrl+t":
if item, ok := m.list.SelectedItem().(hostItem); ok { if item, ok := m.list.SelectedItem().(hostItem); ok {
m.forwardMode = true m.forwardMode = true
@@ -505,7 +832,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.recentMode = true m.recentMode = true
m.lastResults = msg.entries m.lastResults = msg.entries
m.updateListItems(msg.entries) m.updateListItems(msg.entries)
return m, nil return m, m.probeCmd()
} }
if msg.seq != m.seq || msg.query != m.input.Value() { if msg.seq != m.seq || msg.query != m.input.Value() {
return m, nil // discard stale result return m, nil // discard stale result
@@ -514,7 +841,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.err = msg.err m.err = msg.err
m.lastResults = msg.entries m.lastResults = msg.entries
m.updateListItems(msg.entries) m.updateListItems(msg.entries)
return m, nil return m, m.probeCmd()
} }
if m.noteMode { if m.noteMode {
@@ -563,6 +890,50 @@ func (m *Model) View() tea.View {
} }
func (m *Model) viewContent() string { func (m *Model) viewContent() string {
if m.detailHost != nil {
var out strings.Builder
title := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("Details — " + m.detailHost.Title())
out.WriteString(title + "\n\n")
switch {
case m.detailErr != nil:
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("Error: "+m.detailErr.Error()) + "\n")
case m.detailText == "":
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("Loading…") + "\n")
default:
text := m.detailText
if m.height > 4 {
lines := strings.Split(strings.TrimRight(text, "\n"), "\n")
if len(lines) > m.height-4 {
lines = append(lines[:m.height-5], "…")
}
text = strings.Join(lines, "\n") + "\n"
}
out.WriteString(text)
}
if m.flash != "" {
out.WriteString("\n" + m.flash + "\n")
}
out.WriteString("\n" + lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("enter connect ctrl+g open in NetBox esc back") + "\n")
return out.String()
}
if m.actionHost != nil {
var out strings.Builder
fmt.Fprintf(&out, "Action for %s", m.actionHost.Title())
if len(m.markOrder) > 0 {
fmt.Fprintf(&out, " (%d marked hosts)", len(m.markOrder))
}
out.WriteString("\n\n")
for i, n := range m.actionNames {
marker := " "
if i == m.actionIndex {
marker = "> "
}
fmt.Fprintf(&out, "%s%s\n", marker, n)
}
out.WriteString("\n↑/↓ select enter run esc cancel\n")
return out.String()
}
if m.noteMode { if m.noteMode {
target := "local" target := "local"
if m.noteRemote { if m.noteRemote {
@@ -623,7 +994,10 @@ func (m *Model) viewContent() string {
sb.WriteString(m.editInput.View() + "\n") sb.WriteString(m.editInput.View() + "\n")
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n") sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n")
} else { } else {
hint := "ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox" hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox ctrl+l details ctrl+g NetBox page"
if m.flash != "" {
hint = m.flash
}
if n := len(m.markOrder); n > 0 { if n := len(m.markOrder); n > 0 {
hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n) hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n)
} }
@@ -651,8 +1025,7 @@ func (m *Model) doSearch(query string, seq int) tea.Cmd {
var cached []netbox.HostEntry var cached []netbox.HostEntry
if m.cache != nil { if m.cache != nil {
for _, entry := range m.cache.Search(query) { for _, entry := range m.cache.Search(query) {
source, name := netbox.SplitTarget(entry.Name) cached = append(cached, entryFromCache(entry, true))
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags})
} }
} }
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) { if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
@@ -686,10 +1059,34 @@ func (m *Model) netboxSearchOpts() netbox.SearchOptions {
return netbox.SearchOptions{Tag: tag, Kind: f.kind} return netbox.SearchOptions{Tag: tag, Kind: f.kind}
} }
// entryFromCache converts a cache entry for the list. With split, the
// instance prefix becomes Source, like in live NetBox results.
func entryFromCache(e cache.Entry, split bool) netbox.HostEntry {
h := netbox.HostEntry{Name: e.Name, ID: e.ID, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Cached: true, CachedAt: e.CachedAt, Static: e.Static,
Status: e.Status, Site: cache.RefOf(e.Site), Role: cache.RefOf(e.Role), Platform: cache.RefOf(e.Platform), Tenant: cache.RefOf(e.Tenant),
Location: e.Location, Rack: e.Rack, Position: e.Position}
if split {
h.Source, h.Name = netbox.SplitTarget(e.Name)
}
return h
}
// updateListItems applies the active filter and sets the list items. // updateListItems applies the active filter and sets the list items.
func (m *Model) updateListItems(entries []netbox.HostEntry) { func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value()) f := parseFilter(m.filterInput.Value())
filtered := applyFilter(entries, f) filtered := append([]netbox.HostEntry(nil), applyFilter(entries, f)...)
sort.SliceStable(filtered, func(i, j int) bool {
rank := func(e netbox.HostEntry) int {
if m.pinned[e.Target()] {
return 2
}
if m.favorites[e.Target()] {
return 1
}
return 0
}
return rank(filtered[i]) > rank(filtered[j])
})
items := make([]list.Item, len(filtered)) items := make([]list.Item, len(filtered))
labels := make([]string, len(filtered)) labels := make([]string, len(filtered))
counts := make(map[string]int, len(filtered)) counts := make(map[string]int, len(filtered))
@@ -718,7 +1115,24 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
alias = "" alias = ""
} }
} }
items[i] = hostItem{label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags} provenance := "live"
if e.Static {
provenance = "static"
} else if e.Cached {
if e.CachedAt.IsZero() {
provenance = "saved host; resolve on connect"
} else {
age := max(time.Duration(0), time.Since(e.CachedAt)).Round(time.Second)
provenance = "cache " + age.String()
if m.cache != nil {
if _, fresh := m.cache.Get(e.Target()); !fresh {
provenance += ", stale"
}
}
}
}
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags, status: e.Status,
site: e.Site.Key(), role: e.Role.Key(), platform: e.Platform.Key(), tenant: e.Tenant.Key(), cluster: e.Cluster, location: e.LocationPath()}
} }
m.list.SetItems(items) m.list.SetItems(items)
m.resizeList() m.resizeList()
@@ -866,3 +1280,110 @@ func (m *Model) SetHostLabel(format func(string) string) {
func (m *Model) SetAliases(aliasFor func(target string) string) { func (m *Model) SetAliases(aliasFor func(target string) string) {
m.aliasFor = aliasFor m.aliasFor = aliasFor
} }
func copyBools(in map[string]bool) map[string]bool {
out := map[string]bool{}
for k, v := range in {
out[k] = v
}
return out
}
func (m *Model) SetHistoryLimit(limit int) { m.historyLimit = limit }
func (m *Model) SetPreferences(favorites, pinned map[string]bool, save func(map[string]bool, map[string]bool) error) {
m.favorites, m.pinned = copyBools(favorites), copyBools(pinned)
m.savePreferences = save
}
func (m *Model) SetCommands(commands func(string, string, []string) []string) {
m.commandsFor = commands
}
// SetReachability enables the reachability column: listed hosts are probed
// with a TCP connect to the port returned by portFor, unless it returns
// probe=false (for hosts behind a jump host). Configure it before the program starts.
func (m *Model) SetReachability(timeout time.Duration, portFor func(name, kind string, tags []string) (port int, probe bool)) {
if timeout <= 0 {
timeout = 300 * time.Millisecond
}
m.reach = map[string]reachState{}
m.reachTimeout = timeout
m.reachPort = portFor
m.list.SetDelegate(m.delegate())
}
// SetColumns selects what is shown next to each hostname, in order (see
// config.TUIColumns). "reachability" is ignored here: SetReachability
// enables the check. Configure it before the program starts.
func (m *Model) SetColumns(columns []string) {
m.columns = append([]string{}, columns...)
m.list.SetDelegate(m.delegate())
}
func (m *Model) delegate() compactDelegate {
return compactDelegate{marked: m.marked, reach: m.reach, columns: m.columns}
}
// probeCmd starts probes for listed hosts that have no result yet.
func (m *Model) probeCmd() tea.Cmd {
if m.reach == nil {
return nil
}
var cmds []tea.Cmd
for _, it := range m.list.Items() {
h, ok := it.(hostItem)
if !ok || m.reach[h.key()] != reachUnknown {
continue
}
key := h.key()
port, probe := 22, true
if m.reachPort != nil {
port, probe = m.reachPort(h.name, h.kind, h.tags)
}
if !probe || h.ip == "" {
m.reach[key] = reachSkipped
continue
}
m.reach[key] = reachPending
address, timeout := h.ip, m.reachTimeout
cmds = append(cmds, func() tea.Msg {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout)
if err != nil {
return reachMsg{key: key, state: reachDown}
}
_ = conn.Close()
return reachMsg{key: key, state: reachUp}
})
}
return tea.Batch(cmds...)
}
// SetOpener opens a host's NetBox page (ctrl+g). Configure it before the program starts.
func (m *Model) SetOpener(open func(name, kind string, id int) error) { m.opener = open }
// SetDetails provides the text of the detail view (ctrl+l). Configure it before the program starts.
func (m *Model) SetDetails(details func(name, kind string, id int) (string, error)) {
m.details = details
}
func (m *Model) openCmd(h hostItem) tea.Cmd {
if m.opener == nil {
return nil
}
open := m.opener
return func() tea.Msg {
if err := open(h.name, h.kind, h.id); err != nil {
return flashMsg{err: err}
}
return flashMsg{text: "opened " + h.name + " in NetBox"}
}
}
// inLocation reports whether a host is in the location want at any level of
// its location chain, or in the rack named want.
func inLocation(e netbox.HostEntry, want string) bool {
for _, location := range e.Location {
if location.Matches(want) {
return true
}
}
return want != "" && strings.EqualFold(e.Rack, want)
}
+67
View File
@@ -0,0 +1,67 @@
package tui
import (
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestFavoritesHistoryAndActions(t *testing.T) {
c := cache.New("", 3600)
for _, name := range []string{"a", "b", "pinned"} {
c.Upsert(cache.Entry{Name: name, IP: "10.0.0.1", Kind: "device"})
c.MarkUsed(name)
}
m := New(nil, c, "")
m.SetHistoryLimit(1)
m.SetPreferences(map[string]bool{"pinned": true, "offline/missing": true}, map[string]bool{"pinned": true}, nil)
msg := m.loadRecent()().(searchResultMsg)
if len(msg.entries) < 2 || msg.entries[0].Target() != "pinned" {
t.Fatalf("%+v", msg.entries)
}
m.Update(msg)
m.Update(tea.WindowSizeMsg{Width: 160, Height: 30})
if !strings.Contains(m.View().Content, "◆") || !strings.Contains(m.View().Content, "cache") {
t.Fatal(m.View().Content)
}
m.SetCommands(func(name, kind string, tags []string) []string { return []string{"mtr"} })
m.Update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl})
m.Update(tea.KeyPressMsg{Code: tea.KeyDown})
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.Selected() == nil || m.Selected().Command != "mtr" || m.Selected().Name != "pinned" {
t.Fatalf("%+v", m.Selected())
}
}
func TestHistoryLimitAndPreferencePersistence(t *testing.T) {
c := cache.New("", 3600)
for _, n := range []string{"a", "b", "c"} {
c.Upsert(cache.Entry{Name: n})
c.MarkUsed(n)
}
m := New(nil, c, "")
m.SetHistoryLimit(2)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 2 {
t.Fatal(got)
}
m.SetHistoryLimit(0)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 3 {
t.Fatal(got)
}
saved := false
m.SetPreferences(nil, nil, func(f, p map[string]bool) error { saved = f["prod/web"] && p["prod/web"]; return nil })
entries := []netbox.HostEntry{{Name: "web", Source: "prod", Cached: true, CachedAt: time.Now().Add(-2 * time.Hour)}}
m.lastResults = entries
m.updateListItems(entries)
m.Update(tea.KeyPressMsg{Code: 'p', Mod: tea.ModCtrl})
if !saved {
t.Fatal("pin not persisted")
}
item := m.list.Items()[0].(hostItem)
if !strings.Contains(item.provenance, "stale") {
t.Fatal(item.provenance)
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
config_only </dev/null config_only </dev/null
rm -f "$XDG_CONFIG_HOME/netssh.yaml" rm -f "$XDG_CONFIG_HOME/netssh.yaml"
# no NetBox, static hosts, add, name, address, user, port, tags, back, save # no NetBox, static hosts, add, name, address, user, port, tags, back, save
out=$(python3 /tests/drive.py 2 4 1 legacy-box 10.231.0.50 admin "" legacy 5 9) out=$(python3 /tests/drive.py 2 4 1 legacy-box 10.231.0.50 admin "" legacy 5 11)
[[ $out == *"Config saved"* ]] && ok "configure saves" || bad "configure saves" "$out" [[ $out == *"Config saved"* ]] && ok "configure saves" || bad "configure saves" "$out"
expect_out "config has the host" 'address: "10.231.0.50"' cat "$XDG_CONFIG_HOME/netssh.yaml" expect_out "config has the host" 'address: "10.231.0.50"' cat "$XDG_CONFIG_HOME/netssh.yaml"
expect_eq "connect to the configured host" "admin" netssh legacy-box whoami expect_eq "connect to the configured host" "admin" netssh legacy-box whoami