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

+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
}
+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, "/")
}
+422
View File
@@ -0,0 +1,422 @@
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 := resolveTargetE(cfg, target, false)
if err != nil {
return netbox.HostEntry{}, nil, h, err
}
if h.Kind == config.StaticKind {
return netbox.HostEntry{}, nil, h, fmt.Errorf("%s is a static host (hosts:) and has no NetBox record", h.Name)
}
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 := resolveTargetE(cfg, args[0], false)
if err != nil {
return err
}
out := cmd.OutOrStdout()
if h.Kind == config.StaticKind {
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)
fmt.Fprintf(tw, "%s\t(static host from hosts:)\n", h.Name)
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 {
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)
}
}
}
+4 -2
View File
@@ -20,14 +20,16 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
if len(cfg.NetBoxes) > 0 {
sources := make([]netbox.Source, 0, len(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)
}
if cfg.NetBox.URL == "" {
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
+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
}
+119 -34
View File
@@ -32,25 +32,32 @@ import (
// managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode.
var managedSubcommands = map[string]bool{
"doctor": true, "explain": true, "favorites": true, "history": true, "batch": true, "config": true,
"configure": true,
"notes": true,
"search": true,
"cache": true,
"alias": true,
"hook": true,
"shell-init": true,
"completion": true,
"__complete": true,
"help": true,
"version": true,
"uninstall": true,
"sftp": true,
"scp": true,
"tunnel": true,
"hosts": true,
"multi": true,
"sync": true,
"run": true,
"configure": true,
"notes": true,
"search": true,
"cache": true,
"alias": true,
"hook": true,
"shell-init": true,
"completion": true,
"__complete": true,
"help": true,
"version": true,
"uninstall": true,
"sftp": true,
"scp": true,
"tunnel": true,
"hosts": true,
"multi": true,
"sync": true,
"run": true,
"open": true,
"info": true,
"whois": true,
"copy-id": true,
"export": true,
"token": true,
"known-hosts": true,
}
func main() {
@@ -221,6 +228,49 @@ type resolvedHost struct {
Kind string
IP 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
@@ -250,7 +300,7 @@ func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost,
if entry.Static {
origin = "static"
}
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags, Origin: origin, Resolver: entry.Resolver, CachedAt: entry.CachedAt}
return hostFromEntry(entry, origin)
}
// Static hosts from the config win and need no NetBox.
@@ -328,10 +378,11 @@ func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost,
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, Resolver: strategy}
c.Upsert(entry)
entry := cacheEntry(target, ip, strategy)
previous := upsertResolved(c, entry)
result := used(entry)
result.Origin = "live"
result.PreviousIP = previous
return result, nil
}
@@ -375,6 +426,20 @@ 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 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 {
fatalf("%v", err)
}
@@ -401,8 +466,7 @@ func connectHost(cfg *config.Config, client internalssh.Client, flags internalss
// hostOptions merges the global, instance, and rule SSH options for host.
func hostOptions(cfg *config.Config, host resolvedHost) config.SSHOptions {
instance, name := netbox.SplitTarget(host.Name)
return cfg.SSHOptionsFor(config.SSHHost{Instance: instance, Name: name, Kind: host.Kind, Tags: host.Tags})
return cfg.SSHOptionsFor(commandHost(host))
}
// execClient replaces the process with the client, or prints the command for --dry-run.
@@ -466,9 +530,15 @@ func runTUI() {
}
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(resolvedHost{Name: name, Kind: kind, Tags: tags})
h := commandHost(known(name, kind, tags))
for name, c := range cfg.Commands {
if c.Allowed(h) {
names = append(names, name)
@@ -483,8 +553,9 @@ func runTUI() {
}
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}))
return forwardNames(hostOptions(cfg, known(name, kind, tags)))
})
configureTUIExtras(m, cfg, nbClient, known)
p := tea.NewProgram(m)
final, err := p.Run()
if err != nil {
@@ -523,10 +594,9 @@ func runTUI() {
}
// 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 {
host.IP = cached.IP
tags = cached.Tags
resolved = hostFromEntry(cached, "cache")
} else {
if nbClient == nil {
fatalf("cannot resolve %q: NetBox is not configured", host.Name)
@@ -546,16 +616,19 @@ func runTUI() {
if err != nil {
fatalf("IP resolution: %v", err)
}
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy})
tags = target.Tags
entry := cacheEntry(target, host.IP, strategy)
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)
c.MarkUsed(host.Name)
_ = c.Save()
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.
@@ -632,7 +705,8 @@ func rootCmd() *cobra.Command {
},
}
root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), 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())
// cobra builds the "completion" command lazily; force init so we can extend it.
root.InitDefaultCompletionCmd()
@@ -883,6 +957,7 @@ func cacheRefreshCmd() *cobra.Command {
return fmt.Errorf("resolver: %w", err)
}
written := 0
var changed []string
nameCounts := make(map[string]int)
for _, e := range entries {
nameCounts[strings.ToLower(e.Target())]++
@@ -906,7 +981,9 @@ func cacheRefreshCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err)
continue
}
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Resolver: strategy})
if previous := upsertResolved(c, cacheEntry(*e, ip, strategy)); previous != "" {
changed = append(changed, fmt.Sprintf("%s: %s → %s", e.Target(), previous, ip))
}
written++
}
@@ -924,6 +1001,14 @@ func cacheRefreshCmd() *cobra.Command {
}
}
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
},
}
+9 -1
View File
@@ -60,6 +60,12 @@ func doctorCmd() *cobra.Command {
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 != "" {
@@ -67,7 +73,8 @@ func doctorCmd() *cobra.Command {
}
for _, s := range sources {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := netbox.NewClient(s.URL, s.Token, s.TokenVersion).Search(ctx, "", netbox.SearchOptions{})
token, version := clientToken(s)
_, err := netbox.NewClient(s.URL, token, version).Search(ctx, "", netbox.SearchOptions{})
cancel()
report("NetBox "+s.Name, err)
}
@@ -109,6 +116,7 @@ func explainCmd() *cobra.Command {
}
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,
})
}}
+1 -1
View File
@@ -19,7 +19,7 @@ import (
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}
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 {
+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)"
}
}
+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
})
}