Files
ssh-netbox-wrapper/cmd/netssh/insights.go
T
Sebastian UnterschützandClaude Opus 5.5 793f095e80 feat: suggest the host behind unknown DNS names
A name neither in NetBox nor in the cache is resolved through DNS, using
dns.domains for short names. The hosts owning the address in NetBox or the
cache are offered together with a direct connection; without a terminal the
suggestions are part of the error. Afterwards netssh offers to save the name
as a link. info, open and whois use the same lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:08 +01:00

438 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// hostCompletion completes cached hostnames for commands taking hosts.
func hostCompletion(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
return completeHosts(toComplete), cobra.ShellCompDirectiveNoFileComp
}
// netboxHost finds the NetBox record of a host given like on the command line
// (shortcut, instance/host). The cache supplies the ID when it has one.
func netboxHost(ctx context.Context, cfg *config.Config, target string) (netbox.HostEntry, *netbox.Client, resolvedHost, error) {
h, err := resolveOrSuggest(cfg, target, false)
if err != nil {
return netbox.HostEntry{}, nil, h, err
}
switch h.Kind {
case config.StaticKind:
return netbox.HostEntry{}, nil, h, fmt.Errorf("%s is a static host (hosts:) and has no NetBox record", h.Name)
case "dns":
return netbox.HostEntry{}, nil, h, fmt.Errorf("%s (%s) is not in NetBox", h.Name, h.IP)
}
client := newNetBoxClient(cfg)
if client == nil {
return netbox.HostEntry{}, nil, h, fmt.Errorf("no NetBox is configured (netssh configure)")
}
return netboxEntry(ctx, client, h.Name, h.Kind, h.ID, h)
}
// netboxEntry completes a cached host with its NetBox ID, looking it up if needed.
func netboxEntry(ctx context.Context, client *netbox.Client, name, kind string, id int, h resolvedHost) (netbox.HostEntry, *netbox.Client, resolvedHost, error) {
source, bare := netbox.SplitTarget(name)
entry := netbox.HostEntry{Source: source, Name: bare, Kind: kind, ID: id}
if id <= 0 {
found, err := client.FindHost(ctx, name, kind)
if err != nil {
return entry, client, h, fmt.Errorf("NetBox: %w", err)
}
entry = found
}
return entry, client, h, nil
}
// openBrowser opens url with $BROWSER, open (macOS), or xdg-open.
var openBrowser = func(url string) error {
var cmd *exec.Cmd
switch browser := os.Getenv("BROWSER"); {
case browser != "":
cmd = exec.Command(browser, url)
case runtime.GOOS == "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
cmd.Stdout, cmd.Stderr = nil, nil
if err := cmd.Start(); err != nil {
return fmt.Errorf("opening browser: %w (print the URL with --print)", err)
}
return cmd.Process.Release()
}
func openCmd() *cobra.Command {
var printOnly bool
cmd := &cobra.Command{
Use: "open HOST",
Short: "Open the NetBox page of a host in the web browser",
Long: "Open the device or virtual machine page in the NetBox web interface.\nThe browser is $BROWSER, else open (macOS) or xdg-open.",
Args: cobra.ExactArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
entry, client, _, err := netboxHost(ctx, cfg, args[0])
if err != nil {
return err
}
url, err := client.WebURL(entry)
if err != nil {
return err
}
if printOnly {
fmt.Fprintln(cmd.OutOrStdout(), url)
return nil
}
fmt.Fprintf(os.Stderr, "Opening %s\n", url)
return openBrowser(url)
},
}
cmd.Flags().BoolVar(&printOnly, "print", false, "Print the URL instead of opening it")
return cmd
}
func infoCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "info HOST",
Short: "Show site, rack, role, platform, status and IP addresses of a host",
Args: cobra.ExactArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveOrSuggest(cfg, args[0], false)
if err != nil {
return err
}
out := cmd.OutOrStdout()
if h.Kind == config.StaticKind || h.Kind == "dns" {
return printStaticInfo(out, cfg, h, asJSON)
}
client := newNetBoxClient(cfg)
if client == nil {
return fmt.Errorf("no NetBox is configured (netssh configure)")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
entry, _, _, err := netboxEntry(ctx, client, h.Name, h.Kind, h.ID, h)
if err != nil {
return err
}
details, err := client.GetDetails(ctx, entry)
if err != nil && details.Name == "" {
return fmt.Errorf("NetBox: %w", err)
}
if asJSON {
return json.NewEncoder(out).Encode(map[string]any{"host": details, "connect": map[string]any{"address": h.IP, "source": h.Origin, "resolver": h.Resolver}})
}
writeDetails(out, details, h)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: %v\n", err)
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "Print JSON")
return cmd
}
func printStaticInfo(w io.Writer, cfg *config.Config, h resolvedHost, asJSON bool) error {
user, port := hostDefaults(cfg, h)
if asJSON {
return json.NewEncoder(w).Encode(map[string]any{"host": map[string]any{"name": h.Name, "kind": h.Kind, "address": h.IP, "user": user, "port": port, "tags": h.Tags}})
}
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
origin := "(static host from hosts:)"
if h.Kind == "dns" {
origin = "(DNS name, not in NetBox)"
}
fmt.Fprintf(tw, "%s\t%s\n", h.Name, origin)
row(tw, "Address", h.IP)
row(tw, "User", user)
if port > 0 {
row(tw, "Port", fmt.Sprint(port))
}
row(tw, "Tags", strings.Join(h.Tags, ", "))
return tw.Flush()
}
func row(w io.Writer, label, value string) {
if strings.TrimSpace(value) != "" {
fmt.Fprintf(w, " %s\t%s\n", label, value)
}
}
// formatDetails renders netssh info output; the TUI detail view uses it too.
func formatDetails(d netbox.HostDetails, h resolvedHost) string {
var b strings.Builder
writeDetails(&b, d, h)
return b.String()
}
func writeDetails(w io.Writer, d netbox.HostDetails, h resolvedHost) {
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
header := d.Target() + "\t(" + d.Kind
if d.Source != "" {
header += ", NetBox " + d.Source
}
fmt.Fprintln(tw, header+")")
status := d.StatusLabel
if status == "" {
status = d.Status
}
row(tw, "Status", status)
row(tw, "Site", d.Site.Name)
var locations []string
for _, location := range d.Location {
locations = append(locations, location.Name)
}
row(tw, "Location", strings.Join(locations, " › "))
row(tw, "Rack", strings.TrimSpace(d.Rack+" "+d.RackUnits()))
if len(d.Location) > 0 || d.Rack != "" {
row(tw, "Path", d.LocationPath())
}
row(tw, "Role", d.Role.Name)
row(tw, "Platform", d.Platform.Name)
row(tw, "Tenant", d.Tenant.Name)
row(tw, "Type", d.DeviceType)
row(tw, "Serial", d.Serial)
row(tw, "Asset tag", d.AssetTag)
row(tw, "Cluster", d.Cluster)
var resources []string
if d.VCPUs != "" {
resources = append(resources, d.VCPUs+" vCPU")
}
if d.MemoryMB > 0 {
resources = append(resources, fmt.Sprintf("%d MB RAM", d.MemoryMB))
}
if d.DiskGB > 0 {
resources = append(resources, fmt.Sprintf("%d GB disk", d.DiskGB))
}
row(tw, "Resources", strings.Join(resources, ", "))
row(tw, "Tags", strings.Join(d.Tags, ", "))
if h.IP != "" {
via := h.Resolver
if h.Origin != "" {
via = strings.Trim(via+", "+h.Origin, ", ")
}
connect := h.IP
if via != "" {
connect += " (" + via + ")"
}
row(tw, "Connect", connect)
}
row(tw, "URL", d.URL)
row(tw, "Description", d.Description)
_ = tw.Flush()
if len(d.IPs) == 0 {
return
}
fmt.Fprintln(w, "\nIP addresses")
tw = tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
for _, ip := range d.IPs {
mark := " "
if ip.Primary {
mark = "*"
}
extra := ip.Status
if ip.Role != "" {
extra = strings.Trim(extra+", "+ip.Role, ", ")
}
if ip.VRF != "" {
extra = strings.Trim(extra+", vrf "+ip.VRF, ", ")
}
fmt.Fprintf(tw, " %s %s\t%s\t%s\t%s\n", mark, ip.Address, orDash(ip.Interface), ip.DNSName, extra)
}
_ = tw.Flush()
}
// whoisResult is what netssh whois found for one address.
type whoisResult struct {
Address string `json:"address"`
NetBox []netbox.IPOwner `json:"netbox"`
Prefixes []netbox.PrefixInfo `json:"prefixes"`
Cached []string `json:"cached_hosts"`
}
func whoisCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "whois ADDRESS|HOSTNAME",
Short: "Find the host, interface and prefix an IP address belongs to",
Long: `Look an IP address up in every NetBox instance and in the local cache:
the device or VM and interface it is assigned to, its DNS name, and the
prefixes containing it. A hostname is resolved through DNS first.`,
Example: " netssh whois 10.20.0.15\n netssh whois mail.example.com",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
addresses, err := whoisAddresses(ctx, args[0])
if err != nil {
// A short name like mx123 may resolve with a shortcut domain.
if names := dnsNames(cfg, args[0]); len(names) > 0 && names[0] != args[0] {
if _, found := lookupDNS(ctx, names); len(found) > 0 {
addresses, err = found, nil
}
}
}
if err != nil {
return err
}
c := newCache(cfg)
_ = c.Load()
var client *netbox.Client
if cfg.HasNetBox() {
client = newNetBoxClient(cfg)
}
var results []whoisResult
var warnings []error
found := false
for _, address := range addresses {
r := whoisResult{Address: address}
for _, e := range c.All() {
if e.IP == address {
r.Cached = append(r.Cached, e.Name)
}
}
sort.Strings(r.Cached)
if client != nil {
owners, err := client.LookupIP(ctx, address)
if err != nil {
warnings = append(warnings, err)
}
r.NetBox = owners
prefixes, err := client.PrefixesContaining(ctx, address)
if err != nil {
warnings = append(warnings, err)
}
r.Prefixes = prefixes
}
found = found || len(r.NetBox) > 0 || len(r.Cached) > 0 || len(r.Prefixes) > 0
results = append(results, r)
}
for _, warning := range warnings {
fmt.Fprintf(os.Stderr, "warning: %v\n", warning)
}
out := cmd.OutOrStdout()
if asJSON {
return json.NewEncoder(out).Encode(results)
}
writeWhois(out, results)
if !found {
cmd.SilenceErrors, cmd.SilenceUsage = true, true
return &commandExit{code: 1}
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "Print JSON")
return cmd
}
// lookupHost is replaced in tests.
var lookupHost = net.DefaultResolver.LookupHost
func whoisAddresses(ctx context.Context, query string) ([]string, error) {
query = strings.TrimSpace(query)
if ip := net.ParseIP(query); ip != nil {
return []string{ip.String()}, nil
}
if _, network, err := net.ParseCIDR(query); err == nil {
return []string{network.IP.String()}, nil
}
addresses, err := lookupHost(ctx, query)
if err != nil {
return nil, fmt.Errorf("%q is no IP address and cannot be resolved: %w", query, err)
}
if len(addresses) == 0 {
return nil, errors.New("no addresses found")
}
return addresses, nil
}
func writeWhois(w io.Writer, results []whoisResult) {
for i, r := range results {
if i > 0 {
fmt.Fprintln(w)
}
fmt.Fprintln(w, r.Address)
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
if len(r.NetBox) == 0 && len(r.Cached) == 0 && len(r.Prefixes) == 0 {
fmt.Fprintln(tw, " not found in NetBox or the cache")
}
for _, o := range r.NetBox {
owner := "unassigned"
if o.Target() != "" {
owner = o.Target() + " (" + o.HostKind + ")"
if o.Interface != "" {
owner += " " + o.Interface
}
}
var extra []string
if o.Status != "" {
extra = append(extra, o.Status)
}
if o.VRF != "" {
extra = append(extra, "vrf "+o.VRF)
}
if o.DNSName != "" {
extra = append(extra, "dns "+o.DNSName)
}
if o.Description != "" {
extra = append(extra, fmt.Sprintf("%q", o.Description))
}
fmt.Fprintf(tw, " IP\t%s\t%s\t%s\n", o.Address, owner, strings.Join(extra, " "))
}
for _, p := range r.Prefixes {
var extra []string
for _, pair := range [][2]string{{"", p.Status}, {"site ", p.Site}, {"role ", p.Role}, {"vlan ", p.VLAN}, {"vrf ", p.VRF}} {
if pair[1] != "" {
extra = append(extra, pair[0]+pair[1])
}
}
if p.Description != "" {
extra = append(extra, fmt.Sprintf("%q", p.Description))
}
prefix := p.Prefix
if p.Source != "" {
prefix += " (" + p.Source + ")"
}
fmt.Fprintf(tw, " Prefix\t%s\t%s\n", prefix, strings.Join(extra, " "))
}
for _, name := range r.Cached {
fmt.Fprintf(tw, " Cache\t%s\n", name)
}
_ = tw.Flush()
}
}