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
+46
View File
@@ -538,3 +538,49 @@ func (s *PostgresStore) PurgeAllScanData() error {
_, err := s.db.ExecContext(context.Background(), `truncate table scan_jobs restart identity cascade`)
return err
}
func (s *PostgresStore) SavePortDeviceResult(scanID string, result PortDeviceResult) error {
query := `
insert into scan_port_devices (scan_id, ip, if_index, mac, learned_ip, checked_at)
values ($1, $2, $3, $4, $5, $6)`
_, err := s.db.ExecContext(
context.Background(),
query,
scanID,
result.IP,
result.IfIndex,
result.MAC,
result.LearnedIP,
result.CheckedAt,
)
return err
}
func (s *PostgresStore) ListPortDeviceResults(scanID string, filterIP string, filterIfIndex int, limit int) []PortDeviceResult {
if limit <= 0 {
limit = 20000
}
query := `
select ip::text, if_index, coalesce(mac, ''), coalesce(learned_ip::text, ''), checked_at
from scan_port_devices
where scan_id = $1
and ($2 = '' or ip = $2::inet)
and ($3 = 0 or if_index = $3)
order by if_index asc, mac asc, learned_ip asc
limit $4`
rows, err := s.db.QueryContext(context.Background(), query, scanID, filterIP, filterIfIndex, limit)
if err != nil {
return nil
}
defer rows.Close()
out := make([]PortDeviceResult, 0, 256)
for rows.Next() {
var r PortDeviceResult
if err = rows.Scan(&r.IP, &r.IfIndex, &r.MAC, &r.LearnedIP, &r.CheckedAt); err != nil {
return nil
}
out = append(out, r)
}
return out
}
+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.
+60
View File
@@ -69,6 +69,8 @@ type Store interface {
ListLLDPResults(scanID string, limit int) []LLDPResult
SaveInterfaceResult(scanID string, result InterfaceResult) error
ListInterfaceResults(scanID string, filterIP string, limit int) []InterfaceResult
SavePortDeviceResult(scanID string, result PortDeviceResult) error
ListPortDeviceResults(scanID string, filterIP string, filterIfIndex int, limit int) []PortDeviceResult
// PurgeAllScanData удаляет все сканы и связанные строки (хосты, порты, SNMP, LLDP, интерфейсы).
PurgeAllScanData() error
}
@@ -115,6 +117,15 @@ type InterfaceResult struct {
CheckedAt time.Time `json:"checked_at"`
}
// PortDeviceResult — MAC/IP, обнаруженные за конкретным портом (ifIndex) через BRIDGE-MIB + ARP.
type PortDeviceResult struct {
IP string `json:"ip"`
IfIndex int `json:"if_index"`
MAC string `json:"mac"`
LearnedIP string `json:"learned_ip"`
CheckedAt time.Time `json:"checked_at"`
}
type MemoryStore struct {
mu sync.RWMutex
jobs map[string]ScanJob
@@ -123,6 +134,7 @@ type MemoryStore struct {
snmp map[string][]SNMPResult
lldp map[string][]LLDPResult
ifaces map[string][]InterfaceResult
fdb map[string][]PortDeviceResult
}
func NewMemoryStore() *MemoryStore {
@@ -133,6 +145,7 @@ func NewMemoryStore() *MemoryStore {
snmp: make(map[string][]SNMPResult),
lldp: make(map[string][]LLDPResult),
ifaces: make(map[string][]InterfaceResult),
fdb: make(map[string][]PortDeviceResult),
}
}
@@ -341,6 +354,7 @@ func (s *MemoryStore) PurgeAllScanData() error {
s.snmp = make(map[string][]SNMPResult)
s.lldp = make(map[string][]LLDPResult)
s.ifaces = make(map[string][]InterfaceResult)
s.fdb = make(map[string][]PortDeviceResult)
return nil
}
@@ -373,6 +387,52 @@ func (s *MemoryStore) ListInterfaceResults(scanID string, filterIP string, limit
return out
}
func (s *MemoryStore) SavePortDeviceResult(scanID string, result PortDeviceResult) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.jobs[scanID]; !ok {
return errors.New("scan not found")
}
s.fdb[scanID] = append(s.fdb[scanID], result)
return nil
}
func (s *MemoryStore) ListPortDeviceResults(scanID string, filterIP string, filterIfIndex int, limit int) []PortDeviceResult {
if limit <= 0 {
limit = 20000
}
s.mu.RLock()
defer s.mu.RUnlock()
items := s.fdb[scanID]
filtered := make([]PortDeviceResult, 0, len(items))
for _, r := range items {
if filterIP != "" && r.IP != filterIP {
continue
}
if filterIfIndex > 0 && r.IfIndex != filterIfIndex {
continue
}
filtered = append(filtered, r)
}
sort.Slice(filtered, func(i, j int) bool {
if filtered[i].IfIndex != filtered[j].IfIndex {
return filtered[i].IfIndex < filtered[j].IfIndex
}
if filtered[i].MAC != filtered[j].MAC {
return filtered[i].MAC < filtered[j].MAC
}
return filtered[i].LearnedIP < filtered[j].LearnedIP
})
if len(filtered) <= limit {
out := make([]PortDeviceResult, len(filtered))
copy(out, filtered)
return out
}
out := make([]PortDeviceResult, limit)
copy(out, filtered[:limit])
return out
}
func applyDefaultOptions(opts *ScanOptions) {
if opts.PingTimeoutMS <= 0 {
opts.PingTimeoutMS = 700