Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
20d7a40543 | ||
|
|
1f46d9d9e5 | ||
|
|
10eadaa13c | ||
|
|
ffaa0a9c3c | ||
|
|
42bf21a79d | ||
|
|
81b8715331 | ||
|
|
41e488bce8 | ||
|
|
9f281e9ce6 | ||
|
|
f1da2ea379 | ||
|
|
c58b26ecf8 | ||
|
|
c46c95e04b | ||
|
|
314dabf1f7 | ||
|
|
a23a9bb125 | ||
|
|
6e80b733dc | ||
|
|
d3e7f137c3 | ||
|
|
6493e7c41e | ||
|
|
a8bf2b4141 | ||
|
|
396d489187 | ||
|
|
699b9469b6 | ||
|
|
a31aab4110 | ||
|
|
dbb99bdded | ||
|
|
55e7a5106b | ||
|
|
3c9e54b254 | ||
|
|
a950a82552 | ||
|
|
5821dfbebd | ||
|
|
2be9f19cc2 | ||
|
|
c71cc0ae3b | ||
|
|
2cadea30c7 | ||
|
|
25c03fff9d | ||
|
|
8e4417a6ea | ||
|
|
2fafa0b119 | ||
|
|
b009863c37 | ||
|
|
a1c9210f3c | ||
|
|
15fb57c0ea | ||
|
|
c55aae520f | ||
|
|
88af34a64b | ||
|
|
314905c538 | ||
|
|
ad3f14186d | ||
|
|
4f08a1c92a | ||
|
|
45a2abce90 | ||
|
|
f7fc1b2a37 | ||
|
|
c45ad9f0d1 | ||
|
|
97fc8f5458 | ||
|
|
d24870e4c0 | ||
|
|
053db984be | ||
|
|
6419fbb00d |
No files matched your search
@@ -22,6 +22,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
|
||||
- [Quick start](#quick-start)
|
||||
- [Configuration](#configuration) — [wizard](#interactive-wizard), [manual config](#manual-config), [reference](#configuration-reference), [environment variables](#environment-variables), [files](#files-and-directories), [multiple instances](#multiple-netbox-instances)
|
||||
- [Usage](#usage) — [command overview](#command-overview), [SSH options](#ssh-options), [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)
|
||||
- [Hotkey cheat sheet](#hotkey-cheat-sheet) — search, editors, tmux and zellij
|
||||
- [Recipes](#recipes)
|
||||
- [IP Resolution Strategies](#ip-resolution-strategies)
|
||||
- [Shell Completion](#shell-completion) and [Shell Hook](#shell-hook)
|
||||
@@ -211,7 +212,7 @@ Every key, its default, and the section that explains it. Keys marked *layered*
|
||||
| `netbox.url` | string | — | NetBox base URL (single instance). Use either `netbox` or `netboxes`. |
|
||||
| `netbox.token` | string | — | API token; `nbt_…` is v2, anything else v1. |
|
||||
| `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. |
|
||||
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
|
||||
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `disable_prefix`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
|
||||
| `resolver.strategies` | list | `[management_subnet, primary_ip]` | Tried in order, first IP wins — see [IP Resolution Strategies](#ip-resolution-strategies). The wizard suggests `primary_ip`. |
|
||||
| `resolver.management_subnets` | list of CIDR | `[]` | Used by `management_subnet`. |
|
||||
| `resolver.interface_name` | string | — | Used by `interface_name`, e.g. `mgmt0`. |
|
||||
@@ -305,7 +306,41 @@ netssh notes show lab/web01 --netbox --kind device
|
||||
|
||||
For direct connections without an instance prefix, every instance must be reachable to verify uniqueness. A qualified target queries only its own instance and can use a fresh cached IP while other instances are offline. Qualified shortcuts such as `office/web01` also support configured domain suffixes and hyphen folding.
|
||||
|
||||
Cache entries and generated aliases retain the instance name (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed.
|
||||
Cache entries retain the instance name. Generated aliases include it by default (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed.
|
||||
|
||||
**Aliases and TUI names without an instance prefix.** Set `disable_prefix: true`
|
||||
on individual instances, or enable **Hide instance prefix in aliases and TUI?**
|
||||
when editing an instance in `netssh configure`:
|
||||
|
||||
```yaml
|
||||
netboxes:
|
||||
- name: office
|
||||
url: https://netbox.office.example
|
||||
token: nbt_office-token
|
||||
disable_prefix: true
|
||||
- name: lab
|
||||
url: https://netbox.lab.example
|
||||
token: nbt_lab-token
|
||||
```
|
||||
|
||||
With the appropriate domain shortcut, this generates `web01` for
|
||||
`office/web01.example.com` and `lab_web01` for the lab host. The default is
|
||||
`false`. The alias command still contains the full `instance/hostname`, so it
|
||||
connects to the selected instance even when another instance has the same host
|
||||
name. Domain stripping, rewrites and hyphen folding still apply.
|
||||
|
||||
If a bare alias conflicts with another generated alias, a reserved qualified
|
||||
alias, `netssh`, or your configured command alias, the instance prefix is kept.
|
||||
It is also kept if the bare name is not a valid shell alias (e.g. starts with a digit).
|
||||
The TUI result list also hides the prefix for this instance; duplicate visible
|
||||
names keep their prefixes to remain distinguishable. Selection, autocomplete,
|
||||
connection editors, notes and cache identities still use the full target.
|
||||
Completion already offers unique hostnames
|
||||
without an instance prefix.
|
||||
|
||||
Open a new shell with the installed netssh hook to regenerate and load aliases.
|
||||
No cache refresh is needed for this setting. Existing aliases in an already open
|
||||
shell remain until removed or the shell is replaced.
|
||||
|
||||
Local notes remain keyed by the NetBox URL, host kind, and canonical hostname. Migrating a single instance or renaming it preserves its notes. Use `instance/hostname` and `--kind` for uncached local notes; these operations work offline. NetBox comments and interface/IP lookups always use the selected instance's credentials.
|
||||
|
||||
@@ -597,7 +632,9 @@ multi:
|
||||
| Exclude one pane | `Ctrl+b e` (again: include) or `netssh sync --pane` | not possible — zellij syncs whole tabs |
|
||||
| Shown in the border | `[SYNC]` receives broadcast, `[SOLO]` excluded | `(SYNC)` in the tab name |
|
||||
|
||||
**Keys in tmux.** `S` and `e` are free in a default tmux (`E` would be "spread panes evenly"). netssh binds them after your prefix when it opens panes, but only if your own `tmux.conf` does not already use them — then it keeps your binding and says so. They act only in windows opened by `netssh multi`; elsewhere they just show a message. Change or turn them off with `multi.sync_key` / `multi.solo_key` (`none`), e.g. `sync_key: C-s` for `prefix Ctrl+s`.
|
||||
**Keys in tmux.** The active pane border keeps the available broadcast/solo keys visible after attaching. See the [hotkey cheat sheet](#hotkey-cheat-sheet) for navigation and editor keys.
|
||||
|
||||
`S` and `e` are free in a default tmux (`E` would be "spread panes evenly"). netssh binds them after your prefix when it opens panes, but only if your own `tmux.conf` does not already use them — then it keeps your binding and says so. They act only in windows opened by `netssh multi`; elsewhere they just show a message. Change or turn them off with `multi.sync_key` / `multi.solo_key` (`none`), e.g. `sync_key: C-s` for `prefix Ctrl+s`.
|
||||
|
||||
**In the TUI**, mark hosts with `Space` (or all listed hosts with `Ctrl+A`) and press `Enter` to open them together.
|
||||
|
||||
@@ -714,21 +751,7 @@ netssh
|
||||
|
||||
The TUI opens with your 10 most-recently-connected hosts. Start typing to search all cached hosts or query NetBox live.
|
||||
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| type | filter hosts (300 ms debounce → NetBox query) |
|
||||
| `Tab` | autocomplete top result into the search field |
|
||||
| `↑` / `↓` | navigate results |
|
||||
| `Enter` | connect to selected host |
|
||||
| `Space` | mark/unmark the host; with marks, `Enter` opens them side by side (`netssh multi`) |
|
||||
| `Ctrl+A` | mark all listed hosts (again: unmark all) |
|
||||
| `Ctrl+O` | open an SFTP session to the selected host |
|
||||
| `Ctrl+T` | start a tunnel: enter forward names or specs (`web, 8080:localhost:80`) |
|
||||
| `Ctrl+E` | open inline editor to override user/port before connecting |
|
||||
| `Ctrl+N` | edit local notes for the selected server |
|
||||
| `Ctrl+B` | edit NetBox comments for the selected server |
|
||||
| `Ctrl+F` | open/close tag and kind filter (`tag:prod kind:vm`) |
|
||||
| `Esc` / `Ctrl+C` | quit (or close filter/edit if open) |
|
||||
See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys.
|
||||
|
||||
**Tag and kind filter** — press `Ctrl+F` to open a second input line:
|
||||
|
||||
@@ -817,6 +840,100 @@ The hook is a no-op when the cache is fresh — it adds no measurable delay to y
|
||||
netssh search app- # prints matching hostnames, one per line
|
||||
```
|
||||
|
||||
## Hotkey cheat sheet
|
||||
|
||||
Keys depend on the current screen: for example, `Ctrl+B` opens NetBox comments
|
||||
in the search, while tmux uses `Ctrl+b` as its default prefix.
|
||||
“Then” means release the first combination before pressing the next key;
|
||||
`S` is uppercase (`Shift+s`).
|
||||
|
||||
### Search and host selection
|
||||
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| type | filter hosts (300 ms debounce → NetBox query) |
|
||||
| `Tab` | autocomplete top result into the search field |
|
||||
| `↑` / `↓` | navigate results |
|
||||
| `PageUp` / `PageDown` | previous/next results page |
|
||||
| `Home` / `End` | first/last result (also moves the search cursor) |
|
||||
| `Enter` | connect to selected host |
|
||||
| `Space` | mark/unmark the host; with marks, `Enter` opens them side by side (`netssh multi`) |
|
||||
| `Ctrl+A` | mark all listed hosts (again: unmark all) |
|
||||
| `Ctrl+O` | open an SFTP session to the selected host |
|
||||
| `Ctrl+T` | start a tunnel: enter forward names or specs (`web, 8080:localhost:80`) |
|
||||
| `Ctrl+E` | open inline editor to override user/port before connecting |
|
||||
| `Ctrl+N` | edit local notes for the selected server |
|
||||
| `Ctrl+B` | edit NetBox comments for the selected server |
|
||||
| `Ctrl+F` | open/close tag and kind filter (`tag:prod kind:vm`) |
|
||||
| `Esc` | quit search |
|
||||
| `Ctrl+C` | quit from any TUI mode, including editors |
|
||||
|
||||
### Filters, connection/tunnel editors and notes
|
||||
|
||||
| Screen | Key | Action |
|
||||
|---|---|---|
|
||||
| Filter (`Ctrl+F`) | `Enter` | apply filter and return to results |
|
||||
| Filter | `Esc` / `Ctrl+F` | close and clear the filter |
|
||||
| User/port editor (`Ctrl+E`) | `Enter` | connect using the edited user/port |
|
||||
| Tunnel editor (`Ctrl+T`) | `Enter` | start the requested forwards |
|
||||
| User/port or tunnel editor | `Esc` | cancel and return to results |
|
||||
| Local notes / NetBox comments | `Enter` | insert a new line |
|
||||
| Local notes / NetBox comments | `Ctrl+S` | save |
|
||||
| Local notes / NetBox comments | `Esc` | cancel and discard unsaved edits (when not loading/saving) |
|
||||
| Any TUI screen | `Ctrl+C` | quit, discarding unsaved edits |
|
||||
|
||||
Text fields also support their standard cursor movement and editing keys.
|
||||
|
||||
### Multi-mode: tmux
|
||||
|
||||
The active pane's top border shows the configured broadcast/solo shortcuts
|
||||
throughout the session. A narrow pane may clip the legend; zoom it with
|
||||
`Ctrl+b` then `z` to make more room. `[SYNC]` means the pane receives broadcast;
|
||||
`[SOLO]` means it is excluded.
|
||||
|
||||
The following uses tmux's default prefix `Ctrl+b`. Use your own prefix if
|
||||
changed in `tmux.conf`; netssh's legend reads the configured prefix.
|
||||
Navigation keys below are tmux defaults and can be remapped by your configuration.
|
||||
|
||||
| Key | Action |
|
||||
|---|---|
|
||||
| `Ctrl+b` then `S` | toggle broadcast for the current window (netssh default) |
|
||||
| `Ctrl+b` then `e` | exclude/include the active pane in broadcast (netssh default) |
|
||||
| `Ctrl+b` then arrow key | focus the pane in that direction |
|
||||
| `Ctrl+b` then `o` | focus the next pane |
|
||||
| `Ctrl+b` then `z` | zoom/unzoom the active pane |
|
||||
| `Ctrl+b` then `n` / `p` | next/previous window |
|
||||
| `Ctrl+b` then `w` | choose a window |
|
||||
| `Ctrl+b` then `d` | detach; sessions keep running |
|
||||
| `Ctrl+b` then `?` | show all current tmux bindings |
|
||||
| `Enter` after a failed connection | close the pane displaying the error |
|
||||
|
||||
Change broadcast/solo keys with `multi.sync_key` and `multi.solo_key`;
|
||||
`none` disables a binding. Existing user bindings take precedence and are
|
||||
reported in the legend. Command alternatives are `netssh sync` and
|
||||
`netssh sync --pane` (run locally inside the multiplexer).
|
||||
Solo excludes a pane from broadcast; it does not toggle zoom.
|
||||
|
||||
### Multi-mode: zellij
|
||||
|
||||
Zellij's bottom status bar shows the keys for the current mode. These are
|
||||
standard bindings; custom presets may differ.
|
||||
|
||||
| Key | Action |
|
||||
|---|---|
|
||||
| `Ctrl+t` then `s` | toggle broadcast for the entire tab |
|
||||
| `Ctrl+p` then arrow key | move pane focus in pane mode |
|
||||
| `Ctrl+p` then `f` | toggle fullscreen for the focused pane |
|
||||
| `Ctrl+t` then left/right arrow | switch tabs in tab mode |
|
||||
| `Enter` / `Esc` in a control mode | return to normal mode |
|
||||
| `Ctrl+o` then `d` | detach; session keeps running |
|
||||
| `Ctrl+g` | toggle locked mode to pass control keys to the remote application |
|
||||
|
||||
Zellij cannot exclude individual panes from broadcast. `netssh sync` toggles
|
||||
the whole tab. When starting a new zellij session, enable broadcast manually
|
||||
with `Ctrl+t` then `s`; `--sync` is applied automatically only inside an
|
||||
existing zellij session.
|
||||
|
||||
## Recipes
|
||||
|
||||
**Everything through a bastion, except the bastion itself**
|
||||
|
||||
@@ -386,6 +386,7 @@ func runTUI() {
|
||||
}
|
||||
|
||||
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
|
||||
m.SetHostLabel(cfg.HostLabel)
|
||||
m.SetNotes(notes.New(cfg.NetBox.URL, nbClient))
|
||||
m.SetForwards(func(name, kind string, tags []string) []string {
|
||||
return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags}))
|
||||
|
||||
@@ -6,7 +6,7 @@ require (
|
||||
charm.land/bubbles/v2 v2.2.1
|
||||
charm.land/bubbletea/v2 v2.1.1
|
||||
charm.land/huh/v2 v2.0.3
|
||||
charm.land/lipgloss/v2 v2.1.0
|
||||
charm.land/lipgloss/v2 v2.1.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/viper v1.21.0
|
||||
golang.org/x/sys v0.50.0
|
||||
|
||||
@@ -4,8 +4,8 @@ charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
|
||||
charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
||||
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
|
||||
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
|
||||
charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU=
|
||||
charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI=
|
||||
charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc=
|
||||
charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc=
|
||||
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
|
||||
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
|
||||
@@ -30,11 +30,12 @@ type ShellConfig struct {
|
||||
}
|
||||
|
||||
type NetBoxConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
URL string `mapstructure:"url"`
|
||||
Token string `mapstructure:"token"`
|
||||
TokenVersion int `mapstructure:"token_version"`
|
||||
SSH SSHOptions `mapstructure:"ssh"`
|
||||
DisablePrefix bool `mapstructure:"disable_prefix"`
|
||||
Name string `mapstructure:"name"`
|
||||
URL string `mapstructure:"url"`
|
||||
Token string `mapstructure:"token"`
|
||||
TokenVersion int `mapstructure:"token_version"`
|
||||
SSH SSHOptions `mapstructure:"ssh"`
|
||||
}
|
||||
|
||||
type ResolverConfig struct {
|
||||
|
||||
@@ -65,3 +65,17 @@ func (c *Config) CachePath() string {
|
||||
sum := sha256.Sum256([]byte(strings.Join(identities, "\x00")))
|
||||
return filepath.Join(filepath.Dir(c.Cache.Path), fmt.Sprintf("instances-%x", sum[:8]), filepath.Base(c.Cache.Path))
|
||||
}
|
||||
|
||||
// HostLabel omits the configured instance prefix for display only. Callers
|
||||
// must retain the canonical target for connections and handle label collisions.
|
||||
func (c *Config) HostLabel(target string) string {
|
||||
source, host, qualified := strings.Cut(target, "/")
|
||||
if qualified {
|
||||
for _, instance := range c.NetBoxes {
|
||||
if instance.DisablePrefix && strings.EqualFold(instance.Name, source) {
|
||||
return host
|
||||
}
|
||||
}
|
||||
}
|
||||
return target
|
||||
}
|
||||
@@ -15,6 +15,7 @@ func TestLoadNamedNetBoxes(t *testing.T) {
|
||||
- name: Office
|
||||
url: https://office.example/netbox
|
||||
token: nbt_office
|
||||
disable_prefix: true
|
||||
- name: lab
|
||||
url: https://lab.example
|
||||
token: legacy-token
|
||||
@@ -34,7 +35,14 @@ cache:
|
||||
if cfg.NetBox.URL != "" {
|
||||
t.Fatal("legacy environment variables added an unnamed instance")
|
||||
}
|
||||
if !cfg.NetBoxes[0].DisablePrefix || cfg.NetBoxes[1].DisablePrefix {
|
||||
t.Fatal("per-instance alias prefix setting was not loaded")
|
||||
}
|
||||
first := cfg.CachePath()
|
||||
cfg.NetBoxes[0].DisablePrefix = false
|
||||
if cfg.CachePath() != first {
|
||||
t.Fatal("alias prefix setting discarded cache")
|
||||
}
|
||||
if first == cfg.Cache.Path {
|
||||
t.Fatal("named sources reuse legacy cache")
|
||||
}
|
||||
|
||||
@@ -124,9 +124,34 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
|
||||
seen[cfg.Shell.Alias] = true
|
||||
out = append(out, AliasEntry{Name: cfg.Shell.Alias})
|
||||
}
|
||||
for _, e := range entries {
|
||||
|
||||
withoutPrefix := make(map[string]bool, len(cfg.NetBoxes))
|
||||
for _, source := range cfg.NetBoxes {
|
||||
withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix
|
||||
}
|
||||
// Reserve canonical aliases as well as requested bare aliases before
|
||||
// generating any output, so cache ordering cannot redirect a collision.
|
||||
canonical := make(map[string]bool, len(entries))
|
||||
counts := make(map[string]int, len(entries))
|
||||
candidates := make([]string, len(entries))
|
||||
for i, e := range entries {
|
||||
name := shortcuts.AliasName(e.Name, cfg.Shortcuts)
|
||||
if seen[name] || name == "" || !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`).MatchString(name) {
|
||||
canonical[name] = true
|
||||
source, host, qualified := strings.Cut(e.Name, "/")
|
||||
if qualified && withoutPrefix[strings.ToLower(source)] {
|
||||
name = shortcuts.AliasName(host, cfg.Shortcuts)
|
||||
}
|
||||
candidates[i] = name
|
||||
counts[name]++
|
||||
}
|
||||
validAlias := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
|
||||
for i, e := range entries {
|
||||
name := candidates[i]
|
||||
full := shortcuts.AliasName(e.Name, cfg.Shortcuts)
|
||||
if name != full && (counts[name] > 1 || canonical[name] || seen[name] || !validAlias.MatchString(name)) {
|
||||
name = full
|
||||
}
|
||||
if seen[name] || name == "" || !validAlias.MatchString(name) {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
|
||||
@@ -253,3 +253,78 @@ func TestAliasesUseRewriteRules(t *testing.T) {
|
||||
t.Fatalf("entries: %+v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasesOptionalInstancePrefix(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "OFFICE", DisablePrefix: true},
|
||||
{Name: "lab"},
|
||||
},
|
||||
Shortcuts: config.ShortcutsConfig{
|
||||
Domains: []string{".example.com"},
|
||||
Rewrites: []config.ShortcutRewrite{{Pattern: "^web-", Replace: "app"}},
|
||||
},
|
||||
}
|
||||
entries := hook.BuildAliasEntries([]cache.Entry{
|
||||
{Name: "office/web-01.example.com"},
|
||||
{Name: "lab/web-01.example.com"},
|
||||
}, cfg)
|
||||
got := map[string]string{}
|
||||
for _, e := range entries {
|
||||
got[e.Name] = e.Host
|
||||
// Both output formats must keep the fully qualified destination.
|
||||
for _, shell := range []string{"bash", "zsh", "fish"} {
|
||||
if !strings.Contains(e.Definition(shell), e.Host) {
|
||||
t.Fatalf("%s alias lost its target: %s", shell, e.Definition(shell))
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(got) != 2 || got["app01"] != "office/web-01.example.com" || got["lab_app01"] != "lab/web-01.example.com" {
|
||||
t.Fatalf("unexpected aliases: %+v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasesWithoutPrefixCollisions(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "office", DisablePrefix: true},
|
||||
{Name: "lab", DisablePrefix: true},
|
||||
},
|
||||
Shell: config.ShellConfig{Alias: "j"},
|
||||
Shortcuts: config.ShortcutsConfig{Domains: []string{".example.com"}},
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
hosts []string
|
||||
want map[string]string
|
||||
}{
|
||||
{"two instances", []string{"office/web.example.com", "lab/web.example.com"},
|
||||
map[string]string{"j": "", "office_web": "office/web.example.com", "lab_web": "lab/web.example.com"}},
|
||||
{"static host", []string{"office/web.example.com", "web"},
|
||||
map[string]string{"j": "", "office_web": "office/web.example.com", "web": "web"}},
|
||||
{"command aliases", []string{"office/j", "office/netssh"},
|
||||
map[string]string{"j": "", "office_j": "office/j", "office_netssh": "office/netssh"}},
|
||||
{"reserved qualified alias", []string{"office/lab_web", "lab/web"},
|
||||
map[string]string{"j": "", "office_lab_web": "office/lab_web", "web": "lab/web"}},
|
||||
{"invalid bare alias", []string{"office/123.example.com"},
|
||||
map[string]string{"j": "", "office_123": "office/123.example.com"}},
|
||||
{"normalized names", []string{"office/web.example.com", "office/web"},
|
||||
map[string]string{"j": "", "office_web": "office/web"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var input []cache.Entry
|
||||
for _, host := range tc.hosts {
|
||||
input = append(input, cache.Entry{Name: host})
|
||||
}
|
||||
entries := hook.BuildAliasEntries(input, cfg)
|
||||
if len(entries) != len(tc.want) {
|
||||
t.Fatalf("aliases: %+v, want %+v", entries, tc.want)
|
||||
}
|
||||
for _, e := range entries {
|
||||
if host, ok := tc.want[e.Name]; !ok || host != e.Host {
|
||||
t.Fatalf("unexpected alias: %+v", e)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ type fake struct {
|
||||
syncState string
|
||||
keys map[string]string // existing prefix bindings by key
|
||||
solo string
|
||||
prefix string
|
||||
n int
|
||||
}
|
||||
|
||||
@@ -33,6 +34,8 @@ func (f *fake) Output(argv ...string) (string, error) {
|
||||
f.calls = append(f.calls, strings.Join(argv, " "))
|
||||
f.n++
|
||||
switch argv[1] {
|
||||
case "show-options":
|
||||
return f.prefix, nil
|
||||
case "new-window", "new-session":
|
||||
return fmt.Sprintf("@%d %%%d", f.n, f.n), nil
|
||||
case "split-window":
|
||||
@@ -121,6 +124,8 @@ func TestTmuxInside(t *testing.T) {
|
||||
"tmux list-keys -T prefix S",
|
||||
"tmux list-keys -T prefix e",
|
||||
"tmux source-file /tmp/l/netssh-multi.tmux.conf",
|
||||
"tmux set-window-option -t @1 @netssh_keys keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off",
|
||||
"tmux set-window-option -t @1 pane-border-format #{@netssh_host}#{?pane_synchronized, [SYNC],#{?@netssh_solo, [SOLO],}} #{?pane_active, | #{@netssh_keys},} ",
|
||||
"tmux select-window -t @1",
|
||||
}
|
||||
if strings.Join(f.calls, "\n") != strings.Join(want, "\n") {
|
||||
@@ -234,7 +239,7 @@ func TestTmuxKeyBindings(t *testing.T) {
|
||||
t.Errorf("conf lacks %q:\n%s", want, conf)
|
||||
}
|
||||
}
|
||||
if hint != "keys: C-b S broadcast to all panes, C-b e exclude/include this pane" {
|
||||
if hint != "keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off" {
|
||||
t.Errorf("hint %q", hint)
|
||||
}
|
||||
|
||||
@@ -279,3 +284,34 @@ func TestToggleSyncPane(t *testing.T) {
|
||||
t.Fatalf("zellij: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTmuxPersistentHints(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
keys map[string]string
|
||||
want string
|
||||
}{
|
||||
{"custom prefix", nil, "keys: Ctrl+a then Ctrl+s: sync on/off | Ctrl+a then e: solo on/off"},
|
||||
{"occupied key", map[string]string{"C-s": "bind-key -T prefix C-s display-time"}, "keys: Ctrl+a then e: solo on/off; C-a C-s kept your own binding (use netssh sync)"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := newFake(nil, "tmux")
|
||||
f.prefix, f.keys = "C-a", tc.keys
|
||||
if err := Open(Tmux, panes("a", "b"), Options{PerWindow: 1, SyncKey: "C-s", SoloKey: "e"}, f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := 0
|
||||
for _, call := range f.calls {
|
||||
if strings.Contains(call, " @netssh_keys ") {
|
||||
n++
|
||||
if !strings.HasSuffix(call, " @netssh_keys "+tc.want) {
|
||||
t.Fatalf("wrong persistent hint: %s", call)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n != 2 {
|
||||
t.Fatalf("hints installed in %d windows, want 2", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
|
||||
}
|
||||
groups := chunks(panes, opts.PerWindow)
|
||||
first := ""
|
||||
var windows []string
|
||||
for i, group := range groups {
|
||||
name := windowLabel(opts.Label, i, len(groups))
|
||||
format := []string{"-P", "-F", "#{window_id} #{pane_id}", "-n", name}
|
||||
@@ -52,6 +53,7 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
|
||||
}
|
||||
}
|
||||
window, pane, _ := strings.Cut(out, " ")
|
||||
windows = append(windows, window)
|
||||
if first == "" {
|
||||
first = window
|
||||
}
|
||||
@@ -91,6 +93,17 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
|
||||
}
|
||||
if keys != "" {
|
||||
opts.Hint(keys)
|
||||
// Window-local hints remain visible after attaching, including in an
|
||||
// existing session. Keep other windows and the user's status bar intact.
|
||||
for _, window := range windows {
|
||||
if _, err := r.Output("tmux", "set-window-option", "-t", window, "@netssh_keys", keys); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := r.Output("tmux", "set-window-option", "-t", window, "pane-border-format",
|
||||
" #{@netssh_host}#{?pane_synchronized, [SYNC],#{?@netssh_solo, [SOLO],}} #{?pane_active, | #{@netssh_keys},} "); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if inside {
|
||||
_, err := r.Output("tmux", "select-window", "-t", first)
|
||||
@@ -149,8 +162,8 @@ func bindKeys(r Runner, opts Options) (string, error) {
|
||||
var conf strings.Builder
|
||||
var hints, taken []string
|
||||
for _, key := range []struct{ key, binding, what string }{
|
||||
{opts.SyncKey, syncBinding, "broadcast to all panes"},
|
||||
{opts.SoloKey, soloBinding, "exclude/include this pane"},
|
||||
{opts.SyncKey, syncBinding, "sync on/off"},
|
||||
{opts.SoloKey, soloBinding, "solo on/off"},
|
||||
} {
|
||||
if key.key == "" {
|
||||
continue
|
||||
@@ -161,7 +174,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&conf, key.binding, key.key)
|
||||
hints = append(hints, prefix+" "+key.key+" "+key.what)
|
||||
hints = append(hints, displayKey(prefix)+" then "+displayKey(key.key)+": "+key.what)
|
||||
}
|
||||
if conf.Len() > 0 {
|
||||
path := filepath.Join(opts.LayoutDir, "netssh-multi.tmux.conf")
|
||||
@@ -172,7 +185,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
hint := "keys: " + strings.Join(hints, ", ")
|
||||
hint := "keys: " + strings.Join(hints, " | ")
|
||||
if len(hints) == 0 {
|
||||
hint = "toggle broadcast with: netssh sync, netssh sync --pane"
|
||||
}
|
||||
@@ -192,3 +205,9 @@ func freeSession(r Runner, name string) string {
|
||||
candidate = name + "-" + strconv.Itoa(n)
|
||||
}
|
||||
}
|
||||
|
||||
// displayKey expands tmux's modifier notation for the on-screen legend.
|
||||
func displayKey(key string) string {
|
||||
key = strings.ReplaceAll(key, "C-", "Ctrl+")
|
||||
return strings.ReplaceAll(key, "M-", "Alt+")
|
||||
}
|
||||
@@ -108,6 +108,9 @@ func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, ori
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
huh.NewConfirm().Title("Hide instance prefix in aliases and TUI?").
|
||||
Description("Shorter shell aliases and TUI host names. Conflicting names keep their prefix.").
|
||||
Value(&source.DisablePrefix),
|
||||
huh.NewInput().Title("NetBox URL").Placeholder("https://netbox.example.com").Value(&source.URL).Validate(func(value string) error {
|
||||
return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes()
|
||||
}),
|
||||
|
||||
@@ -385,6 +385,9 @@ func save(cfg config.Config) error {
|
||||
b.WriteString("netboxes:\n")
|
||||
for _, source := range cfg.NetBoxes {
|
||||
fmt.Fprintf(&b, " - name: %q\n url: %q\n token: %q\n token_version: %d\n", source.Name, source.URL, source.Token, source.TokenVersion)
|
||||
if source.DisablePrefix {
|
||||
b.WriteString(" disable_prefix: true\n")
|
||||
}
|
||||
if !sshOptionsEmpty(source.SSH) {
|
||||
b.WriteString(" ssh:\n")
|
||||
writeSSHOptions(&b, " ", source.SSH)
|
||||
|
||||
@@ -398,7 +398,7 @@ func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
cfg := config.Config{
|
||||
NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2},
|
||||
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2, DisablePrefix: true},
|
||||
{Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1},
|
||||
},
|
||||
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
@@ -79,3 +80,89 @@ func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) {
|
||||
t.Fatalf("outage warning overflowed view: %d", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenPrefixKeepsCanonicalTargets(t *testing.T) {
|
||||
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "OFFICE", DisablePrefix: true}, {Name: "lab"},
|
||||
}}
|
||||
for _, cached := range []bool{false, true} {
|
||||
for _, action := range []string{"ssh", "sftp", "multi", "autocomplete", "edit", "tunnel"} {
|
||||
t.Run(fmt.Sprintf("cached=%v/%s", cached, action), func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.SetHostLabel(cfg.HostLabel)
|
||||
m.Update(tea.WindowSizeMsg{Width: 100, Height: 24})
|
||||
entries := []netbox.HostEntry{
|
||||
{Source: "office", Name: "web01", PrimaryIP4: "10.0.0.1"},
|
||||
{Source: "lab", Name: "web01", PrimaryIP4: "10.0.0.2"},
|
||||
}
|
||||
if cached {
|
||||
for i := range entries {
|
||||
entries[i].Name = entries[i].Target()
|
||||
entries[i].Source = ""
|
||||
}
|
||||
}
|
||||
m.updateListItems(entries)
|
||||
item := m.list.Items()[0].(hostItem)
|
||||
if item.Title() != "web01" || item.name != "office/web01" {
|
||||
t.Fatalf("display changed identity: %+v", item)
|
||||
}
|
||||
view := m.View().Content
|
||||
if strings.Contains(view, "office/web01") || !strings.Contains(view, "lab/web01") {
|
||||
t.Fatalf("wrong rendered prefixes: %s", view)
|
||||
}
|
||||
switch action {
|
||||
case "ssh", "sftp":
|
||||
key := tea.KeyPressMsg{Code: tea.KeyEnter}
|
||||
if action == "sftp" {
|
||||
key = tea.KeyPressMsg{Code: 'o', Mod: tea.ModCtrl}
|
||||
}
|
||||
m.Update(key)
|
||||
if m.selected == nil || m.selected.Name != "office/web01" {
|
||||
t.Fatalf("lost instance: %+v", m.selected)
|
||||
}
|
||||
case "multi":
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || len(m.selected.Targets) != 1 || m.selected.Targets[0] != "office/web01" {
|
||||
t.Fatalf("multi lost instance: %+v", m.selected)
|
||||
}
|
||||
case "autocomplete":
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyTab})
|
||||
if m.input.Value() != "office/web01" {
|
||||
t.Fatal("autocomplete lost instance")
|
||||
}
|
||||
case "edit":
|
||||
m.Update(tea.KeyPressMsg{Code: 'e', Mod: tea.ModCtrl})
|
||||
if m.editHost == nil || m.editHost.name != "office/web01" {
|
||||
t.Fatal("editor lost instance")
|
||||
}
|
||||
case "tunnel":
|
||||
m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl})
|
||||
if m.forwardHost == nil || m.forwardHost.name != "office/web01" {
|
||||
t.Fatal("tunnel lost instance")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenPrefixDuplicateLabels(t *testing.T) {
|
||||
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "office", DisablePrefix: true}, {Name: "lab", DisablePrefix: true},
|
||||
}}
|
||||
for _, other := range []netbox.HostEntry{
|
||||
{Source: "lab", Name: "WEB"},
|
||||
{Name: "web", Kind: "static"},
|
||||
} {
|
||||
m := New(nil, nil, "")
|
||||
m.SetHostLabel(cfg.HostLabel)
|
||||
m.updateListItems([]netbox.HostEntry{{Source: "office", Name: "web"}, other})
|
||||
for _, entry := range m.list.Items() {
|
||||
item := entry.(hostItem)
|
||||
if item.Title() != item.name {
|
||||
t.Fatalf("ambiguous label: %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+37
-9
@@ -63,14 +63,20 @@ type searchResultMsg struct {
|
||||
// --- list item ---
|
||||
|
||||
type hostItem struct {
|
||||
name string
|
||||
id int
|
||||
ip string
|
||||
kind string
|
||||
tags []string
|
||||
label string // display only; name remains the canonical target
|
||||
name string
|
||||
id int
|
||||
ip string
|
||||
kind string
|
||||
tags []string
|
||||
}
|
||||
|
||||
func (h hostItem) Title() string { return h.name }
|
||||
func (h hostItem) Title() string {
|
||||
if h.label != "" {
|
||||
return h.label
|
||||
}
|
||||
return h.name
|
||||
}
|
||||
func (h hostItem) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) }
|
||||
func (h hostItem) FilterValue() string { return h.name }
|
||||
|
||||
@@ -91,7 +97,7 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
|
||||
if d.marked[h.key()] {
|
||||
mark = "● "
|
||||
}
|
||||
line := fmt.Sprintf(" %s%s %s", mark, h.name, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
|
||||
line := fmt.Sprintf(" %s%s %s", mark, h.Title(), lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
|
||||
if index == m.Index() {
|
||||
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
|
||||
}
|
||||
@@ -181,7 +187,8 @@ type Model struct {
|
||||
editMode bool // Ctrl+E on the selected item
|
||||
forwardMode bool // Ctrl+T on the selected item
|
||||
marked map[string]bool // hostItem.key() of hosts marked with space
|
||||
markOrder []string // targets in the order they were marked
|
||||
hostLabel func(string) string
|
||||
markOrder []string // targets in the order they were marked
|
||||
}
|
||||
|
||||
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
|
||||
@@ -678,12 +685,27 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
|
||||
f := parseFilter(m.filterInput.Value())
|
||||
filtered := applyFilter(entries, f)
|
||||
items := make([]list.Item, len(filtered))
|
||||
labels := make([]string, len(filtered))
|
||||
counts := make(map[string]int, len(filtered))
|
||||
canonical := make(map[string]bool, len(filtered))
|
||||
for i, e := range filtered {
|
||||
labels[i] = e.Target()
|
||||
canonical[strings.ToLower(e.Target())] = true
|
||||
if m.hostLabel != nil {
|
||||
labels[i] = m.hostLabel(e.Target())
|
||||
}
|
||||
counts[strings.ToLower(labels[i])]++
|
||||
}
|
||||
for i, e := range filtered {
|
||||
ip := e.PrimaryIP4
|
||||
if ip == "" {
|
||||
ip = e.PrimaryIP6
|
||||
}
|
||||
items[i] = hostItem{id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
|
||||
label := labels[i]
|
||||
if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) {
|
||||
label = e.Target()
|
||||
}
|
||||
items[i] = hostItem{label: label, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
|
||||
}
|
||||
m.list.SetItems(items)
|
||||
m.resizeList()
|
||||
@@ -819,3 +841,9 @@ func parseForwards(input string, available []string) ([]string, error) {
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// SetHostLabel sets the display name formatter without changing host identity.
|
||||
// Configure it before the program starts, just like SetNotes and SetForwards.
|
||||
func (m *Model) SetHostLabel(format func(string) string) {
|
||||
m.hostLabel = format
|
||||
}
|
||||
@@ -10,7 +10,7 @@ COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
RUN CGO_ENABLED=0 go build -o /out/netssh ./cmd/netssh
|
||||
|
||||
FROM alpine:3.23
|
||||
FROM alpine:3.24
|
||||
# xvfb/xterm/imagemagick/tesseract: render panes in a real terminal emulator,
|
||||
# take screenshots, and read them back with OCR (tests/16-render.sh).
|
||||
RUN apk add --no-cache openssh-client-default tmux zellij bash zsh fish bash-completion \
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
name: netssh-test
|
||||
|
||||
x-netbox: &netbox
|
||||
image: netboxcommunity/netbox:v4.7.4-5.1.1
|
||||
image: netboxcommunity/netbox:v4.7.5-5.1.1
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
redis: {condition: service_healthy}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SSH target for the netssh test environment: every NetBox host, the bastion,
|
||||
# and the static host run this image with a different hostname.
|
||||
FROM alpine:3.23
|
||||
FROM alpine:3.24
|
||||
|
||||
# Alpine locks new accounts with "!"; sshd refuses key logins for locked
|
||||
# accounts, so the password field is set to "*" (no password, not locked).
|
||||
|
||||
Reference in new issue
Block a user