diff --git a/README.de.md b/README.de.md index 0e2a25b..e27e0ae 100644 --- a/README.de.md +++ b/README.de.md @@ -40,7 +40,15 @@ sshTermy ist eine schlanke Terminal-Anwendung (TUI, eine einzige Datei, ~9 MB, k - **Server-Datei im eigenen Editor**: `e` in F5 (Server-Seite) oder Palette „Server-Datei im eigenen Editor öffnen“ mit Pfad öffnet die Datei in VS Code, Notepad++, TextEdit … auf deinem Rechner; jedes Speichern lädt sie über dieselbe Verbindung zurück (Besitzer und Rechte bleiben). Editor einstellen: Palette → Einstellungen › „Editor für Server-Dateien“ (z. B. `code --new-window`) - **Farbregeln für die Ausgabe**: Text ohne eigene Farbe wird eingefärbt, Fehler rot, Warnungen gelb, ok/up grün, IP-Adressen blau, MAC-Adressen lila, Switch-Syslog (`%LINK-3-UPDOWN`) nach Schwere; nie in vim/htop. Eigene Regeln „farbe muster“ (Palette → „Farbregeln für die Ausgabe“); mit `!` davor meldet sich sshTermy, wenn das Muster in einem verdeckten Tab auftaucht (Tab bekommt ein `!`, Einblendung, auf Wunsch Desktop-Meldung) - **Host-Übersicht (F6)**: Server zeigen beim Verbinden CPU, Last, RAM, Platte, Laufzeit und offene Updates. Switches (ArubaOS-Switch/ProCurve, ArubaOS-CX, Cisco IOS) zeigen auf Abruf Firmware, Ports und VLANs; die show-Befehle laufen sichtbar am Prompt, nie als versteckte Exec-Sitzung -- **Config-Sicherung für Switches**: `b` sichert `show running-config` verschlüsselt auf dem Rechner, `d` zeigt den Diff zum vorherigen Stand, unveränderte Stände werden nicht doppelt gespeichert +- **Config-Sicherung für Switches**: `b` sichert `show running-config` verschlüsselt auf dem Rechner, `d` zeigt den Diff zum vorherigen Stand, unveränderte Stände werden nicht doppelt gespeichert. + Nächtlich geht es per Zeitplan (`z`, Art „Config-Sicherung“) für einen ganzen Ordner. **Regeln für Switch-Configs** + (Palette → Einstellungen): `+^ntp server` muss vorkommen, `-telnet-server` darf nicht; jede Sicherung wird geprüft, + Verstöße stehen im F6-Panel, als Einblendung und im Ergebnis des Zeitplans +- **Gerät finden**: MAC (jede Schreibweise) oder IP in die Palette tippen, sshTermy fragt alle Switches nach MAC-, + ARP- und LLDP-Tabellen und zeigt Switch, Port und VLAN, an dem das Gerät hängt. Uplinks erkennt es an den + LLDP-Nachbarn und lässt sie hinten anstehen +- **Netzwerk-Topologie** (Palette „topo“): aus LLDP/CDP-Nachbarn aller Switches entsteht ein Baum (wer hängt an + welchem Port von wem, APs und Telefone als Blätter), dazu ein Mermaid-Diagramm in Downloads für Doku, Wiki oder GitHub - **Broadcast** (m im Manager): ein Befehl oder Runbook läuft parallel auf einer Gruppe (z. B. alle Aruba-Switches), die Ergebnisse stehen in Spalten nebeneinander. Gefahrenregeln gelten auch hier: Rot braucht zweimal ⏎. Server bekommen jeden Schritt per Exec (mit Exit-Code), Netzwerkgeräte die Befehle in die Shell getippt („-- MORE --“ wird weitergeblättert). diff --git a/README.md b/README.md index 3f00723..26e665e 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,15 @@ sshTermy is a lean terminal application (TUI, a single file, ~9 MB, no installer - **Server file in your own editor**: `e` in F5 (server side) or the palette entry „Open server file in your own editor“ with a path opens the file in VS Code, Notepad++, TextEdit … on your computer; every save uploads it back over the same connection (owner and permissions stay). Choose the editor: palette → Settings › „Editor for server files“ (e.g. `code --new-window`) - **Color rules for output**: text without its own color gets colored, errors red, warnings yellow, ok/up green, IP addresses blue, MAC addresses purple, switch syslog (`%LINK-3-UPDOWN`) by severity; never in vim/htop. Own rules „color pattern“ (palette → „Color rules for output“); with `!` in front sshTermy notifies you when the pattern shows up in a hidden tab (the tab gets a `!`, a toast, a desktop notification if you like) - **Host overview (F6)**: servers show CPU, load, RAM, disk, uptime and pending updates when you connect. Switches (ArubaOS-Switch/ProCurve, ArubaOS-CX, Cisco IOS) show firmware, ports and VLANs on request; the show commands run visibly at the prompt, never as a hidden exec session -- **Config backup for switches**: `b` saves `show running-config` encrypted on your computer, `d` shows the diff to the previous state, unchanged states are not stored twice +- **Config backup for switches**: `b` saves `show running-config` encrypted on your computer, `d` shows the diff to the previous state, unchanged states are not stored twice. + Nightly runs go through a schedule (`z`, type „Config backup“) for a whole folder. **Switch config rules** + (palette → Settings): `+^ntp server` must appear, `-telnet-server` must not; every backup is checked, + violations show in the F6 panel, as a toast and in the schedule result +- **Find device**: type a MAC (any notation) or IP into the palette, sshTermy asks all switches for their MAC, + ARP and LLDP tables and shows the switch, port and VLAN the device is plugged into. Uplinks are recognized + by their LLDP neighbors and listed last +- **Network topology** (palette „topo“): the LLDP/CDP neighbors of all switches become a tree (who is connected to + which port of whom, APs and phones as leaves), plus a Mermaid diagram in Downloads for docs, wiki or GitHub - **Broadcast** (m in the manager): one command or runbook runs in parallel on a group (e.g. all Aruba switches), the results are shown side by side in columns. The danger rules apply here too: red needs ⏎ twice. Servers get every step via exec (with exit code), network devices get the commands typed into their shell („-- MORE --“ is paged automatically). diff --git a/internal/devfake/procurve.go b/internal/devfake/procurve.go index 54750b5..8c8e99a 100644 --- a/internal/devfake/procurve.go +++ b/internal/devfake/procurve.go @@ -233,6 +233,12 @@ func (sw *Switch) run(cmd string) string { fmt.Fprintf(&b, " %-7d %-32s | Port-based No No\n", v, vlanName(v)) } return b.String() + case "show mac-address": + return " Status and Counters - Port Address Table\n\n MAC Address Port VLAN\n ------------- ----- ----\n 001122-aabbcc 4 1\n 941882-000001 25 1\n 941882-000002 25 1\n" + case "show arp": + return " IP ARP table\n\n IP Address MAC Address Type Port\n --------------- ----------------- ------- ----\n 192.168.1.20 001122-aabbcc dynamic 4\n" + case "show lldp info remote-device": + return " LLDP Remote Devices Information\n\n LocalPort | ChassisId PortId PortDescr SysName\n --------- + ------------------------- ------ --------- ----------\n 25 | 94 18 82 00 00 01 1/1/48 1/1/48 core\n" case "show running-config": var b strings.Builder b.WriteString("\nRunning configuration:\n\n; J9773A Configuration Editor; Created on release #YA.16.10.0009\n; Ver #14:01.4f.f8.1d.9b.3f.bf.bb.ef.7c.59.fc.6b.fb.9f.fc.ff.ff.37.ef:05\nhostname \"sw-buero\"\nmodule 1 type j9773a\nsnmp-server community \"public\" unrestricted\noobm\n ip address dhcp-bootp\n exit\n") diff --git a/internal/domain/model.go b/internal/domain/model.go index b049804..abec47e 100644 --- a/internal/domain/model.go +++ b/internal/domain/model.go @@ -518,6 +518,10 @@ type Settings struct { // Schedules: Zeitpläne für Broadcast/Runbooks (nur dieser Rechner). Schedules []Schedule `json:"schedules,omitempty"` + // ConfigRules: Regeln für gesicherte Switch-Configs, eine pro Zeile: + // "+muster" muss vorkommen, "-muster" darf nicht (regulärer Ausdruck). + ConfigRules []string `json:"config_rules,omitempty"` + // Highlight: Farbregeln für die Ausgabe im Terminal (highlight-Paket). Highlight HighlightConfig `json:"highlight,omitempty"` @@ -784,6 +788,7 @@ type Schedule struct { Days []int `json:"days,omitempty"` // 0 = Sonntag … 6; leer = täglich Folder string `json:"folder,omitempty"` Conns []string `json:"conns,omitempty"` + Kind string `json:"kind,omitempty"` // "" = Befehle/Runbook, "backup" = Switch-Configs sichern RunbookID string `json:"runbook_id,omitempty"` Steps []string `json:"steps,omitempty"` // ohne Runbook Off bool `json:"off,omitempty"` @@ -793,6 +798,9 @@ type Schedule struct { LastText string `json:"last_text,omitempty"` // Ergebnis je Host, gekürzt } +// ScheduleBackup: Zeitplan sichert die running-config aller Switches im Ziel. +const ScheduleBackup = "backup" + // ScheduleCatchUp: so lange nach dem Termin wird ein verpasster Lauf nachgeholt. const ScheduleCatchUp = 12 * time.Hour diff --git a/internal/hostinfo/hostinfo_test.go b/internal/hostinfo/hostinfo_test.go index 903b038..ac6abad 100644 --- a/internal/hostinfo/hostinfo_test.go +++ b/internal/hostinfo/hostinfo_test.go @@ -199,3 +199,24 @@ func TestServerScriptRunsLocally(t *testing.T) { } t.Logf("%s\n%s", out, s.Summary()) } + +func TestConfigRules(t *testing.T) { + cfg := "hostname \"sw1\"\nsnmp-server community \"public\" unrestricted\ntelnet-server\nntp server 10.0.0.1\n" + rules := ParseConfigRules([]string{"+^ntp server", "+^logging", "-telnet-server", "-community \"public\"", "", "# Kommentar"}) + if len(rules) != 4 { + t.Fatalf("%d Regeln", len(rules)) + } + v := CheckConfig(cfg, rules) + if len(v) != 3 { + t.Fatalf("%+v", v) + } + if v[0].Text() != "fehlt: ^logging" || v[1].Line != "telnet-server" || !strings.Contains(v[2].Line, "public") { + t.Errorf("%q %q %q", v[0].Text(), v[1].Line, v[2].Line) + } + if _, _, err := ParseConfigRule("ntp"); err == nil { + t.Error("ohne +/- sollte scheitern") + } + if _, _, err := ParseConfigRule("+(("); err == nil { + t.Error("kaputter Ausdruck sollte scheitern") + } +} diff --git a/internal/hostinfo/rules.go b/internal/hostinfo/rules.go new file mode 100644 index 0000000..757bb6f --- /dev/null +++ b/internal/hostinfo/rules.go @@ -0,0 +1,115 @@ +package hostinfo + +import ( + "errors" + "fmt" + "regexp" + "strings" + + "github.com/db9979/sshtermy/internal/i18n" +) + +// Regeln für Switch-Configs +// +// Eine Regel pro Zeile: „+muster“ muss in der Konfiguration vorkommen, +// „-muster“ darf nicht vorkommen. Das Muster ist ein regulärer Ausdruck und +// gilt zeilenweise; Groß/Klein ist egal, solange das Muster keine +// Großbuchstaben enthält. Beispiele: +// +// +^ntp server NTP muss eingetragen sein +// +^logging Syslog-Ziel muss gesetzt sein +// -telnet-server Telnet darf nicht an sein +// -community "public" keine Standard-SNMP-Community + +// ConfigRule: eine geprüfte Regel. +type ConfigRule struct { + Must bool + Pattern string + rx *regexp.Regexp +} + +// String: wieder als „+muster“ / „-muster“. +func (r ConfigRule) String() string { + if r.Must { + return "+" + r.Pattern + } + return "-" + r.Pattern +} + +// ParseConfigRule liest eine Zeile (leer oder # = keine Regel, ok=false). +func ParseConfigRule(line string) (r ConfigRule, ok bool, err error) { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + return r, false, nil + } + switch line[0] { + case '+': + r.Must = true + case '-': + default: + return r, false, errors.New(i18n.T("mit + (muss vorkommen) oder - (darf nicht vorkommen) beginnen")) + } + r.Pattern = strings.TrimSpace(line[1:]) + if r.Pattern == "" { + return r, false, errors.New(i18n.T("Muster fehlt")) + } + expr := r.Pattern + if strings.ToLower(expr) == expr { + expr = "(?i)" + expr + } + r.rx, err = regexp.Compile("(?m)" + expr) + if err != nil { + return r, false, fmt.Errorf(i18n.T("Muster ist kein gültiger regulärer Ausdruck: %v"), err) + } + return r, true, nil +} + +// ParseConfigRules: alle Zeilen, ungültige werden übersprungen. +func ParseConfigRules(lines []string) []ConfigRule { + var out []ConfigRule + for _, l := range lines { + if r, ok, err := ParseConfigRule(l); ok && err == nil { + out = append(out, r) + } + } + return out +} + +// Violation: verletzte Regel, bei „-“ mit der ersten passenden Zeile. +type Violation struct { + Rule ConfigRule + Line string +} + +// Text für Meldungen. +func (v Violation) Text() string { + if v.Rule.Must { + return fmt.Sprintf(i18n.T("fehlt: %s"), v.Rule.Pattern) + } + return fmt.Sprintf(i18n.T("verboten: %s"), strings.TrimSpace(v.Line)) +} + +// CheckConfig prüft eine Konfiguration gegen die Regeln. +func CheckConfig(cfg string, rules []ConfigRule) []Violation { + cfg = strings.ReplaceAll(cfg, "\r", "") + var out []Violation + for _, r := range rules { + if r.rx == nil { + continue + } + loc := r.rx.FindStringIndex(cfg) + switch { + case r.Must && loc == nil: + out = append(out, Violation{Rule: r}) + case !r.Must && loc != nil: + start := strings.LastIndexByte(cfg[:loc[0]], '\n') + 1 + end := strings.IndexByte(cfg[loc[0]:], '\n') + line := cfg[start:] + if end >= 0 { + line = cfg[start : loc[0]+end] + } + out = append(out, Violation{Rule: r, Line: line}) + } + } + return out +} diff --git a/internal/i18n/en_netmap.go b/internal/i18n/en_netmap.go new file mode 100644 index 0000000..a4465b2 --- /dev/null +++ b/internal/i18n/en_netmap.go @@ -0,0 +1,62 @@ +package i18n + +// Texte für Gerät finden, Topologie und Config-Regeln. +var enNetmap = map[string]string{ + " (%d MACs am Port)": " (%d MACs on the port)", + "%d Regeln": "%d rules", + "%s steht in keiner ARP-Tabelle; den Router oder Core-Switch mit in die Suche nehmen": "%s is in no ARP table; add the router or core switch to sshTermy", + "%s steht in keiner MAC-Tabelle (Gerät aus oder länger still?)": "%s is in no MAC table (device off or quiet for a while?)", + "+muster muss vorkommen, -muster darf nicht · regulärer Ausdruck, zeilenweise": "+pattern must appear, -pattern must not · regular expression, per line", + "Abfrage läuft schon …": "Query already running …", + "Befehle oder Runbook": "Commands or runbook", + "Config-Sicherung (Switches)": "Config backup (switches)", + "Config-Sicherung: show running-config je Switch, verschlüsselt gespeichert, mit den Regeln für Switch-Configs geprüft": "Config backup: show running-config per switch, stored encrypted, checked against the switch config rules", + "Das Gerät hängt an %s, Port %s.": "The device is connected to %s, port %s.", + "Diagramm (Mermaid): ": "Diagram (Mermaid): ", + "Diagramm nicht gespeichert: ": "Diagram not saved: ", + "Frage %d Switches ab (show-Befehle) …": "Querying %d switches (show commands) …", + "Gerät finden: ": "Find device: ", + "Gerät finden: MAC/IP → Switch-Port": "Find device: MAC/IP → switch port", + "Gerät finden: MAC/IP → Switch-Port …": "Find device: MAC/IP → switch port …", + "Kein Switch im Ziel (Server werden bei der Config-Sicherung übersprungen)": "No switch in the target (servers are skipped by the config backup)", + "Keine LLDP/CDP-Nachbarn gefunden (LLDP auf den Switches aus?)": "No LLDP/CDP neighbors found (LLDP switched off on the switches?)", + "Keine Switches in sshTermy: Verbindung auf „Netzwerkgerät“ stellen oder einmal verbinden": "No switches in sshTermy: set the connection to “Network device” or connect once", + "MAC (jede Schreibweise) oder IP-Adresse. sshTermy fragt alle Switches nach MAC-, ARP- und LLDP-Tabellen (nur show-Befehle).": "MAC (any notation) or IP address. sshTermy asks all switches for their MAC, ARP and LLDP tables (show commands only).", + "MAC/IP → Switch-Port": "MAC/IP → switch port", + "Muster fehlt": "Pattern missing", + "Muster ist kein gültiger regulärer Ausdruck: %v": "Pattern is not a valid regular expression: %v", + "Netzwerk-Topologie": "Network topology", + "Netzwerk-Topologie (LLDP/CDP)": "Network topology (LLDP/CDP)", + "Netzwerk-Topologie · %d Switches": "Network topology · %d switches", + "Nur auf Uplinks gesehen: der Zugangs-Switch ist nicht in sshTermy oder antwortet nicht.": "Only seen on uplinks: the access switch is not in sshTermy or does not answer.", + "Port": "port", + "Regeln für Switch-Configs": "Switch config rules", + "Regeln für Switch-Configs …": "Switch config rules …", + "Regeln verletzt (%d): ": "Rules violated (%d): ", + "Stand %s · %d Switches abgefragt · neue Abfrage nach 3 Minuten": "As of %s · %d switches queried · new query after 3 minutes", + "Switch-Configs sichern": "Back up switch configs", + "Switch-Port finden": "find switch port", + "„topo“": "“topo”", + "MAC / IP": "MAC / IP", + "Switches": "switches", + "Uplink zu ": "uplink to ", + "erste Sicherung gespeichert": "first backup saved", + "fehlt: %s": "missing: %s", + "gesichert, +%d −%d Zeilen (F6 d zeigt den Diff)": "saved, +%d −%d lines (F6 d shows the diff)", + "hinter ": "behind ", + "kein Netzwerkgerät, übersprungen": "not a network device, skipped", + "keine Verbindungen": "no links", + "mit + (muss vorkommen) oder - (darf nicht vorkommen) beginnen": "start with + (must appear) or - (must not appear)", + "schon oben": "see above", + "unverändert seit ": "unchanged since ", + "verboten: %s": "forbidden: %s", + "z. B. „+^ntp server“, „+^logging“, „-telnet-server“, „-community \"public\"“ · geprüft bei jeder Sicherung (F6 b, Zeitplan)": "e.g. “+^ntp server”, “+^logging”, “-telnet-server”, “-community \"public\"” · checked on every backup (F6 b, schedule)", + "· = Nachbar, der nicht in sshTermy steht (AP, Telefon, fremder Switch)": "· = neighbor that is not in sshTermy (AP, phone, foreign switch)", + "„%s“ ist weder MAC noch IP-Adresse": "“%s” is neither a MAC nor an IP address", +} + +func init() { + for k, v := range enNetmap { + en[k] = v + } +} diff --git a/internal/netmap/analyze.go b/internal/netmap/analyze.go new file mode 100644 index 0000000..396c39b --- /dev/null +++ b/internal/netmap/analyze.go @@ -0,0 +1,303 @@ +package netmap + +import ( + "fmt" + "sort" + "strings" + + "github.com/db9979/sshtermy/internal/i18n" +) + +// Device: was ein Switch geliefert hat. +type Device struct { + Alias string // Name der Verbindung in sshTermy + Host string + Name string // Name aus dem Prompt + MACs []MACEntry + ARP map[string]string + Neigh []Neighbor + Err string +} + +// ParseDevice zerlegt die Shell-Ausgabe eines Switches. +func ParseDevice(alias, host, out string, cmds []string) Device { + sec, name := Sections(out, cmds) + d := Device{Alias: alias, Host: host, Name: name, ARP: map[string]string{}} + for c, text := range sec { + switch { + case strings.Contains(c, "mac"): + d.MACs = append(d.MACs, ParseMACTable(text)...) + case strings.Contains(c, "arp"): + for ip, mac := range ParseARP(text) { + d.ARP[ip] = mac + } + case strings.Contains(c, "lldp") || strings.Contains(c, "cdp"): + d.Neigh = append(d.Neigh, ParseNeighbors(text)...) + } + } + d.Neigh = dedupNeighbors(d.Neigh) + return d +} + +func dedupNeighbors(ns []Neighbor) []Neighbor { + seen := map[string]bool{} + var out []Neighbor + for _, n := range ns { + k := normPort(n.LocalPort) + "|" + ShortName(n.RemoteName) + if seen[k] { + continue + } + seen[k] = true + out = append(out, n) + } + return out +} + +// normPort: „GigabitEthernet1/0/1“, „Gig1/0/1“ und „Gi1/0/1“ sind derselbe Port. +func normPort(p string) string { + p = strings.ToLower(strings.TrimSpace(p)) + i := strings.IndexAny(p, "0123456789") + if i <= 0 { + return p + } + pre := p[:i] + if len(pre) > 2 { + pre = pre[:2] + } + return pre + p[i:] +} + +// names: Namen, unter denen ein Switch bei seinen Nachbarn auftauchen kann. +func (d Device) names() []string { + var out []string + for _, s := range []string{d.Alias, d.Name, d.Host} { + if s = ShortName(s); s != "" { + out = append(out, s) + } + } + return out +} + +// index: Kurzname → Gerät. +func index(devs []Device) map[string]int { + m := map[string]int{} + for i, d := range devs { + for _, n := range d.names() { + if _, ok := m[n]; !ok { + m[n] = i + } + } + } + return m +} + +// ---------------------------------------------------------------- Suche + +// Sighting: ein Switch hat die MAC an einem Port gelernt. +type Sighting struct { + Device string // Alias + Port string + VLAN int + PortMACs int // so viele MACs kennt dieser Port insgesamt + Uplink string // Port führt zu diesem Switch ("" = kein Switch dahinter) + Behind string // Nachbar am Port, der kein Switch in sshTermy ist (AP, Telefon …) +} + +// Located: Ergebnis der Suche. +type Located struct { + MAC string // normiert + IP string + Found []Sighting // Zugangsport zuerst + Edge bool // Found[0] ist sicher der Zugangsport (kein Uplink) +} + +// Locate sucht eine MAC oder IP in den Tabellen aller Switches. +func Locate(devs []Device, query string) (Located, error) { + q := strings.TrimSpace(query) + var r Located + switch { + case NormMAC(q) != "": + r.MAC = NormMAC(q) + case IsIP(q): + r.IP = q + for _, d := range devs { + if m := d.ARP[q]; m != "" { + r.MAC = m + break + } + } + if r.MAC == "" { + return r, fmt.Errorf(i18n.T("%s steht in keiner ARP-Tabelle; den Router oder Core-Switch mit in die Suche nehmen"), q) + } + default: + return r, fmt.Errorf(i18n.T("„%s“ ist weder MAC noch IP-Adresse"), q) + } + if r.IP == "" { + for _, d := range devs { + for ip, m := range d.ARP { + if m == r.MAC { + r.IP = ip + } + } + } + } + idx := index(devs) + for _, d := range devs { + count := map[string]int{} + for _, e := range d.MACs { + count[normPort(e.Port)]++ + } + for _, e := range d.MACs { + if e.MAC != r.MAC { + continue + } + s := Sighting{Device: d.Alias, Port: e.Port, VLAN: e.VLAN, PortMACs: count[normPort(e.Port)]} + for _, n := range d.Neigh { + if normPort(n.LocalPort) != normPort(e.Port) { + continue + } + if j, ok := idx[ShortName(n.RemoteName)]; ok { + s.Uplink = devs[j].Alias + } else if n.RemoteName != "" { + s.Behind = n.RemoteName + } + } + r.Found = append(r.Found, s) + } + } + if len(r.Found) == 0 { + return r, fmt.Errorf(i18n.T("%s steht in keiner MAC-Tabelle (Gerät aus oder länger still?)"), FormatMAC(r.MAC)) + } + sort.SliceStable(r.Found, func(i, j int) bool { + a, b := r.Found[i], r.Found[j] + if (a.Uplink == "") != (b.Uplink == "") { + return a.Uplink == "" + } + return a.PortMACs < b.PortMACs + }) + r.Edge = r.Found[0].Uplink == "" + return r, nil +} + +// ---------------------------------------------------------------- Topologie + +// Link zwischen zwei Geräten. +type Link struct { + A, APort string + B, BPort string + Known bool // B ist ein Switch in sshTermy +} + +// Topology: Verbindungen zwischen den Switches (doppelte Sicht von beiden +// Seiten zusammengefasst) und Nachbarn, die nicht in sshTermy stehen. +func Topology(devs []Device) []Link { + idx := index(devs) + seen := map[string]bool{} + var out []Link + for _, d := range devs { + for _, n := range d.Neigh { + name := n.RemoteName + if name == "" { + continue + } + l := Link{A: d.Alias, APort: n.LocalPort, B: name, BPort: n.RemotePort} + if j, ok := idx[ShortName(name)]; ok { + l.B, l.Known = devs[j].Alias, true + if l.B == l.A { + continue + } + } + k1 := l.A + "|" + normPort(l.APort) + "|" + l.B + k2 := l.B + "|" + normPort(l.BPort) + "|" + l.A + if seen[k1] || (l.Known && seen[k2]) { + continue + } + seen[k1] = true + out = append(out, l) + } + } + return out +} + +// TreeLines: Topologie als eingerückter Baum, beginnend beim Switch mit den +// meisten Verbindungen. +func TreeLines(devs []Device, links []Link) []string { + adj := map[string][]Link{} + deg := map[string]int{} + for _, l := range links { + adj[l.A] = append(adj[l.A], l) + if l.Known { + adj[l.B] = append(adj[l.B], Link{A: l.B, APort: l.BPort, B: l.A, BPort: l.APort, Known: true}) + deg[l.A]++ + deg[l.B]++ + } + } + order := make([]string, 0, len(devs)) + for _, d := range devs { + order = append(order, d.Alias) + } + sort.SliceStable(order, func(i, j int) bool { return deg[order[i]] > deg[order[j]] }) + var out []string + done := map[string]bool{} + var walk func(name, indent string) + walk = func(name, indent string) { + done[name] = true + ls := adj[name] + sort.SliceStable(ls, func(i, j int) bool { return ls[i].Known && !ls[j].Known }) + for _, l := range ls { + port := l.APort + if l.BPort != "" { + port += " ⇄ " + l.BPort + } + switch { + case !l.Known: + out = append(out, fmt.Sprintf("%s %s · %s", indent+"└", l.B, port)) + case done[l.B]: + out = append(out, fmt.Sprintf("%s %s %s (%s)", indent+"└", l.B, port, i18n.T("schon oben"))) + default: + out = append(out, fmt.Sprintf("%s %s %s", indent+"└", l.B, port)) + walk(l.B, indent+" ") + } + } + } + for _, name := range order { + if done[name] { + continue + } + if len(out) > 0 { + out = append(out, "") + } + out = append(out, name) + walk(name, " ") + } + return out +} + +// Mermaid: Topologie als Mermaid-Diagramm (rendert in GitHub, GitLab, +// Obsidian, Confluence …). +func Mermaid(links []Link) string { + var b strings.Builder + b.WriteString("```mermaid\ngraph LR\n") + ids := map[string]string{} + id := func(name string) string { + if v, ok := ids[name]; ok { + return v + } + v := fmt.Sprintf("n%d", len(ids)+1) + ids[name] = v + return v + } + for _, l := range links { + a, c := id(l.A), id(l.B) + label := strings.ReplaceAll(l.APort+" – "+l.BPort, `"`, "'") + shape := `["` + esc(l.B) + `"]` + if !l.Known { + shape = `("` + esc(l.B) + `")` + } + fmt.Fprintf(&b, " %s[\"%s\"] ---|\"%s\"| %s%s\n", a, esc(l.A), strings.TrimSuffix(label, " – "), c, shape) + } + b.WriteString("```\n") + return b.String() +} + +func esc(s string) string { return strings.ReplaceAll(s, `"`, "'") } diff --git a/internal/netmap/netmap.go b/internal/netmap/netmap.go new file mode 100644 index 0000000..732eb05 --- /dev/null +++ b/internal/netmap/netmap.go @@ -0,0 +1,403 @@ +// Package netmap liest MAC-Tabellen, ARP-Tabellen und LLDP/CDP-Nachbarn von +// Switches (ArubaOS-Switch/ProCurve, ArubaOS-CX, Cisco IOS) und setzt daraus +// zusammen, wo ein Gerät hängt und wie die Switches verbunden sind. +// +// Die Befehle laufen über die interaktive Shell (Netzwerkgeräte vertragen +// keine Exec-Kanäle). Die Ausgabe aller Befehle kommt als ein Strom zurück; +// Sections teilt ihn am Echo der Befehlszeilen wieder auf. +package netmap + +import ( + "regexp" + "strconv" + "strings" +) + +// Vendor wie in hostinfo, hier als Text, damit das Paket ohne UI auskommt. +const ( + ProCurve = "procurve" + ArubaCX = "aruba-cx" + Cisco = "cisco" +) + +// Commands: show-Befehle für Suche und Topologie. Unbekannter Hersteller +// bekommt alle Varianten; was das Gerät nicht kennt, lehnt es harmlos ab. +func Commands(vendor string, mac, arp, lldp bool) []string { + var out []string + add := func(c ...string) { out = append(out, c...) } + switch vendor { + case ProCurve: + add("no page") + if mac { + add("show mac-address") + } + if arp { + add("show arp") + } + if lldp { + add("show lldp info remote-device") + } + case ArubaCX: + add("no page") + if mac { + add("show mac-address-table") + } + if arp { + add("show arp") + } + if lldp { + add("show lldp neighbor-info") + } + case Cisco: + add("terminal length 0") + if mac { + add("show mac address-table") + } + if arp { + add("show ip arp") + } + if lldp { + add("show lldp neighbors", "show cdp neighbors") + } + default: + add("no page", "terminal length 0") + if mac { + add("show mac-address", "show mac-address-table", "show mac address-table") + } + if arp { + add("show arp", "show ip arp") + } + if lldp { + add("show lldp info remote-device", "show lldp neighbor-info", "show lldp neighbors", "show cdp neighbors") + } + } + return out +} + +// Sections teilt die Shell-Ausgabe nach Befehlen auf. name ist der Name aus +// dem Prompt („sw-core# show arp“ → sw-core). +func Sections(out string, cmds []string) (sec map[string]string, name string) { + sec = map[string]string{} + cur := "" + var b strings.Builder + flush := func() { + if cur != "" { + sec[cur] += b.String() + } + b.Reset() + } + for _, l := range strings.Split(strings.ReplaceAll(out, "\r", ""), "\n") { + t := strings.TrimSpace(l) + if c, pre, ok := echoOf(t, cmds); ok { + flush() + cur = c + if name == "" { + name = promptName(pre) + } + continue + } + if isPrompt(t) { + if name == "" { + name = promptName(t) + } + continue + } + b.WriteString(l + "\n") + } + flush() + return sec, name +} + +// echoOf: ist t das Echo eines der Befehle („sw# show arp“ oder nur „show arp“)? +// Der längste passende Befehl gewinnt („show lldp neighbors“ vor „show lldp“). +func echoOf(t string, cmds []string) (cmd, prompt string, ok bool) { + for _, c := range cmds { + if !strings.HasSuffix(t, c) || len(c) <= len(cmd) { + continue + } + pre := strings.TrimSpace(t[:len(t)-len(c)]) + if pre == "" || isPrompt(pre) { + cmd, prompt, ok = c, pre, true + } + } + return +} + +func isPrompt(l string) bool { + if l == "" || len(l) > 80 { + return false + } + end := l[len(l)-1] + return (end == '#' || end == '>') && !strings.ContainsAny(l[:len(l)-1], " \t#>") +} + +func promptName(p string) string { + p = strings.TrimRight(strings.TrimSpace(p), "#>") + if i := strings.Index(p, "("); i > 0 { + p = p[:i] + } + return p +} + +// ---------------------------------------------------------------- MAC + +var ( + macColon = regexp.MustCompile(`(?i)\b[0-9a-f]{2}(?:[:-][0-9a-f]{2}){5}\b`) + macDot = regexp.MustCompile(`(?i)\b[0-9a-f]{4}\.[0-9a-f]{4}\.[0-9a-f]{4}\b`) + macHP = regexp.MustCompile(`(?i)\b[0-9a-f]{6}-[0-9a-f]{6}\b`) + macBare = regexp.MustCompile(`(?i)^[0-9a-f]{12}$`) + ipv4 = regexp.MustCompile(`\b(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}\b`) +) + +// NormMAC bringt jede Schreibweise auf 12 Kleinbuchstaben ohne Trenner +// ("" = keine MAC). +func NormMAC(s string) string { + s = strings.ToLower(strings.TrimSpace(s)) + if macColon.MatchString(s) || macDot.MatchString(s) || macHP.MatchString(s) { + s = strings.NewReplacer(":", "", "-", "", ".", "").Replace(s) + } + if !macBare.MatchString(s) { + return "" + } + return s +} + +// FormatMAC: aa:bb:cc:dd:ee:ff. +func FormatMAC(norm string) string { + if len(norm) != 12 { + return norm + } + var b strings.Builder + for i := 0; i < 12; i += 2 { + if i > 0 { + b.WriteByte(':') + } + b.WriteString(norm[i : i+2]) + } + return b.String() +} + +// IsIP: sieht s wie eine IPv4-Adresse aus? +func IsIP(s string) bool { + s = strings.TrimSpace(s) + return ipv4.FindString(s) == s && s != "" +} + +func findMAC(l string) (string, int) { + for _, rx := range []*regexp.Regexp{macColon, macDot, macHP} { + if loc := rx.FindStringIndex(l); loc != nil { + return NormMAC(l[loc[0]:loc[1]]), loc[0] + } + } + return "", -1 +} + +// MACEntry: eine Zeile der MAC-Tabelle. +type MACEntry struct { + MAC string // normiert + Port string + VLAN int +} + +var macType = map[string]bool{"dynamic": true, "static": true, "learned": true, "secure": true, "sticky": true, "permanent": true, "self": true, "port-access": true, "delete-on-timeout": true} + +// ParseMACTable liest MAC-Tabellen aller drei Familien: +// +// ProCurve: 001122-334455 24 1 +// CX: 00:11:22:33:44:55 10 dynamic 1/1/24 +// Cisco: 10 0011.2233.4455 DYNAMIC Gi1/0/24 +func ParseMACTable(text string) []MACEntry { + var out []MACEntry + for _, l := range strings.Split(text, "\n") { + mac, _ := findMAC(l) + if mac == "" { + continue + } + f := strings.Fields(l) + pos := -1 + for i, x := range f { + if NormMAC(x) == mac { + pos = i + break + } + } + if pos < 0 || len(f) < 3 { + continue + } + typed := false + for _, x := range f { + if macType[strings.ToLower(x)] { + typed = true + } + } + var e MACEntry + e.MAC = mac + switch { + case pos == 0 && typed: // CX + e.VLAN, _ = strconv.Atoi(f[1]) + e.Port = f[len(f)-1] + case pos == 0: // ProCurve + e.Port = f[1] + e.VLAN, _ = strconv.Atoi(f[2]) + case pos == 1: // Cisco + v, err := strconv.Atoi(f[0]) + if err != nil { + continue + } + e.VLAN = v + e.Port = f[len(f)-1] + default: + continue + } + if e.Port == "" || macType[strings.ToLower(e.Port)] { + continue + } + out = append(out, e) + } + return out +} + +// ParseARP: IP → MAC aus „show arp“ / „show ip arp“ (jede Zeile mit beidem). +func ParseARP(text string) map[string]string { + out := map[string]string{} + for _, l := range strings.Split(text, "\n") { + ip := ipv4.FindString(l) + mac, _ := findMAC(l) + if ip != "" && mac != "" { + out[ip] = mac + } + } + return out +} + +// ---------------------------------------------------------------- LLDP / CDP + +// Neighbor: ein Nachbar an einem Port. +type Neighbor struct { + LocalPort string + RemoteName string + RemotePort string +} + +// ParseNeighbors liest die Nachbar-Tabellen: +// +// ProCurve „show lldp info remote-device“: 24 | 00 11 22 33 44 55 25 25 sw-core +// CX „show lldp neighbor-info“: 1/1/1 08:97:34:aa:bb:cc 1/1/49 1/1/49 120 core1 +// Cisco „show lldp neighbors“: sw2 Gi1/0/1 120 B,R Gi1/0/2 +// Cisco „show cdp neighbors“: sw2.lab Gig 1/0/1 150 S I WS-C3750 Gig 1/0/2 +func ParseNeighbors(text string) []Neighbor { + var out []Neighbor + mode, pending := "", "" + for _, l := range strings.Split(text, "\n") { + t := strings.TrimSpace(l) + low := strings.ToLower(t) + switch { + case strings.HasPrefix(low, "localport") && strings.Contains(t, "|"): + mode = "procurve" + continue + case strings.HasPrefix(low, "local-port") || strings.HasPrefix(low, "local port") && strings.Contains(low, "chassis"): + mode = "cx" + continue + case strings.HasPrefix(low, "device id") && strings.Contains(low, "local intrfce"): + mode = "cdp" + continue + case strings.HasPrefix(low, "device id") && strings.Contains(low, "local intf"): + mode = "lldp-cisco" + continue + } + if t == "" || strings.HasPrefix(t, "---") || strings.Contains(t, "-----") || isPrompt(t) { + continue + } + if strings.HasPrefix(low, "total ") { + mode = "" + continue + } + var n Neighbor + switch mode { + case "procurve": + i := strings.Index(t, "|") + if i < 0 { + continue + } + n.LocalPort = strings.TrimSpace(t[:i]) + f := strings.Fields(t[i+1:]) + if len(f) < 2 { + continue + } + n.RemoteName = f[len(f)-1] + if len(f) >= 4 { + n.RemotePort = f[len(f)-3] + } + case "cx": + f := strings.Fields(t) + if len(f) < 4 { + continue + } + n.LocalPort, n.RemotePort = f[0], f[2] + if len(f) >= 6 { + n.RemoteName = f[len(f)-1] + } + case "cdp", "lldp-cisco": + f := joinIfNames(strings.Fields(t)) + if len(f) == 1 { // Name zu lang: Rest steht in der nächsten Zeile + pending = f[0] + continue + } + if pending != "" { + f = append([]string{pending}, f...) + pending = "" + } + if len(f) < 3 { + continue + } + n.RemoteName, n.LocalPort, n.RemotePort = f[0], f[1], f[len(f)-1] + default: + continue + } + n.RemoteName = strings.Trim(n.RemoteName, `"`) + if n.LocalPort == "" { + continue + } + out = append(out, n) + } + return out +} + +var ifPrefix = regexp.MustCompile(`(?i)^(gig|gi|ten|te|fas|fa|eth|et|twe|two|fiv|hun|for|port)$`) + +// joinIfNames: „Gig 1/0/1“ → „Gig1/0/1“ (CDP trennt Typ und Nummer). +func joinIfNames(f []string) []string { + var out []string + for i := 0; i < len(f); i++ { + if ifPrefix.MatchString(f[i]) && i+1 < len(f) && len(f[i+1]) > 0 && f[i+1][0] >= '0' && f[i+1][0] <= '9' { + out = append(out, f[i]+f[i+1]) + i++ + continue + } + out = append(out, f[i]) + } + return out +} + +// ShortName: „sw2.lab.example.com“ → „sw2“, zum Vergleichen. +func ShortName(s string) string { + s = strings.ToLower(strings.Trim(strings.TrimSpace(s), `"`)) + if IsIP(s) { + return s + } + if i := strings.IndexByte(s, '.'); i > 0 { + s = s[:i] + } + return s +} + +// PagingOff: Befehle, die das Blättern abschalten (unbekannt = beide). +func PagingOff(vendor string) []string { + switch vendor { + case ProCurve, ArubaCX: + return []string{"no page"} + case Cisco: + return []string{"terminal length 0"} + } + return []string{"no page", "terminal length 0"} +} diff --git a/internal/netmap/netmap_test.go b/internal/netmap/netmap_test.go new file mode 100644 index 0000000..9cd46b2 --- /dev/null +++ b/internal/netmap/netmap_test.go @@ -0,0 +1,170 @@ +package netmap + +import ( + "strings" + "testing" +) + +func TestNormMAC(t *testing.T) { + for _, in := range []string{"00:11:22:aa:bb:cc", "00-11-22-AA-BB-CC", "0011.22aa.bbcc", "001122-aabbcc", "001122aabbcc"} { + if got := NormMAC(in); got != "001122aabbcc" { + t.Errorf("NormMAC(%q) = %q", in, got) + } + } + if NormMAC("10.0.0.1") != "" || NormMAC("hallo") != "" { + t.Error("keine MAC erwartet") + } + if FormatMAC("001122aabbcc") != "00:11:22:aa:bb:cc" { + t.Error(FormatMAC("001122aabbcc")) + } +} + +func TestParseMACTable(t *testing.T) { + pc := ` + Status and Counters - Port Address Table + + MAC Address Port VLAN + ------------- ----- ---- + 001122-aabbcc 17 20 + 001122-000001 25 1 +` + cx := ` +MAC age-time : 300 seconds +MAC Address VLAN Type Port +-------------------------------------------------------------- +00:11:22:aa:bb:cc 20 dynamic 1/1/48 +` + cs := ` + Mac Address Table +------------------------------------------- +Vlan Mac Address Type Ports +---- ----------- -------- ----- + 20 0011.22aa.bbcc DYNAMIC Gi1/0/24 +Total Mac Addresses for this criterion: 1 +` + cases := []struct { + text, port string + vlan int + }{{pc, "17", 20}, {cx, "1/1/48", 20}, {cs, "Gi1/0/24", 20}} + for i, c := range cases { + es := ParseMACTable(c.text) + if len(es) == 0 || es[0].MAC != "001122aabbcc" || es[0].Port != c.port || es[0].VLAN != c.vlan { + t.Errorf("Fall %d: %+v", i, es) + } + } +} + +func TestParseARP(t *testing.T) { + m := ParseARP(` + IP Address MAC Address Type Port + 10.0.20.15 001122-aabbcc dynamic 17 +Internet 10.0.20.16 5 0011.22aa.bbcd ARPA Vlan20 +`) + if m["10.0.20.15"] != "001122aabbcc" || m["10.0.20.16"] != "001122aabbcd" { + t.Errorf("%v", m) + } +} + +func TestParseNeighbors(t *testing.T) { + pc := ` + LLDP Remote Devices Information + + LocalPort | ChassisId PortId PortDescr SysName + --------- + ------------------------- ------ --------- ---------------------- + 25 | 94 18 82 00 00 01 1/1/48 1/1/48 core + 3 | 00 11 22 33 44 55 1 eth0 ap-03 +` + cx := ` +LLDP Neighbor Information +========================= + +Total Neighbor Entries : 1 +LOCAL-PORT CHASSIS-ID PORT-ID PORT-DESC TTL SYS-NAME +-------------------------------------------------------------------- +1/1/48 94:18:82:00:00:02 25 25 120 sw-etage2 +` + cdp := ` +Capability Codes: R - Router, T - Trans Bridge, B - Source Route Bridge +Device ID Local Intrfce Holdtme Capability Platform Port ID +access-switch-lang.example.com + Gig 1/0/1 150 S I WS-C2960 Gig 0/1 +sw4 Gig 1/0/2 150 S I WS-C2960 Gig 0/2 +` + ns := ParseNeighbors(pc) + if len(ns) != 2 || ns[0].LocalPort != "25" || ns[0].RemoteName != "core" || ns[0].RemotePort != "1/1/48" { + t.Errorf("procurve %+v", ns) + } + ns = ParseNeighbors(cx) + if len(ns) != 1 || ns[0].LocalPort != "1/1/48" || ns[0].RemoteName != "sw-etage2" || ns[0].RemotePort != "25" { + t.Errorf("cx %+v", ns) + } + ns = ParseNeighbors(cdp) + if len(ns) != 2 || ns[0].RemoteName != "access-switch-lang.example.com" || ns[0].LocalPort != "Gig1/0/1" || ns[1].RemotePort != "Gig0/2" { + t.Errorf("cdp %+v", ns) + } +} + +func TestSections(t *testing.T) { + cmds := Commands(ProCurve, true, true, true) + out := "Welcome\nsw-etage2# no page\nsw-etage2# show mac-address\n 001122-aabbcc 17 20\nsw-etage2# show arp\n 10.0.0.1 001122-aabbcc dynamic 17\nsw-etage2# show lldp info remote-device\n LocalPort | ChassisId PortId PortDescr SysName\n 25 | 941882000001 1/1/48 1/1/48 core\nsw-etage2# " + sec, name := Sections(out, cmds) + if name != "sw-etage2" { + t.Errorf("name %q", name) + } + if !strings.Contains(sec["show mac-address"], "001122-aabbcc") || strings.Contains(sec["show mac-address"], "10.0.0.1") { + t.Errorf("mac %q", sec["show mac-address"]) + } + d := ParseDevice("etage2", "10.0.0.2", out, cmds) + if len(d.MACs) != 1 || len(d.ARP) != 1 || len(d.Neigh) != 1 { + t.Errorf("%+v", d) + } +} + +func lab() []Device { + return []Device{ + {Alias: "core", Name: "core", MACs: []MACEntry{ + {MAC: "001122aabbcc", Port: "1/1/48", VLAN: 20}, + {MAC: "000000000001", Port: "1/1/48", VLAN: 20}, + {MAC: "000000000002", Port: "1/1/48", VLAN: 20}, + }, ARP: map[string]string{"10.0.20.15": "001122aabbcc"}, + Neigh: []Neighbor{{"1/1/48", "sw-etage2", "25"}}}, + {Alias: "etage2", Name: "sw-etage2", MACs: []MACEntry{ + {MAC: "001122aabbcc", Port: "17", VLAN: 20}, + {MAC: "000000000001", Port: "25", VLAN: 20}, + }, Neigh: []Neighbor{{"25", "core", "1/1/48"}, {"3", "ap-03", "eth0"}}}, + } +} + +func TestLocate(t *testing.T) { + r, err := Locate(lab(), "10.0.20.15") + if err != nil { + t.Fatal(err) + } + if r.MAC != "001122aabbcc" || !r.Edge || r.Found[0].Device != "etage2" || r.Found[0].Port != "17" { + t.Errorf("%+v", r) + } + if r.Found[1].Uplink != "etage2" { + t.Errorf("core-Port sollte Uplink sein: %+v", r.Found[1]) + } + if _, err := Locate(lab(), "10.9.9.9"); err == nil { + t.Error("unbekannte IP sollte scheitern") + } + if _, err := Locate(lab(), "aa:aa:aa:aa:aa:aa"); err == nil { + t.Error("unbekannte MAC sollte scheitern") + } +} + +func TestTopology(t *testing.T) { + ls := Topology(lab()) + if len(ls) != 2 { + t.Fatalf("%+v", ls) + } + tree := strings.Join(TreeLines(lab(), ls), "\n") + if !strings.Contains(tree, "etage2") || !strings.Contains(tree, "ap-03") { + t.Error(tree) + } + m := Mermaid(ls) + if !strings.Contains(m, "graph LR") || !strings.Contains(m, "ap-03") { + t.Error(m) + } +} diff --git a/internal/ui/app.go b/internal/ui/app.go index 356acd2..3b6599c 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -65,6 +65,7 @@ const ( scrTeamForm // Team-Freigabe: Passwort, Datei, Optionen scrHighlightForm // Farbregeln (highlight.go) scrScheduleForm // Zeitplan (schedule.go) + scrRulesForm // Regeln für Switch-Configs (configrules.go) ) // App ist das Wurzel-Modell. @@ -119,6 +120,8 @@ type App struct { formSched domain.Schedule // Zeitplan im Formular (schedule.go) schedRBIDs map[string]string // Runbook-Name → ID im Formular schedRun map[string]bool // laufende Zeitpläne + netData *netCache // letzte Abfrage der Switches (netfind.go) + netBusy bool book *sessionlog.Book // Sitzungsprotokolle (Schlüssel nur bei entsperrtem Store) logs logsState @@ -434,6 +437,9 @@ func (a *App) update(msg tea.Msg) (tea.Model, tea.Cmd) { if cmd, ok := a.scheduleMsg(msg); ok { return a, cmd } + if cmd, ok := a.netMsg(msg); ok { + return a, cmd + } if cmd, ok := a.editMsg(msg); ok { return a, cmd } @@ -464,7 +470,7 @@ func (a *App) update(msg tea.Msg) (tea.Model, tea.Cmd) { if a.pick != nil { return a, a.pickerKey(k) } - if a.keys.is(actHelp, k.String()) && (a.pal != nil || a.scr == scrConnForm || a.scr == scrSettings || a.scr == scrTunnelForm || a.scr == scrImport || a.scr == scrKeys || a.scr == scrBroadcast || a.scr == scrScan || a.scr == scrQuickForm || a.scr == scrMonitorForm || a.scr == scrHighlightForm || a.scr == scrScheduleForm || a.scr == scrKeyForm || a.scr == scrSSHKeyForm || a.scr == scrRelayForm) { + if a.keys.is(actHelp, k.String()) && (a.pal != nil || a.scr == scrConnForm || a.scr == scrSettings || a.scr == scrTunnelForm || a.scr == scrImport || a.scr == scrKeys || a.scr == scrBroadcast || a.scr == scrScan || a.scr == scrQuickForm || a.scr == scrMonitorForm || a.scr == scrHighlightForm || a.scr == scrScheduleForm || a.scr == scrRulesForm || a.scr == scrKeyForm || a.scr == scrSSHKeyForm || a.scr == scrRelayForm) { a.modal = a.helpModal() return a, nil } @@ -505,7 +511,7 @@ func (a *App) update(msg tea.Msg) (tea.Model, tea.Cmd) { return a, a.updateUnlock(msg) case scrManager: return a, a.updateManager(msg) - case scrConnForm, scrSettings, scrTunnelForm, scrQuickForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrKeyForm, scrSSHKeyForm, scrRelayForm: + case scrConnForm, scrSettings, scrTunnelForm, scrQuickForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrRulesForm, scrKeyForm, scrSSHKeyForm, scrRelayForm: return a, a.updateForm(msg) case scrTerminal: return a, a.updateTerminal(msg) @@ -616,7 +622,7 @@ func (a *App) View() tea.View { k = append(k, [2]string{"Strg+D", i18n.T("löschen")}) } body = a.frame(a.viewForm(), append(k, [2]string{"Esc", i18n.T("abbrechen")})) - case scrConnForm, scrKeyForm, scrSSHKeyForm, scrRelayForm, scrMonitorForm, scrHighlightForm, scrScheduleForm: + case scrConnForm, scrKeyForm, scrSSHKeyForm, scrRelayForm, scrMonitorForm, scrHighlightForm, scrScheduleForm, scrRulesForm: body = a.frame(a.viewForm(), [][2]string{{"Tab", i18n.T("weiter")}, {"←/→", i18n.T("wählen")}, {"Strg+S", i18n.T("speichern")}, {"Esc", i18n.T("abbrechen")}}) case scrQuickForm: body = a.frame(a.viewForm(), [][2]string{{"Tab", i18n.T("weiter")}, {"Strg+R", i18n.T("Vorbelegung")}, {"Strg+S", i18n.T("speichern")}, {"Esc", i18n.T("abbrechen")}}) diff --git a/internal/ui/configrules.go b/internal/ui/configrules.go new file mode 100644 index 0000000..6f5330e --- /dev/null +++ b/internal/ui/configrules.go @@ -0,0 +1,81 @@ +package ui + +import ( + "fmt" + "strings" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/hostinfo" + "github.com/db9979/sshtermy/internal/i18n" +) + +// Regeln für Switch-Configs (Palette „Regeln für Switch-Configs“) +// +// Jede gesicherte running-config (F6 b oder Zeitplan „Config-Sicherung“) +// wird gegen diese Regeln geprüft: „+muster“ muss vorkommen, „-muster“ darf +// nicht. Verstöße stehen im F6-Panel und im Ergebnis des Zeitplans. + +const maxConfigRules = 12 + +func (a *App) configRules() []hostinfo.ConfigRule { + return hostinfo.ParseConfigRules(a.st.Settings().ConfigRules) +} + +func (a *App) configRulesHint() string { + n := len(a.st.Settings().ConfigRules) + if n == 0 { + return i18n.T("keine") + } + return fmt.Sprintf(i18n.T("%d Regeln"), n) +} + +func (a *App) openConfigRulesForm() tea.Cmd { + rules := a.st.Settings().ConfigRules + f := &form{title: i18n.T("Regeln für Switch-Configs")} + for i := 0; i < maxConfigRules; i++ { + v := "" + if i < len(rules) { + v = rules[i] + } + h := i18n.T("+muster muss vorkommen, -muster darf nicht · regulärer Ausdruck, zeilenweise") + if i == 0 { + h = i18n.T("z. B. „+^ntp server“, „+^logging“, „-telnet-server“, „-community \"public\"“ · geprüft bei jeder Sicherung (F6 b, Zeitplan)") + } + f.text(fmt.Sprintf("r%d", i), fmt.Sprintf(i18n.T("Regel %d"), i+1), v, h) + } + f.get("r0").in.Placeholder = "+^ntp server" + f.get("r1").in.Placeholder = "-telnet-server" + a.returnToTerminal = a.scr == scrTerminal + a.form, a.scr = f, scrRulesForm + return f.setFocus(0) +} + +func (a *App) saveConfigRules() error { + f := a.form + var rules []string + for i := 0; i < maxConfigRules; i++ { + v := f.str(fmt.Sprintf("r%d", i)) + if v == "" { + continue + } + r, ok, err := hostinfo.ParseConfigRule(v) + if err != nil { + return fmt.Errorf(i18n.T("Regel %d: %v"), i+1, err) + } + if ok { + rules = append(rules, r.String()) + } + } + return a.st.UpdateSettings(func(s *domain.Settings) { s.ConfigRules = rules }) +} + +// violationText: Verstöße in einer Zeile. +func violationText(vs []hostinfo.Violation) string { + var parts []string + for _, v := range vs { + parts = append(parts, v.Text()) + } + return strings.Join(parts, " · ") +} diff --git a/internal/ui/help.go b/internal/ui/help.go index 8c7320f..c39821f 100644 --- a/internal/ui/help.go +++ b/internal/ui/help.go @@ -227,6 +227,8 @@ var helpSections = []helpSection{ {"↓ „umschreiben“", "Befehl fürs System anpassen"}, {"„log“", "KI wertet Ausgabe aus"}, {"„farb“", "Farbregeln bearbeiten"}, + {"MAC / IP", "Switch-Port finden"}, + {"„topo“", "Netzwerk-Topologie"}, {"Esc", "schließen"}, }}, {hcNone, "i", "Systemprofil", "", false, [][2]string{ diff --git a/internal/ui/hostpanel.go b/internal/ui/hostpanel.go index 9476cd6..de2c284 100644 --- a/internal/ui/hostpanel.go +++ b/internal/ui/hostpanel.go @@ -45,6 +45,7 @@ type hostState struct { backups []store.Backup sel int note string // Ergebnis der letzten Sicherung + viol string // verletzte Config-Regeln der letzten Sicherung alerts []hostinfo.Alert // Kennzahlen über der Warnschwelle lastTry time.Time // letzte Server-Abfrage (auch fehlgeschlagene) } @@ -120,6 +121,7 @@ type netResult struct { added int removed int model string // aus der Konfiguration (ProCurve) + viol []hostinfo.Violation err error } @@ -208,6 +210,9 @@ func (a *App) hostNetCmd(s *session, info, backup bool) tea.Cmd { } h.seq++ h.busy, h.err, h.note = true, "", "" + if backup { + h.viol = "" + } h.step = i18n.T("Übersicht abfragen …") if backup && !info { h.step = i18n.T("show running-config sichern …") @@ -221,6 +226,7 @@ func (a *App) hostNetCmd(s *session, info, backup bool) tea.Cmd { } st := a.st connID := s.conn.ID + rules := a.configRules() return func() tea.Msg { defer cancel() r := netResult{vendor: vendor, pagingOff: pagingOff} @@ -273,6 +279,7 @@ func (a *App) hostNetCmd(s *session, info, backup bool) tea.Cmd { } cfg = strings.TrimRight(cfg, "\n") + "\n" r.model = hostinfo.ModelFromConfig(cfg) + r.viol = hostinfo.CheckConfig(cfg, rules) if list := st.Backups(connID); len(list) > 0 { prev := list[0] r.prev = &prev @@ -400,7 +407,13 @@ func (a *App) hostMsg(msg tea.Msg) (tea.Cmd, bool) { } if r.backup != nil || r.unchanged { h.backups, h.sel = a.st.Backups(s.conn.ID), 0 - a.flash(s.conn.Alias + ": " + firstSentence(h.note)) + h.viol = "" + if len(r.viol) > 0 { + h.viol = fmt.Sprintf(i18n.T("Regeln verletzt (%d): "), len(r.viol)) + violationText(r.viol) + a.pushToast(toastWarn, s.conn.Alias+": "+h.viol) + } else { + a.flash(s.conn.Alias + ": " + firstSentence(h.note)) + } } return nil, true } @@ -707,6 +720,9 @@ func (a *App) viewHost(b *strings.Builder, s *session, w int) { if h.note != "" { b.WriteString(st.OK.Render(wrap(h.note, w)) + "\n") } + if h.viol != "" { + b.WriteString(st.Warn.Render(wrap(h.viol, w)) + "\n") + } if len(h.backups) == 0 { b.WriteString(st.Muted.Render(wrap(i18n.T("Noch keine Sicherung. b sichert „show running-config“ verschlüsselt auf diesem Rechner."), w)) + "\n") return diff --git a/internal/ui/manager.go b/internal/ui/manager.go index 11e8c27..956c221 100644 --- a/internal/ui/manager.go +++ b/internal/ui/manager.go @@ -15,8 +15,8 @@ import ( "github.com/db9979/sshtermy/internal/domain" "github.com/db9979/sshtermy/internal/i18n" - "github.com/db9979/sshtermy/internal/pwsource" "github.com/db9979/sshtermy/internal/keychain" + "github.com/db9979/sshtermy/internal/pwsource" "github.com/db9979/sshtermy/internal/sshx" "github.com/db9979/sshtermy/internal/store" ) @@ -885,6 +885,8 @@ func (a *App) updateForm(msg tea.Msg) tea.Cmd { err = a.saveHighlight() case scrScheduleForm: err = a.saveScheduleForm() + case scrRulesForm: + err = a.saveConfigRules() } if err != nil { a.form.err = err.Error() diff --git a/internal/ui/netfind.go b/internal/ui/netfind.go new file mode 100644 index 0000000..3ed82dc --- /dev/null +++ b/internal/ui/netfind.go @@ -0,0 +1,260 @@ +package ui + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/db9979/sshtermy/internal/broadcast" + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/netmap" +) + +// Gerät finden und Topologie (Palette) +// +// „Gerät finden“ nimmt eine MAC oder IP und fragt alle Switches in +// sshTermy nach MAC-Tabelle, ARP-Tabelle und LLDP/CDP-Nachbarn. Der Port, an +// dem kein weiterer Switch hängt und der die wenigsten MACs kennt, ist der +// Zugangsport. „Netzwerk-Topologie“ setzt aus den LLDP/CDP-Nachbarn einen +// Baum zusammen und legt ihn als Mermaid-Diagramm in Downloads ab. +// +// Alles läuft wie der Broadcast über eine eigene Shell je Switch, nur mit +// show-Befehlen. Die Antworten bleiben drei Minuten im Speicher, damit die +// nächste Suche sofort fertig ist. + +const netCacheFor = 3 * time.Minute + +type netCache struct { + at time.Time + lldp bool + mac bool + devs []netmap.Device + fails []string +} + +type netDataMsg struct { + query string // "" = Topologie + data netCache +} + +// netDialer: in Tests austauschbar. +var netDialer = func(a *App) broadcast.Dialer { return a.bcDialer() } + +// netDevices: SSH-Verbindungen, die als Netzwerkgerät bekannt sind. +func (a *App) netDevices() []domain.Connection { + var out []domain.Connection + for _, c := range a.st.Connections() { + if c.Protocol.Raw() { + continue + } + if isNetConn(c) { + out = append(out, c) + } + } + return out +} + +func isNetConn(c domain.Connection) bool { + if c.Device == domain.DeviceNetwork { + return true + } + if c.Device == domain.DeviceServer { + return false + } + return c.Profile != nil && (c.Profile.Family == domain.FamilyNetwork || domain.FamilyOf(c.Profile.Dialect) == domain.FamilyNetwork) +} + +// connVendor: Befehlssatz aus dem Systemprofil. +func connVendor(c domain.Connection) string { + if c.Profile == nil { + return "" + } + switch c.Profile.Dialect { + case "procurve": + return netmap.ProCurve + case "arubaos-cx": + return netmap.ArubaCX + case "cisco-ios": + return netmap.Cisco + } + return "" +} + +func (a *App) askNetFind() tea.Cmd { + m := inputModal(i18n.T("Gerät finden: MAC/IP → Switch-Port"), + i18n.T("MAC (jede Schreibweise) oder IP-Adresse. sshTermy fragt alle Switches nach MAC-, ARP- und LLDP-Tabellen (nur show-Befehle)."), "", + func(v string) tea.Cmd { return a.netFind(v) }) + m.in.Placeholder = "00:11:22:aa:bb:cc · 10.0.20.15" + a.modal = m + return m.in.Focus() +} + +// looksLikeAddr: Palette bietet „Gerät finden“ direkt an. +func looksLikeAddr(q string) bool { + q = strings.TrimSpace(q) + return netmap.NormMAC(q) != "" || netmap.IsIP(q) +} + +func (a *App) netFind(q string) tea.Cmd { + q = strings.TrimSpace(q) + if q == "" { + return nil + } + if !looksLikeAddr(q) { + a.flashErr(fmt.Sprintf(i18n.T("„%s“ ist weder MAC noch IP-Adresse"), q)) + return nil + } + if c := a.netData; c != nil && c.mac && time.Since(c.at) < netCacheFor { + a.showNetFind(q, *c) + return nil + } + return a.netCollect(q, true) +} + +func (a *App) netTopology() tea.Cmd { + if c := a.netData; c != nil && c.lldp && time.Since(c.at) < netCacheFor { + a.showTopology(*c) + return nil + } + return a.netCollect("", false) +} + +// netCollect fragt alle Switches ab; mac=false nur die Nachbarn. +func (a *App) netCollect(query string, mac bool) tea.Cmd { + if a.netBusy { + a.flash(i18n.T("Abfrage läuft schon …")) + return nil + } + conns := a.netDevices() + if len(conns) == 0 { + a.flashErr(i18n.T("Keine Switches in sshTermy: Verbindung auf „Netzwerkgerät“ stellen oder einmal verbinden")) + return nil + } + job := broadcast.Job{Conns: conns, Parallel: 8, Timeout: 3 * time.Minute} + cmds := make([][]string, len(conns)) + for i, c := range conns { + cmds[i] = netmap.Commands(connVendor(c), mac, mac, true) + job.PerHost = append(job.PerHost, cmds[i]) + } + job.Steps = cmds[0] + a.netBusy = true + a.flash(fmt.Sprintf(i18n.T("Frage %d Switches ab (show-Befehle) …"), len(conns))) + dial := netDialer(a) + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + res := broadcast.Run(ctx, job, dial, func(int, broadcast.Result) {}) + data := netCache{at: time.Now(), lldp: true, mac: mac} + for i, r := range res { + if r.Err != "" && r.Output == "" { + data.fails = append(data.fails, "× "+r.Alias+": "+r.Err) + continue + } + data.devs = append(data.devs, netmap.ParseDevice(conns[i].Alias, conns[i].Host, r.Output, cmds[i])) + } + return netDataMsg{query: query, data: data} + } +} + +func (a *App) netMsg(msg tea.Msg) (tea.Cmd, bool) { + m, ok := msg.(netDataMsg) + if !ok { + return nil, false + } + a.netBusy = false + a.netData = &m.data + if m.query == "" { + a.showTopology(m.data) + } else { + a.showNetFind(m.query, m.data) + } + return nil, true +} + +func (a *App) showNetFind(q string, d netCache) { + r, err := netmap.Locate(d.devs, q) + var lines []string + title := i18n.T("Gerät finden: ") + q + if err != nil { + lines = append(lines, "× "+err.Error()) + } else { + head := netmap.FormatMAC(r.MAC) + if r.IP != "" { + head += " · " + r.IP + } + lines = append(lines, head, "") + for i, s := range r.Found { + mark := " " + if i == 0 { + mark = "→ " + } + l := fmt.Sprintf("%s%s %s %s VLAN %d", mark, s.Device, i18n.T("Port"), s.Port, s.VLAN) + switch { + case s.Uplink != "": + l += " · " + i18n.T("Uplink zu ") + s.Uplink + case s.Behind != "": + l += " · " + i18n.T("hinter ") + s.Behind + } + if s.PortMACs > 1 { + l += fmt.Sprintf(i18n.T(" (%d MACs am Port)"), s.PortMACs) + } + lines = append(lines, l) + } + lines = append(lines, "") + if r.Edge { + lines = append(lines, fmt.Sprintf(i18n.T("Das Gerät hängt an %s, Port %s."), r.Found[0].Device, r.Found[0].Port)) + } else { + lines = append(lines, i18n.T("Nur auf Uplinks gesehen: der Zugangs-Switch ist nicht in sshTermy oder antwortet nicht.")) + } + } + lines = append(lines, a.netFooter(d)...) + a.modal = textModal(title, lines) +} + +func (a *App) showTopology(d netCache) { + links := netmap.Topology(d.devs) + var lines []string + if len(links) == 0 { + lines = append(lines, i18n.T("Keine LLDP/CDP-Nachbarn gefunden (LLDP auf den Switches aus?)")) + } else { + lines = append(lines, netmap.TreeLines(d.devs, links)...) + lines = append(lines, "", i18n.T("· = Nachbar, der nicht in sshTermy steht (AP, Telefon, fremder Switch)")) + if p, err := writeTopology(d.devs, links); err == nil { + lines = append(lines, i18n.T("Diagramm (Mermaid): ")+p) + } else { + lines = append(lines, i18n.T("Diagramm nicht gespeichert: ")+err.Error()) + } + } + lines = append(lines, a.netFooter(d)...) + a.modal = textModal(fmt.Sprintf(i18n.T("Netzwerk-Topologie · %d Switches"), len(d.devs)), lines) +} + +func (a *App) netFooter(d netCache) []string { + out := []string{""} + if len(d.fails) > 0 { + sort.Strings(d.fails) + out = append(out, d.fails...) + } + out = append(out, fmt.Sprintf(i18n.T("Stand %s · %d Switches abgefragt · neue Abfrage nach 3 Minuten"), d.at.Format("15:04:05"), len(d.devs))) + return out +} + +func writeTopology(devs []netmap.Device, links []netmap.Link) (string, error) { + if len(links) == 0 { + return "", errors.New(i18n.T("keine Verbindungen")) + } + var b strings.Builder + b.WriteString("# " + i18n.T("Netzwerk-Topologie") + " " + time.Now().Format("2006-01-02 15:04") + "\n\n") + b.WriteString(netmap.Mermaid(links)) + b.WriteString("\n```\n" + strings.Join(netmap.TreeLines(devs, links), "\n") + "\n```\n") + p := filepath.Join(exportDir(), "sshtermy-topologie-"+time.Now().Format("20060102-1504")+".md") + return p, os.WriteFile(p, []byte(b.String()), 0o600) +} diff --git a/internal/ui/netfind_test.go b/internal/ui/netfind_test.go new file mode 100644 index 0000000..d0de399 --- /dev/null +++ b/internal/ui/netfind_test.go @@ -0,0 +1,167 @@ +package ui + +import ( + "context" + "os" + "strings" + "testing" + + "github.com/db9979/sshtermy/internal/broadcast" + "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/sshx" +) + +// fakeSwitch antwortet wie ein ProCurve über die Shell. +type fakeSwitch struct { + name string + out map[string]string +} + +func (e fakeSwitch) NetDevice() bool { return true } +func (e fakeSwitch) Learned() bool { return false } +func (e fakeSwitch) Close() error { return nil } +func (e fakeSwitch) Exec(context.Context, string) (sshx.RunResult, error) { + return sshx.RunResult{}, nil +} +func (e fakeSwitch) RunInShell(_ context.Context, cmds []string) (sshx.RunResult, error) { + var b strings.Builder + for _, c := range cmds { + b.WriteString(e.name + "# " + c + "\n") + if o, ok := e.out[c]; ok { + b.WriteString(o) + } else if c != "no page" && c != "terminal length 0" { + b.WriteString("Invalid input: " + c + "\n") + } + } + b.WriteString(e.name + "# ") + return sshx.RunResult{Output: []byte(b.String()), Exit: -1}, nil +} + +var fakeLab = map[string]fakeSwitch{ + "core": {"core", map[string]string{ + "show mac-address": " 001122-aabbcc 48 20\n 001122-000001 48 20\n 001122-000002 48 20\n", + "show arp": " 10.0.20.15 001122-aabbcc dynamic 48\n", + "show lldp info remote-device": " LocalPort | ChassisId PortId PortDescr SysName\n" + + " --------- + --------- ------ --------- -------\n 48 | 941882000002 25 25 sw-etage2\n", + "show running-config": "hostname \"core\"\nntp server 10.0.0.1\ntelnet-server\n", + }}, + "etage2": {"sw-etage2", map[string]string{ + "show mac-address": " 001122-aabbcc 17 20\n 001122-000001 25 20\n", + "show lldp info remote-device": " LocalPort | ChassisId PortId PortDescr SysName\n" + + " --------- + --------- ------ --------- -------\n 25 | 941882000001 48 48 core\n 3 | 001122334455 eth0 eth0 ap-03\n", + "show running-config": "hostname \"sw-etage2\"\nntp server 10.0.0.1\nvlan 20\n", + }}, +} + +func netTestApp(t *testing.T) *App { + a := newPaletteTestApp(t) + a.pal = nil + for _, alias := range []string{"core", "etage2"} { + if _, err := a.st.UpsertConnection(domain.Connection{Alias: alias, Host: alias, Username: "admin", Auth: domain.AuthAgent, + Device: domain.DeviceNetwork, Group: "Netz"}); err != nil { + t.Fatal(err) + } + } + if _, err := a.st.UpsertConnection(domain.Connection{Alias: "web", Host: "web", Username: "root", Auth: domain.AuthAgent, Device: domain.DeviceServer, Group: "Netz"}); err != nil { + t.Fatal(err) + } + dial := func(*App) broadcast.Dialer { + return func(_ context.Context, c domain.Connection) (broadcast.Executor, error) { + if c.Alias == "web" { + t.Errorf("Server darf nicht abgefragt werden") + } + return fakeLab[c.Alias], nil + } + } + oldN, oldS := netDialer, schedDialer + t.Cleanup(func() { netDialer, schedDialer = oldN, oldS }) + netDialer, schedDialer = dial, dial + return a +} + +func TestNetFind(t *testing.T) { + a := netTestApp(t) + if len(a.netDevices()) != 2 { + t.Fatalf("%d Switches", len(a.netDevices())) + } + cmd := a.netFind("10.0.20.15") + if cmd == nil { + t.Fatal("keine Abfrage") + } + a.netMsg(cmd()) + if a.modal == nil { + t.Fatal("kein Ergebnis") + } + text := strings.Join(a.modal.lines, "\n") + if !strings.Contains(text, "→ etage2 Port 17 VLAN 20") || !strings.Contains(text, "Uplink zu etage2") { + t.Fatal(text) + } + // zweite Suche kommt aus dem Speicher + a.modal = nil + if cmd := a.netFind("00:11:22:00:00:01"); cmd != nil { + t.Fatal("sollte den Speicher nutzen") + } + if a.modal == nil { + t.Fatal("kein Ergebnis aus dem Speicher") + } + if a.netFind("hallo") != nil { + t.Fatal("Unsinn darf nichts abfragen") + } +} + +func TestNetTopology(t *testing.T) { + a := netTestApp(t) + t.Setenv("HOME", t.TempDir()) + cmd := a.netTopology() + a.netMsg(cmd()) + text := strings.Join(a.modal.lines, "\n") + if !strings.Contains(text, "etage2") || !strings.Contains(text, "ap-03") || !strings.Contains(text, "Mermaid") { + t.Fatal(text) + } + var path string + for _, l := range a.modal.lines { + if i := strings.Index(l, "sshtermy-topologie-"); i > 0 { + path = strings.TrimSpace(l[strings.Index(l, ": ")+2:]) + } + } + data, err := os.ReadFile(path) + if err != nil || !strings.Contains(string(data), "graph LR") { + t.Fatalf("%s: %v", path, err) + } +} + +func TestScheduleBackupWithRules(t *testing.T) { + a := netTestApp(t) + _ = a.st.UpdateSettings(func(s *domain.Settings) { s.ConfigRules = []string{"+^ntp server", "-telnet-server"} }) + a.openScheduleForm(domain.Schedule{At: "03:00"}) + f := a.form + setChoice(t, f, "kind", "Config-Sicherung (Switches)") + setChoice(t, f, "folder", "Netz") + if err := a.saveScheduleForm(); err != nil { + t.Fatal(err) + } + sc := a.schedules()[0] + if sc.Kind != domain.ScheduleBackup || sc.Name == "" || len(a.schedConns(sc)) != 2 { + t.Fatalf("%+v", sc) + } + a.scheduleMsg(a.startSchedule(sc)()) + sc, _ = a.scheduleByID(sc.ID) + if sc.LastOK != 1 || sc.LastFail != 1 || !strings.Contains(sc.LastText, "verboten: telnet-server") || !strings.Contains(sc.LastText, "erste Sicherung") { + t.Fatalf("%d/%d\n%s", sc.LastOK, sc.LastFail, sc.LastText) + } + core, _ := a.connByAlias("core") + bs := a.st.Backups(core.ID) + if len(bs) != 1 { + t.Fatalf("%d Sicherungen", len(bs)) + } + cfg, _ := a.st.LoadBackup(core.ID, bs[0].ID) + if !strings.HasPrefix(cfg, "hostname \"core\"") || strings.Contains(cfg, "core#") { + t.Fatalf("%q", cfg) + } + // zweiter Lauf: unverändert, nichts Neues gespeichert + a.scheduleMsg(a.startSchedule(sc)()) + sc, _ = a.scheduleByID(sc.ID) + if len(a.st.Backups(core.ID)) != 1 || !strings.Contains(sc.LastText, "unverändert") { + t.Fatalf("%s", sc.LastText) + } +} diff --git a/internal/ui/palette.go b/internal/ui/palette.go index d420cb2..ef8931d 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -124,6 +124,10 @@ func (a *App) paletteItems() []palItem { if quickFirst { items = append(items, quick...) // user@host:port: Verbinden ist gemeint } + if looksLikeAddr(q) && len(a.netDevices()) > 0 { + items = append(items, palItem{icon: ic("scan"), label: i18n.T("Gerät finden: ") + q, hint: i18n.T("MAC/IP → Switch-Port"), + run: func() tea.Cmd { return a.netFind(q) }}) + } if q != "" && inTerm { items = append(items, palItem{group: pgAI, icon: ic("goal"), label: i18n.T("Als Ziel starten: „") + trunc(oneLine(q), 50) + "“", hint: "⏎", @@ -254,6 +258,10 @@ func (a *App) paletteItems() []palItem { {icon: ic("broadcast"), label: i18n.T("Broadcast: Befehl auf mehreren Hosts"), hint: a.keys.label(actBroadcast), run: func() tea.Cmd { return a.openBroadcast() }}, {icon: ic("scan"), label: i18n.T("Netzwerk-Scan: SSH-Geräte finden"), hint: a.keys.label(actScan), run: func() tea.Cmd { return a.openScan() }}, {icon: ic("runbook"), label: i18n.T("Zeitpläne: Broadcast/Runbook nach Uhrzeit"), hint: a.keys.label(actSchedule), run: func() tea.Cmd { return a.openSchedules() }}, + {icon: ic("scan"), label: i18n.T("Gerät finden: MAC/IP → Switch-Port …"), hint: i18n.T("Switches"), + keys: "mac ip port vlan switch finden suchen wo hängt locate find", run: func() tea.Cmd { return a.askNetFind() }}, + {icon: ic("scan"), label: i18n.T("Netzwerk-Topologie (LLDP/CDP)"), hint: i18n.T("Switches"), + keys: "topologie topology lldp cdp nachbarn neighbors karte map plan", run: func() tea.Cmd { return a.netTopology() }}, {icon: ic("team"), label: i18n.T("Mit dem Team teilen (verschlüsselt, ohne Passwörter)"), hint: "Team", run: func() tea.Cmd { a.scr = scrManager; return a.openTeamShare() }}, {icon: ic("team"), label: i18n.T("Team-Paket übernehmen"), hint: "Team", run: func() tea.Cmd { return a.openTeamTake() }}, {icon: ic("team"), label: i18n.T("Team-Ordner (veröffentlicht / abonniert)"), hint: "Team", run: func() tea.Cmd { return a.openTeamLinks() }}, @@ -543,6 +551,8 @@ func (a *App) palMenuItems() []palItem { palItem{group: pgSetLook, menu: "settings", icon: ic("colors"), label: i18n.T("Farbregeln für die Ausgabe …"), hint: hlHint(a.highlightOn()), keys: "highlight farbregeln einfärben fehler ip mac syslog regeln", run: func() tea.Cmd { return a.openHighlightForm() }}, hide(palToggle(ic("colors"), i18n.T("Farbregeln: Ausgabe einfärben"), a.highlightOn(), "highlight farbregeln einfärben", func() tea.Cmd { return a.toggleHighlight() })), + palItem{group: pgSetLook, menu: "settings", icon: ic("backup"), label: i18n.T("Regeln für Switch-Configs …"), hint: a.configRulesHint(), + keys: "config regeln rules compliance prüfen check ntp telnet snmp switch", run: func() tea.Cmd { return a.openConfigRulesForm() }}, ) iconIdx := -1 for i, st := range iconStyles { diff --git a/internal/ui/schedule.go b/internal/ui/schedule.go index 4591817..1fc19ad 100644 --- a/internal/ui/schedule.go +++ b/internal/ui/schedule.go @@ -11,9 +11,12 @@ import ( "github.com/db9979/sshtermy/internal/broadcast" "github.com/db9979/sshtermy/internal/domain" + "github.com/db9979/sshtermy/internal/hostinfo" "github.com/db9979/sshtermy/internal/i18n" + "github.com/db9979/sshtermy/internal/netmap" "github.com/db9979/sshtermy/internal/runbook" "github.com/db9979/sshtermy/internal/sshx" + "github.com/db9979/sshtermy/internal/store" ) // Zeitpläne (Manager: z, Palette „Zeitpläne“) @@ -203,6 +206,13 @@ func (a *App) openScheduleForm(sc domain.Schedule) tea.Cmd { } f := &form{title: title} f.text("name", "Name", sc.Name, i18n.T("z. B. „Switch-Configs sichern“")) + kinds := []string{i18n.T("Befehle oder Runbook"), i18n.T("Config-Sicherung (Switches)")} + kindCur := kinds[0] + if sc.Kind == domain.ScheduleBackup { + kindCur = kinds[1] + } + f.choice("kind", i18n.T("Art"), kinds, kindCur, i18n.T("Config-Sicherung: show running-config je Switch, verschlüsselt gespeichert, mit den Regeln für Switch-Configs geprüft")) + isBackup := func(f *form) bool { return f.sel("kind") == kinds[1] } f.text("at", i18n.T("Uhrzeit"), sc.At, i18n.T("HH:MM, Ortszeit dieses Rechners")) var days []string for _, d := range dayChoices { @@ -244,9 +254,9 @@ func (a *App) openScheduleForm(sc domain.Schedule) tea.Cmd { } } a.schedRBIDs = rbIDs - f.choice("runbook", "Runbook", rbs, rbCur, i18n.T("Runbooks ohne Variablen und ohne Skripte")) + f.choice("runbook", "Runbook", rbs, rbCur, i18n.T("Runbooks ohne Variablen und ohne Skripte")).hidden = isBackup f.text("steps", i18n.T("Befehle"), strings.Join(sc.Steps, " "+schedStepSep+" "), i18n.T("mehrere Schritte mit ;; trennen · {{host}} {{alias}} werden je Host eingesetzt · Gefährliches geht nie")).hidden = func(f *form) bool { - return f.sel("runbook") != rbs[0] + return isBackup(f) || f.sel("runbook") != rbs[0] } f.get("conns").in.Placeholder = "sw-core, sw-etage1" f.get("steps").in.Placeholder = "show running-config ;; show vlan" @@ -282,18 +292,30 @@ func (a *App) saveScheduleForm() error { sc.Conns = append(sc.Conns, c.ID) } } + sc.Kind = "" + if f.sel("kind") == i18n.T("Config-Sicherung (Switches)") { + sc.Kind = domain.ScheduleBackup + } sc.RunbookID, sc.Steps = a.schedRBIDs[f.sel("runbook")], nil - if sc.RunbookID == "" { + if sc.Kind == domain.ScheduleBackup { + sc.RunbookID = "" + } else if sc.RunbookID == "" { for _, st := range strings.Split(f.str("steps"), schedStepSep) { if st = strings.TrimSpace(st); st != "" { sc.Steps = append(sc.Steps, st) } } } + if sc.Name == "" && sc.Kind == domain.ScheduleBackup { + sc.Name = i18n.T("Switch-Configs sichern") + } if sc.Name == "" { sc.Name = orDefault(firstOf(sc.Steps), i18n.T("Zeitplan")) } if len(a.schedConns(sc)) == 0 { + if sc.Kind == domain.ScheduleBackup { + return errors.New(i18n.T("Kein Switch im Ziel (Server werden bei der Config-Sicherung übersprungen)")) + } return errors.New(i18n.T("Kein Ziel: Ordner wählen oder Verbindungen eintragen")) } if _, err := a.schedSteps(sc); err != nil { @@ -350,15 +372,33 @@ func (a *App) schedConns(sc domain.Schedule) []domain.Connection { } out := list[:0] for _, c := range list { - if !c.Protocol.Raw() { - out = append(out, c) + if c.Protocol.Raw() { + continue } + if sc.Kind == domain.ScheduleBackup && !maybeNetConn(c) { + continue + } + out = append(out, c) } return out } +// maybeNetConn: kein bekannter Server (für die Config-Sicherung). +func maybeNetConn(c domain.Connection) bool { + if isNetConn(c) { + return true + } + if c.Device == domain.DeviceServer { + return false + } + return c.Profile == nil || c.Profile.Family == "" +} + // schedSteps: die Schritte, geprüft für einen Lauf ohne Aufsicht. func (a *App) schedSteps(sc domain.Schedule) ([]string, error) { + if sc.Kind == domain.ScheduleBackup { + return []string{"show running-config"}, nil + } steps := sc.Steps if sc.RunbookID != "" { var found bool @@ -428,7 +468,14 @@ func (a *App) startSchedule(sc domain.Schedule) tea.Cmd { } a.schedRun[sc.ID] = true job := broadcast.Job{Conns: conns, Steps: steps} - if runbook.HasBuiltins(steps) { + var backup *schedBackup + if sc.Kind == domain.ScheduleBackup { + backup = &schedBackup{st: a.st, rules: a.configRules()} + for _, c := range conns { + cmds := append(netmap.PagingOff(connVendor(c)), "show running-config") + job.PerHost = append(job.PerHost, cmds) + } + } else if runbook.HasBuiltins(steps) { for _, c := range conns { job.PerHost = append(job.PerHost, runbook.Fill(steps, nil, c)) } @@ -440,6 +487,9 @@ func (a *App) startSchedule(sc domain.Schedule) tea.Cmd { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) defer cancel() res := broadcast.Run(ctx, job, dial, func(int, broadcast.Result) {}) + if backup != nil { + backup.apply(conns, job.PerHost, res) + } return schedDoneMsg{id: id, results: res} } } @@ -542,3 +592,61 @@ func scheduleReport(rs []broadcast.Result) string { } return strings.TrimRight(b.String(), "\n") } + +// ---------------------------------------------------------------- Config-Sicherung + +// schedBackup: nach dem Lauf die running-config jedes Switches sichern +// (nur wenn sie sich geändert hat) und gegen die Regeln prüfen. Die Ausgabe +// im Ergebnis wird durch eine Zeile Zusammenfassung ersetzt. +type schedBackup struct { + st *store.Store + rules []hostinfo.ConfigRule +} + +func (b *schedBackup) apply(conns []domain.Connection, cmds [][]string, res []broadcast.Result) { + for i := range res { + r := &res[i] + if r.State != broadcast.Done || r.Err != "" { + continue + } + if !r.Net { + r.Output, r.Err = "", i18n.T("kein Netzwerkgerät, übersprungen") + continue + } + sec, _ := netmap.Sections(r.Output, cmds[i]) + cfg := strings.TrimSpace(sec["show running-config"]) + if err := checkConfig(cfg); err != nil { + r.Output, r.Err = "", err.Error() + continue + } + cfg += "\n" + note, err := b.save(conns[i].ID, cfg) + if err != nil { + r.Output, r.Err = "", err.Error() + continue + } + r.Output = note + if vs := hostinfo.CheckConfig(cfg, b.rules); len(vs) > 0 { + r.Err = fmt.Sprintf(i18n.T("Regeln verletzt (%d): "), len(vs)) + violationText(vs) + } + } +} + +func (b *schedBackup) save(connID, cfg string) (string, error) { + if list := b.st.Backups(connID); len(list) > 0 { + if old, err := b.st.LoadBackup(connID, list[0].ID); err == nil { + if hostinfo.SameConfig(old, cfg) { + return i18n.T("unverändert seit ") + localTime(list[0].Taken), nil + } + _, add, rem := hostinfo.Diff(hostinfo.ConfigLines(old), hostinfo.ConfigLines(cfg), 0) + if _, err := b.st.SaveBackup(connID, cfg); err != nil { + return "", err + } + return fmt.Sprintf(i18n.T("gesichert, +%d −%d Zeilen (F6 d zeigt den Diff)"), add, rem), nil + } + } + if _, err := b.st.SaveBackup(connID, cfg); err != nil { + return "", err + } + return i18n.T("erste Sicherung gespeichert"), nil +} diff --git a/internal/ui/testdata/golden/palette.de.txt b/internal/ui/testdata/golden/palette.de.txt index e95789b..861594f 100644 --- a/internal/ui/testdata/golden/palette.de.txt +++ b/internal/ui/testdata/golden/palette.de.txt @@ -1,6 +1,6 @@ >_ sshTermy vdev Idee: Dominik Bornhäußer ● KI Verbindungen 6 / suchen │ ▾ Netzwerk - ┌─ ◆ Befehlspalette 22 Einträge ────────────────────────────────────── × ─┐ + ┌─ ◆ Befehlspalette 24 Einträge ────────────────────────────────────── × ─┐ ▾ Netzwerk │ $ Ziel, Frage, Befehl, Tunnel, Verbindung oder user@host:port … │ ○ # switc│ ──────────────────────────────────────────────────────────────────────── │ ▾ Produktio│ // verbindungen │ @@ -18,11 +18,11 @@ │ [*] Broadcast: Befehl auf mehreren Hosts m │ │ [/] Netzwerk-Scan: SSH-Geräte finden f │ │ [>] Zeitpläne: Broadcast/Runbook nach Uhrzeit z │ + │ [/] Gerät finden: MAC/IP → Switch-Port … Switches │ + │ [/] Netzwerk-Topologie (LLDP/CDP) Switches │ │ [&] Mit dem Team teilen (verschlüsselt, ohne Passwörter) Team │ │ [&] Team-Paket übernehmen Team │ │ [&] Team-Ordner (veröffentlicht / abonniert) Team │ - │ [#] Sitzungsprotokolle durchsuchen l │ - │ [$] Lokale Shell öffnen Alt+L │ │ │ │ ↑↓ wählen ⏎ ausführen Esc schließen │ └──────────────────────────────────────────────────────────────────────────┘ diff --git a/internal/ui/testdata/golden/palette.en.txt b/internal/ui/testdata/golden/palette.en.txt index 9a04e68..4a83e4c 100644 --- a/internal/ui/testdata/golden/palette.en.txt +++ b/internal/ui/testdata/golden/palette.en.txt @@ -1,6 +1,6 @@ >_ sshTermy vdev Idea: Dominik Bornhäußer ● AI connections 6 / search │ ▾ Netzwerk - ┌─ ◆ Command palette 22 entries ────────────────────────────────────── × ─┐ + ┌─ ◆ Command palette 24 entries ────────────────────────────────────── × ─┐ ▾ Netzwerk │ $ Goal, question, command, tunnel, connection or user@host:port … │ ○ # switc│ ──────────────────────────────────────────────────────────────────────── │ ▾ Produktio│ // connections │ @@ -18,11 +18,11 @@ │ [*] Broadcast: command on several hosts m │ │ [/] Network scan: find SSH devices f │ │ [>] Schedules: broadcast/runbook at a set time z │ + │ [/] Find device: MAC/IP → switch port … switches │ + │ [/] Network topology (LLDP/CDP) switches │ │ [&] Share with the team (encrypted, no passwords) Team │ │ [&] Import team package Team │ │ [&] Team folders (published / subscribed) Team │ - │ [#] Search session logs l │ - │ [$] Open local shell Alt+L │ │ │ │ ↑↓ select ⏎ run Esc close │ └──────────────────────────────────────────────────────────────────────────┘ diff --git a/site/de/index.html b/site/de/index.html index 050ba7e..ff38556 100644 --- a/site/de/index.html +++ b/site/de/index.html @@ -124,6 +124,8 @@ sudo apt update && sudo apt install sshtermy
CPU, Last, RAM, Platte und Updates bei Servern; Firmware, Ports und VLANs bei Aruba- und Cisco-Switches, mit Konfig-Sicherung und Diff.
-L, -R, -D (SOCKS5) und Webdienste mit einem Klick.
Ein Befehl oder Runbook parallel auf einer ganzen Gruppe, Ergebnisse nebeneinander.
MAC oder IP rein, Switch, Port und VLAN raus: sshTermy liest MAC-, ARP- und LLDP-Tabellen aller Switches.
LLDP/CDP-Nachbarn werden zu Baum und Mermaid-Diagramm; Config-Regeln prüfen jede Sicherung.
Broadcast oder Runbook zu einer Uhrzeit auf einem Ordner, z. B. nachts show running-config auf allen Switches.
Passwörter und 2FA-Codes aus 1Password, Bitwarden, KeePassXC oder pass; gespeichert wird nur der Verweis.
SSH-Geräte in einem Subnetz finden und als Verbindungen anlegen.
CPU, load, RAM, disk and updates for servers; firmware, ports and VLANs for Aruba and Cisco switches, with config backup and diff.
-L, -R, -D (SOCKS5) and web services with one click.
One command or runbook on a whole group in parallel, results side by side.
MAC or IP in, switch, port and VLAN out: sshTermy reads the MAC, ARP and LLDP tables of all switches.
LLDP/CDP neighbors become a tree and a Mermaid diagram; config rules check every backup.
Broadcast or runbook at a set time on a folder, e.g. nightly show running-config on all switches.
Passwords and 2FA codes from 1Password, Bitwarden, KeePassXC or pass; only the reference is stored.
Find SSH devices in a subnet and create them as connections.