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>
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-18 12:33:59 +01:00
1 parent e5bde9c61f
commit 1660bb3098
39 files changed
+4868 -96

No files matched your search

+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
}