feat(snmp,ui): устройства за портом (MAC/IP) в таблице 2

Добавил сбор FDB/ARP по SNMP (BRIDGE-MIB + ipNetToMedia), хранение и API /port-devices.
В UI Таблица 2 теперь показывает MAC/IP за выбранным портом после клика по строке Таблицы 1.

Made-with: Cursor
This commit is contained in:
Луценко Андрей Анатольевич
2026-04-10 17:44:42 +10:00
parent 526c67b5b1
commit 5b82901565
7 changed files with 350 additions and 39 deletions
+129 -5
View File
@@ -102,7 +102,7 @@ func (r *Runner) run(job ScanJob) {
}
}
if isUp && r.cfg.SNMPEnabled {
snmpRes, lldpRes, ifRes := probeSNMPAndLLDP(ip, r.cfg.SNMPCommunity, checkedAt, job.Options.PingTimeoutMS)
snmpRes, lldpRes, ifRes, portDevRes := probeSNMPAndLLDP(ip, r.cfg.SNMPCommunity, checkedAt, job.Options.PingTimeoutMS)
_ = r.store.SaveSNMPResult(job.ID, snmpRes)
for _, lr := range lldpRes {
if err := r.store.SaveLLDPResult(job.ID, lr); err != nil {
@@ -114,6 +114,11 @@ func (r *Runner) run(job ScanJob) {
log.Printf("scan %s: save interface %s ifIndex=%d: %v", job.ID, iface.IP, iface.IfIndex, err)
}
}
for _, pd := range portDevRes {
if err := r.store.SavePortDeviceResult(job.ID, pd); err != nil {
log.Printf("scan %s: save port-device %s ifIndex=%d mac=%s: %v", job.ID, pd.IP, pd.IfIndex, pd.MAC, err)
}
}
}
mu.Lock()
@@ -153,7 +158,7 @@ func (r *Runner) run(job ScanJob) {
})
}
func probeSNMPAndLLDP(ip, community string, checkedAt time.Time, timeoutMS int) (SNMPResult, []LLDPResult, []InterfaceResult) {
func probeSNMPAndLLDP(ip, community string, checkedAt time.Time, timeoutMS int) (SNMPResult, []LLDPResult, []InterfaceResult, []PortDeviceResult) {
if timeoutMS <= 0 {
timeoutMS = 700
}
@@ -170,7 +175,7 @@ func probeSNMPAndLLDP(ip, community string, checkedAt time.Time, timeoutMS int)
Retries: 1,
}
if err := client.Connect(); err != nil {
return SNMPResult{IP: ip, Success: false, Error: err.Error(), CheckedAt: checkedAt}, nil, nil
return SNMPResult{IP: ip, Success: false, Error: err.Error(), CheckedAt: checkedAt}, nil, nil, nil
}
defer client.Conn.Close()
@@ -181,7 +186,7 @@ func probeSNMPAndLLDP(ip, community string, checkedAt time.Time, timeoutMS int)
}
pkt, err := client.Get(oids)
if err != nil {
return SNMPResult{IP: ip, Success: false, Error: err.Error(), CheckedAt: checkedAt}, nil, nil
return SNMPResult{IP: ip, Success: false, Error: err.Error(), CheckedAt: checkedAt}, nil, nil, nil
}
out := SNMPResult{IP: ip, Success: true, CheckedAt: checkedAt}
@@ -208,10 +213,129 @@ func probeSNMPAndLLDP(ip, community string, checkedAt time.Time, timeoutMS int)
lldpRes := probeLLDP(client, ip, checkedAt)
var ifList []InterfaceResult
var portDevices []PortDeviceResult
if out.Success {
ifList = probeIfTable(client, ip, checkedAt)
portDevices = probePortDevices(client, ip, checkedAt)
}
return out, lldpRes, ifList
return out, lldpRes, ifList, portDevices
}
// probePortDevices собирает MAC-адреса за портами (BRIDGE-MIB) и пытается сопоставить им IP через ARP (ipNetToMedia).
func probePortDevices(client *gosnmp.GoSNMP, ip string, checkedAt time.Time) []PortDeviceResult {
// dot1dBasePortIfIndex: bridge-port -> ifIndex
basePortIfIndex := walkAsMap(client, ".1.3.6.1.2.1.17.1.4.1.2")
// dot1dTpFdbPort: mac(6 octets) -> bridge-port
fdbMacToBridgePort := walkAsMap(client, ".1.3.6.1.2.1.17.4.3.1.2")
// ipNetToMediaPhysAddress: ifIndex.ip -> mac
arpIfIPToMac := walkAsMap(client, ".1.3.6.1.2.1.4.22.1.2")
if len(basePortIfIndex) == 0 || len(fdbMacToBridgePort) == 0 {
return nil
}
macToIPs := make(map[string]map[string]struct{})
for key, mac := range arpIfIPToMac {
mac = strings.ToLower(strings.TrimSpace(mac))
if mac == "" || !strings.Contains(mac, ":") {
continue
}
parts := strings.Split(key, ".")
if len(parts) < 5 {
continue
}
ipStr := strings.Join(parts[1:], ".")
if net.ParseIP(ipStr) == nil {
continue
}
if _, ok := macToIPs[mac]; !ok {
macToIPs[mac] = make(map[string]struct{})
}
macToIPs[mac][ipStr] = struct{}{}
}
seen := make(map[string]struct{})
out := make([]PortDeviceResult, 0, len(fdbMacToBridgePort))
for macTail, bridgePortRaw := range fdbMacToBridgePort {
mac := dottedDecimalToMAC(macTail)
if mac == "" {
continue
}
bridgePort, err := strconv.Atoi(strings.TrimSpace(bridgePortRaw))
if err != nil || bridgePort <= 0 {
continue
}
ifIndexRaw, ok := basePortIfIndex[strconv.Itoa(bridgePort)]
if !ok {
continue
}
ifIndex, err := strconv.Atoi(strings.TrimSpace(ifIndexRaw))
if err != nil || ifIndex <= 0 {
continue
}
ipsSet := macToIPs[strings.ToLower(mac)]
if len(ipsSet) == 0 {
key := fmt.Sprintf("%d|%s|", ifIndex, mac)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
out = append(out, PortDeviceResult{
IP: ip,
IfIndex: ifIndex,
MAC: mac,
LearnedIP: "",
CheckedAt: checkedAt,
})
continue
}
for learnedIP := range ipsSet {
key := fmt.Sprintf("%d|%s|%s", ifIndex, mac, learnedIP)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
out = append(out, PortDeviceResult{
IP: ip,
IfIndex: ifIndex,
MAC: mac,
LearnedIP: learnedIP,
CheckedAt: checkedAt,
})
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].IfIndex != out[j].IfIndex {
return out[i].IfIndex < out[j].IfIndex
}
if out[i].MAC != out[j].MAC {
return out[i].MAC < out[j].MAC
}
return out[i].LearnedIP < out[j].LearnedIP
})
const maxRows = 20000
if len(out) > maxRows {
out = out[:maxRows]
}
return out
}
func dottedDecimalToMAC(s string) string {
p := strings.Split(strings.TrimSpace(s), ".")
if len(p) != 6 {
return ""
}
b := make([]byte, 6)
for i := 0; i < 6; i++ {
n, err := strconv.Atoi(p[i])
if err != nil || n < 0 || n > 255 {
return ""
}
b[i] = byte(n)
}
return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", b[0], b[1], b[2], b[3], b[4], b[5])
}
// probeIfTable собирает ifDescr, ifName (ifXTable), ifOperStatus по IF-MIB для списка портов в UI.