feat: add pre_connect hook and optional shortcut alias display
- ssh.pre_connect: local shell command run before every connection, layered like proxy_jump (global, instance/static host, rules; "none" disables). Host details are passed as NETSSH_* env vars, a non-zero exit aborts the connection, --dry-run only prints it. - shortcuts.show: show shortcut aliases in the TUI host list, an ALIAS column in `cache list` / `hosts list` (also via --aliases) and in Tab completion. - Both editable in `netssh configure`; README and CHANGELOG updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAuVpPncumMViLLc8N4
This commit is contained in:
1 parent
3804c33669
commit
419c682a71
15 files changed
+507
-23
No files matched your search
+26
-5
@@ -14,27 +14,32 @@ import (
|
||||
)
|
||||
|
||||
func hostsCmd() *cobra.Command {
|
||||
var showAliases bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "hosts",
|
||||
Short: "Manage static hosts that are not in NetBox",
|
||||
Long: `Static hosts are defined under hosts: in the config. They are found before
|
||||
NetBox, work offline, and support shortcuts, rules (kind: static), aliases,
|
||||
completion, sftp, scp, and tunnels like NetBox hosts.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error { return listHosts() },
|
||||
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
|
||||
}
|
||||
cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd())
|
||||
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func hostsListCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
var showAliases bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List static hosts",
|
||||
RunE: func(cmd *cobra.Command, args []string) error { return listHosts() },
|
||||
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
|
||||
}
|
||||
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func listHosts() error {
|
||||
func listHosts(showAliases bool) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -43,13 +48,29 @@ func listHosts() error {
|
||||
fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS")
|
||||
return nil
|
||||
}
|
||||
withAliases := showAliases || cfg.Shortcuts.Show
|
||||
var aliases map[string]string
|
||||
if withAliases {
|
||||
// Aliases are unique across all hosts, so compute them with the cache.
|
||||
c := newCache(cfg)
|
||||
_ = c.Load()
|
||||
aliases = shortcutAliases(c.All(), *cfg)
|
||||
}
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
|
||||
if withAliases {
|
||||
fmt.Fprintln(w, "NAME\tALIAS\tADDRESS\tUSER\tPORT\tTAGS")
|
||||
} else {
|
||||
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
|
||||
}
|
||||
for _, host := range cfg.Hosts {
|
||||
port := ""
|
||||
if host.Port > 0 {
|
||||
port = fmt.Sprint(host.Port)
|
||||
}
|
||||
if withAliases {
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", host.Name, orDash(aliases[strings.ToLower(host.Name)]), host.Address, host.User, port, strings.Join(host.Tags, ","))
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", host.Name, host.Address, host.User, port, strings.Join(host.Tags, ","))
|
||||
}
|
||||
return w.Flush()
|
||||
|
||||
+40
-1
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts"
|
||||
)
|
||||
@@ -29,6 +30,28 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
|
||||
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion)
|
||||
}
|
||||
|
||||
// shortcutAliases maps each target (lowercased) to the shell alias generated for
|
||||
// it, but only where shortcuts actually shorten the displayed name: an alias that
|
||||
// merely replaces dots with underscores ("web01_example_com") adds nothing.
|
||||
// The aliases are the same ones netssh alias and the shell hook define.
|
||||
func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string {
|
||||
out := make(map[string]string)
|
||||
if !cfg.Shortcuts.Enabled() {
|
||||
return out
|
||||
}
|
||||
plain := strings.NewReplacer(".", "_", "/", "_")
|
||||
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
|
||||
if alias.Host == "" {
|
||||
continue // the command alias for netssh itself
|
||||
}
|
||||
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
|
||||
continue
|
||||
}
|
||||
out[strings.ToLower(alias.Host)] = alias.Name
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) string {
|
||||
return func(target string) string {
|
||||
source, name := netbox.SplitTarget(target)
|
||||
@@ -48,6 +71,9 @@ func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) st
|
||||
// Names present in several instances stay qualified ("prod/web01").
|
||||
// Hosts whose full name does not match are offered by their configured
|
||||
// shortcut instead ("fsnb" → "fsnbx1" for fsn1-bx1.example.com).
|
||||
//
|
||||
// With shortcuts.show, shortcuts are also offered for hosts whose full name
|
||||
// matches, so "fsn" lists both fsn1-bx1.example.com and fsnbx1.
|
||||
func hostCompletions(entries []cache.Entry, toComplete string, sc config.ShortcutsConfig) []string {
|
||||
prefix := strings.ToLower(toComplete)
|
||||
qualifiedInput := strings.Contains(prefix, "/")
|
||||
@@ -75,7 +101,20 @@ func hostCompletions(entries []cache.Entry, toComplete string, sc config.Shortcu
|
||||
}
|
||||
}
|
||||
if sc.Enabled() {
|
||||
names = append(names, shortcutCompletions(entries, unmatched, prefix, sc)...)
|
||||
candidates := unmatched
|
||||
if sc.Show {
|
||||
candidates = entries
|
||||
}
|
||||
offered := make(map[string]bool, len(names))
|
||||
for _, name := range names {
|
||||
offered[strings.ToLower(name)] = true
|
||||
}
|
||||
for _, name := range shortcutCompletions(entries, candidates, prefix, sc) {
|
||||
if !offered[name] {
|
||||
offered[name] = true
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
|
||||
+29
-3
@@ -348,6 +348,9 @@ func connectHost(cfg *config.Config, client internalssh.Client, flags internalss
|
||||
}
|
||||
fatalf("name a forward or a spec such as 8080:localhost:80; forwards for %s: %s", host.Name, available)
|
||||
}
|
||||
if err := runPreConnect(opts.PreConnectCommand(), host, client.Name, flags.DryRun); err != nil {
|
||||
fatalf("%v", err)
|
||||
}
|
||||
_, name := netbox.SplitTarget(host.Name)
|
||||
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags)
|
||||
}
|
||||
@@ -387,6 +390,10 @@ func runTUI() {
|
||||
|
||||
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
|
||||
m.SetHostLabel(cfg.HostLabel)
|
||||
if cfg.Shortcuts.Show {
|
||||
aliases := shortcutAliases(c.All(), *cfg)
|
||||
m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] })
|
||||
}
|
||||
m.SetNotes(notes.New(cfg.NetBox.URL, nbClient))
|
||||
m.SetForwards(func(name, kind string, tags []string) []string {
|
||||
return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags}))
|
||||
@@ -669,7 +676,8 @@ func cacheCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
func cacheListCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
var showAliases bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "Show all cached entries",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
@@ -685,13 +693,31 @@ func cacheListCmd() *cobra.Command {
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT")
|
||||
if !showAliases && !cfg.Shortcuts.Show {
|
||||
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT")
|
||||
for _, e := range entries {
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
|
||||
}
|
||||
return w.Flush()
|
||||
}
|
||||
aliases := shortcutAliases(entries, *cfg)
|
||||
fmt.Fprintln(w, "NAME\tALIAS\tIP\tKIND\tCACHED AT")
|
||||
for _, e := range entries {
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", e.Name, orDash(aliases[strings.ToLower(e.Name)]), e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
|
||||
}
|
||||
return w.Flush()
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// orDash keeps empty table cells visible.
|
||||
func orDash(s string) string {
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func cacheClearCmd() *cobra.Command {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
// preConnectRunner runs the hook; tests replace it to avoid spawning a shell.
|
||||
var preConnectRunner = runPreConnectCommand
|
||||
|
||||
// preConnectEnv describes the host to the hook through environment variables.
|
||||
func preConnectEnv(host resolvedHost, clientName string) []string {
|
||||
instance, name := netbox.SplitTarget(host.Name)
|
||||
return []string{
|
||||
"NETSSH_HOST=" + name,
|
||||
"NETSSH_TARGET=" + host.Name,
|
||||
"NETSSH_INSTANCE=" + instance,
|
||||
"NETSSH_IP=" + host.IP,
|
||||
"NETSSH_KIND=" + host.Kind,
|
||||
"NETSSH_TAGS=" + strings.Join(host.Tags, ","),
|
||||
"NETSSH_CLIENT=" + clientName,
|
||||
}
|
||||
}
|
||||
|
||||
// runPreConnect runs the configured pre_connect hook for host. Its output goes
|
||||
// to stderr so it never mixes with the output of a remote command or scp.
|
||||
// A failing hook returns an error and the connection must not be opened.
|
||||
func runPreConnect(command string, host resolvedHost, clientName string, dryRun bool) error {
|
||||
if command == "" {
|
||||
return nil
|
||||
}
|
||||
if dryRun {
|
||||
fmt.Fprintf(os.Stderr, "# pre_connect (skipped in --dry-run): %s\n", command)
|
||||
return nil
|
||||
}
|
||||
if err := preConnectRunner(command, preConnectEnv(host, clientName), os.Stdin, os.Stderr); err != nil {
|
||||
return fmt.Errorf("pre_connect hook for %s failed: %w", host.Name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runPreConnectCommand(command string, env []string, stdin io.Reader, out io.Writer) error {
|
||||
cmd := exec.Command("sh", "-c", command)
|
||||
cmd.Env = append(os.Environ(), env...)
|
||||
cmd.Stdin = stdin
|
||||
cmd.Stdout = out
|
||||
cmd.Stderr = out
|
||||
return cmd.Run()
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
|
||||
)
|
||||
|
||||
func TestRunPreConnectPassesHostAndStopsOnFailure(t *testing.T) {
|
||||
host := resolvedHost{Name: "prod/web01", Kind: "vm", IP: "10.0.0.5", Tags: []string{"dmz", "web"}}
|
||||
var gotCommand string
|
||||
var gotEnv []string
|
||||
fail := false
|
||||
preConnectRunner = func(command string, env []string, _ io.Reader, _ io.Writer) error {
|
||||
gotCommand, gotEnv = command, env
|
||||
if fail {
|
||||
return errors.New("exit status 1")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
|
||||
|
||||
if err := runPreConnect("vpn-check", host, "sftp", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"NETSSH_HOST=web01", "NETSSH_TARGET=prod/web01", "NETSSH_INSTANCE=prod", "NETSSH_IP=10.0.0.5", "NETSSH_KIND=vm", "NETSSH_TAGS=dmz,web", "NETSSH_CLIENT=sftp"}
|
||||
if gotCommand != "vpn-check" || !reflect.DeepEqual(gotEnv, want) {
|
||||
t.Fatalf("got %q %v", gotCommand, gotEnv)
|
||||
}
|
||||
|
||||
fail = true
|
||||
if err := runPreConnect("vpn-check", host, "ssh", false); err == nil || !strings.Contains(err.Error(), "prod/web01") {
|
||||
t.Fatalf("failure not reported: %v", err)
|
||||
}
|
||||
|
||||
gotCommand = ""
|
||||
if err := runPreConnect("vpn-check", host, "ssh", true); err != nil || gotCommand != "" {
|
||||
t.Fatalf("dry-run ran the hook: %v %q", err, gotCommand)
|
||||
}
|
||||
if err := runPreConnect("", host, "ssh", false); err != nil || gotCommand != "" {
|
||||
t.Fatalf("empty hook ran: %v %q", err, gotCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunPreConnectCommandUsesShell(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
err := runPreConnectCommand(`echo "$NETSSH_HOST via $NETSSH_CLIENT"`, []string{"NETSSH_HOST=web01", "NETSSH_CLIENT=ssh"}, strings.NewReader(""), &out)
|
||||
if err != nil || out.String() != "web01 via ssh\n" {
|
||||
t.Fatalf("got %q, %v", out.String(), err)
|
||||
}
|
||||
if err := runPreConnectCommand("exit 3", nil, strings.NewReader(""), io.Discard); err == nil {
|
||||
t.Fatal("non-zero exit not reported")
|
||||
}
|
||||
}
|
||||
|
||||
// --dry-run only prints the ssh command: it must not run the hook, which may
|
||||
// have side effects (bringing up a VPN, logging).
|
||||
func TestConnectHostDryRunSkipsPreConnect(t *testing.T) {
|
||||
ran := 0
|
||||
preConnectRunner = func(string, []string, io.Reader, io.Writer) error { ran++; return nil }
|
||||
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
|
||||
cfg := &config.Config{SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PreConnect: "hook"}}}
|
||||
stdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
connectHost(cfg, internalssh.SSH, internalssh.WrapperFlags{DryRun: true}, resolvedHost{Name: "web01", IP: "10.0.0.1"}, []int{0}, []string{"web01"})
|
||||
w.Close()
|
||||
os.Stdout = stdout
|
||||
printed, _ := io.ReadAll(r)
|
||||
if ran != 0 || !strings.Contains(string(printed), "10.0.0.1") {
|
||||
t.Fatalf("dry-run: ran=%d printed=%q", ran, printed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortcutAliasesOnlyWhenShortened(t *testing.T) {
|
||||
cfg := config.Config{Shell: config.ShellConfig{Alias: "j"}, Shortcuts: fsnRewrite}
|
||||
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "web01.other.de"}, {Name: "db01.hoster.de"}}
|
||||
got := shortcutAliases(entries, cfg)
|
||||
want := map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "db01.hoster.de": "db01"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
if got := shortcutAliases(entries, config.Config{}); len(got) != 0 {
|
||||
t.Fatalf("aliases without shortcuts: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostCompletionsShowShortcutsForMatchingNames(t *testing.T) {
|
||||
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "fsn1-db1.hoster.de"}}
|
||||
if got := hostCompletions(entries, "fsn", fsnRewrite); !reflect.DeepEqual(got, []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de"}) {
|
||||
t.Fatalf("without show: %v", got)
|
||||
}
|
||||
show := fsnRewrite
|
||||
show.Show = true
|
||||
want := []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de", "fsnbx1", "fsndb1"}
|
||||
if got := hostCompletions(entries, "fsn", show); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("with show: got %v, want %v", got, want)
|
||||
}
|
||||
// A shortcut equal to an offered name is not repeated.
|
||||
plain := []cache.Entry{{Name: "web01"}}
|
||||
if got := hostCompletions(plain, "web", show); !reflect.DeepEqual(got, []string{"web01"}) {
|
||||
t.Fatalf("duplicate: %v", got)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user