diff --git a/cmd/main.go b/cmd/main.go index 6fca01f..fa6a612 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "path/filepath" + "strings" "sync" "time" @@ -29,6 +30,8 @@ type App struct { tasks map[string]*models.ScanTask mu sync.RWMutex httpServer *http.Server + sessions map[string]time.Time // token -> expire time + sessionMu sync.RWMutex } // NewApp 创建应用 @@ -51,6 +54,7 @@ func NewApp(cfg *config.Config) *App { storage: store, topologyStorage: topoStorage, tasks: make(map[string]*models.ScanTask), + sessions: make(map[string]time.Time), } // 如果有拓扑存储,切换到第一个拓扑 @@ -85,36 +89,56 @@ func (app *App) Start() error { // 设置路由 mux := http.NewServeMux() - // 静态文件服务 - 使用文件系统而非embed + // 登录API(无需认证) + mux.HandleFunc("/api/login", app.handleLogin) + mux.HandleFunc("/api/logout", app.handleLogout) + + // 登录页面(无需认证) + mux.HandleFunc("/login", app.handleLoginPage) + + // 认证中间件保护的路由 + authMux := http.NewServeMux() + + // 静态文件服务 webDir := getWebDir() if _, err := os.Stat(webDir); err == nil { - mux.Handle("/", http.FileServer(http.Dir(webDir))) + authMux.Handle("/", http.FileServer(http.Dir(webDir))) } else { log.Printf("警告: web目录不存在,静态文件服务不可用") - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + authMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("

网络拓扑发现系统

Web界面文件未找到

")) }) } // API路由 - mux.HandleFunc("/api/scan", app.handleScan) - mux.HandleFunc("/api/scan/{id}", app.handleScanProgress) - mux.HandleFunc("/api/topology", app.handleTopology) - mux.HandleFunc("/api/devices", app.handleGetDevices) - mux.HandleFunc("/api/device", app.handleAddDevice) - mux.HandleFunc("/api/device/{id}", app.handleDeviceDetail) + authMux.HandleFunc("/api/scan", app.handleScan) + authMux.HandleFunc("/api/scan/{id}", app.handleScanProgress) + authMux.HandleFunc("/api/topology", app.handleTopology) + authMux.HandleFunc("/api/devices", app.handleGetDevices) + authMux.HandleFunc("/api/device", app.handleAddDevice) + authMux.HandleFunc("/api/device/{id}", app.handleDeviceDetail) // 拓扑管理API - mux.HandleFunc("/api/topologies", app.handleTopologies) - mux.HandleFunc("/api/topology/switch", app.handleSwitchTopology) - mux.HandleFunc("/api/topology/{id}", app.handleTopologyDetail) + authMux.HandleFunc("/api/topologies", app.handleTopologies) + authMux.HandleFunc("/api/topology/switch", app.handleSwitchTopology) + authMux.HandleFunc("/api/topology/{id}", app.handleTopologyDetail) // SSH终端API - mux.HandleFunc("/api/terminal", app.handleTerminalConnect) + authMux.HandleFunc("/api/terminal", app.handleTerminalConnect) // 全局设备池API - mux.HandleFunc("/api/devices/all", app.handleGetAllDevices) - mux.HandleFunc("/api/topology/{id}/devices", app.handleAddDevicesToTopology) + authMux.HandleFunc("/api/devices/all", app.handleGetAllDevices) + authMux.HandleFunc("/api/topology/{id}/devices", app.handleAddDevicesToTopology) + + // 根据认证配置决定是否启用中间件 + var handler http.Handler = authMux + if app.config.Auth.Enabled { + handler = app.authMiddleware(authMux) + log.Printf("认证已启用, 用户: %s", app.config.Auth.Username) + } else { + log.Printf("认证未启用") + } + mux.Handle("/", handler) addr := fmt.Sprintf("%s:%d", app.config.Web.Host, app.config.Web.Port) app.httpServer = &http.Server{ @@ -394,6 +418,64 @@ func (app *App) handleAddDevice(w http.ResponseWriter, r *http.Request) { func (app *App) handleDeviceDetail(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") + if r.Method == http.MethodDelete { + // 删除设备 + if app.storage == nil { + http.Error(w, "Storage not available", http.StatusInternalServerError) + return + } + if err := app.storage.DeleteDevice(id); err != nil { + log.Printf("Failed to delete device %s: %v", id, err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + // 同时从 builder 中移除 + app.builder.RemoveDevice(id) + log.Printf("Deleted device: %s", id) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]string{"status": "success"}) + return + } + + if r.Method == http.MethodPut { + // 修改设备信息(Hostname、Type) + var req struct { + Hostname string `json:"hostname"` + Type string `json:"type"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + if app.storage == nil { + http.Error(w, "Storage not available", http.StatusInternalServerError) + return + } + dev, err := app.storage.GetDevice(id) + if err != nil { + http.Error(w, "Device not found", http.StatusNotFound) + return + } + if req.Hostname != "" { + dev.Hostname = req.Hostname + } + if req.Type != "" { + dev.Type = models.DeviceType(req.Type) + } + if err := app.storage.SaveDevice(dev); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + // 同时更新 builder 中的设备 + app.builder.AddDevice(*dev) + log.Printf("Updated device: %s", id) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(dev) + return + } + + // GET: 获取设备详情 devices := app.builder.GetDevices() for _, dev := range devices { if dev.ID == id || dev.IP == id { @@ -592,6 +674,125 @@ func (app *App) handleTerminalConnect(w http.ResponseWriter, r *http.Request) { terminal.HandleTerminal(w, r, ip, port, username, password) } +// ==================== 认证相关 ==================== + +// authMiddleware 认证中间件 +func (app *App) authMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // 从 cookie 获取 token + cookie, err := r.Cookie("session_token") + if err != nil || !app.isValidSession(cookie.Value) { + // API 请求返回 401,页面请求重定向到登录 + if strings.HasPrefix(r.URL.Path, "/api/") { + http.Error(w, `{"error": "Unauthorized"}`, http.StatusUnauthorized) + } else { + http.Redirect(w, r, "/login", http.StatusFound) + } + return + } + next.ServeHTTP(w, r) + }) +} + +// isValidSession 验证会话是否有效 +func (app *App) isValidSession(token string) bool { + if token == "" { + return false + } + app.sessionMu.RLock() + expire, exists := app.sessions[token] + app.sessionMu.RUnlock() + if !exists { + return false + } + if time.Now().After(expire) { + app.sessionMu.Lock() + delete(app.sessions, token) + app.sessionMu.Unlock() + return false + } + return true +} + +// generateToken 生成随机 token +func generateToken() string { + b := make([]byte, 32) + rand.Read(b) + return fmt.Sprintf("%x", b) +} + +// handleLogin 处理登录 +func (app *App) handleLogin(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var req struct { + Username string `json:"username"` + Password string `json:"password"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + if !app.config.Auth.Enabled { + json.NewEncoder(w).Encode(map[string]interface{}{"success": true}) + return + } + + if req.Username == app.config.Auth.Username && req.Password == app.config.Auth.Password { + token := generateToken() + expire := time.Now().Add(24 * time.Hour) + + app.sessionMu.Lock() + app.sessions[token] = expire + app.sessionMu.Unlock() + + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: token, + Path: "/", + Expires: expire, + HttpOnly: true, + }) + + log.Printf("用户 %s 登录成功", req.Username) + json.NewEncoder(w).Encode(map[string]interface{}{"success": true}) + } else { + log.Printf("登录失败: 用户名或密码错误 (username=%s)", req.Username) + w.WriteHeader(http.StatusUnauthorized) + json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "用户名或密码错误"}) + } +} + +// handleLogout 处理登出 +func (app *App) handleLogout(w http.ResponseWriter, r *http.Request) { + if cookie, err := r.Cookie("session_token"); err == nil { + app.sessionMu.Lock() + delete(app.sessions, cookie.Value) + app.sessionMu.Unlock() + } + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + }) + http.Redirect(w, r, "/login", http.StatusFound) +} + +// handleLoginPage 返回登录页面 +func (app *App) handleLoginPage(w http.ResponseWriter, r *http.Request) { + if !app.config.Auth.Enabled { + http.Redirect(w, r, "/", http.StatusFound) + return + } + http.ServeFile(w, r, filepath.Join(getWebDir(), "login.html")) +} + // 获取所有拓扑中的全部设备(全局设备池) func (app *App) handleGetAllDevices(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { diff --git a/config.example.json b/config.example.json index 836e0e2..5b96e7a 100644 --- a/config.example.json +++ b/config.example.json @@ -30,5 +30,10 @@ "scanner": { "concurrency": 10, "timeout": 2 + }, + "auth": { + "enabled": true, + "username": "admin", + "password": "admin123" } } diff --git a/internal/config/config.go b/internal/config/config.go index 072cc21..f85f16e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,8 +3,8 @@ package config import ( "encoding/json" "fmt" - "os" "network-topology-discovery/pkg/models" + "os" ) // Config 应用配置 @@ -14,16 +14,17 @@ type Config struct { SSH SSHConfig `json:"ssh"` Web WebConfig `json:"web"` Scanner ScannerConfig `json:"scanner"` + Auth AuthConfig `json:"auth"` } // DeviceConfig 设备配置 type DeviceConfig struct { - IP string `json:"ip"` + IP string `json:"ip"` Type models.DeviceType `json:"type"` - Username string `json:"username"` - Password string `json:"password"` - KeyFile string `json:"key_file"` - Port int `json:"port"` + Username string `json:"username"` + Password string `json:"password"` + KeyFile string `json:"key_file"` + Port int `json:"port"` } // SSHConfig SSH配置 @@ -39,6 +40,13 @@ type WebConfig struct { Host string `json:"host"` } +// AuthConfig 认证配置 +type AuthConfig struct { + Enabled bool `json:"enabled"` + Username string `json:"username"` + Password string `json:"password"` +} + // ScannerConfig 扫描器配置 type ScannerConfig struct { Concurrency int `json:"concurrency"` @@ -122,4 +130,10 @@ func (c *Config) setDefaults() { if c.Scanner.Timeout == 0 { c.Scanner.Timeout = 2 } + if c.Auth.Enabled && c.Auth.Username == "" { + c.Auth.Username = "admin" + } + if c.Auth.Enabled && c.Auth.Password == "" { + c.Auth.Password = "admin" + } } diff --git a/internal/device/h3c.go b/internal/device/h3c.go index c84b849..c43181c 100644 --- a/internal/device/h3c.go +++ b/internal/device/h3c.go @@ -37,16 +37,27 @@ func (p *H3CParser) Parse(device *models.Device, outputs []string) error { // outputs[2] 是 display interface fmt.Printf("[H3C DEBUG] display interface output length: %d\n", len(outputs[2])) if len(outputs[2]) > 0 { - // 如果输出小于1000字节,完整输出以便调试 - if len(outputs[2]) <= 1000 { - fmt.Printf("[H3C DEBUG] Complete output:\n%s\n", outputs[2]) + if len(outputs[2]) <= 3000 { + fmt.Printf("[H3C DEBUG] Complete interface output:\n%s\n", outputs[2]) } else { - fmt.Printf("[H3C DEBUG] First 200 chars: %q\n", outputs[2][:200]) + fmt.Printf("[H3C DEBUG] First 3000 chars:\n%s\n", outputs[2][:3000]) } } else { fmt.Printf("[H3C DEBUG] display interface output is EMPTY!\n") } + // outputs[3] 是 display interface brief + fmt.Printf("[H3C BRIEF DEBUG] display interface brief output length: %d\n", len(outputs[3])) + if len(outputs[3]) > 0 { + if len(outputs[3]) <= 3000 { + fmt.Printf("[H3C BRIEF DEBUG] Complete brief output:\n%s\n", outputs[3]) + } else { + fmt.Printf("[H3C BRIEF DEBUG] First 3000 chars:\n%s\n", outputs[3][:3000]) + } + } else { + fmt.Printf("[H3C BRIEF DEBUG] display interface brief output is EMPTY!\n") + } + if outputs[2] == "" { fmt.Printf("Warning: 'display interface' output is empty for device %s\n", device.IP) } else { @@ -111,9 +122,9 @@ func (p *H3CParser) parseVersion(device *models.Device, output string) { } } - uptimeRegex := regexp.MustCompile(`uptime is\s+(\d+\s+\S+)`) + uptimeRegex := regexp.MustCompile(`uptime is\s+(.+)`) if matches := uptimeRegex.FindStringSubmatch(output); len(matches) > 1 { - device.Uptime = matches[1] + device.Uptime = strings.TrimSpace(matches[1]) } } @@ -142,6 +153,15 @@ func (p *H3CParser) parseInterfaces(interfaceOutput, briefOutput string) []model if brief, ok := briefMap[currentInterface.Name]; ok { currentInterface.IP = brief.IP + if currentInterface.Speed == "" { + currentInterface.Speed = brief.Speed + } + if currentInterface.Duplex == "" { + currentInterface.Duplex = brief.Duplex + } + if currentInterface.VLAN == "" { + currentInterface.VLAN = brief.VLAN + } } pendingInterfaceName = "" continue @@ -162,6 +182,15 @@ func (p *H3CParser) parseInterfaces(interfaceOutput, briefOutput string) []model if brief, ok := briefMap[currentInterface.Name]; ok { currentInterface.IP = brief.IP + if currentInterface.Speed == "" { + currentInterface.Speed = brief.Speed + } + if currentInterface.Duplex == "" { + currentInterface.Duplex = brief.Duplex + } + if currentInterface.VLAN == "" { + currentInterface.VLAN = brief.VLAN + } } pendingInterfaceName = "" continue @@ -192,9 +221,48 @@ func (p *H3CParser) parseInterfaces(interfaceOutput, briefOutput string) []model currentInterface.Mask = cidrToMask(matches[2]) } - if speedRegex := regexp.MustCompile(`(\d+)\s+(Kbps|Mbps|Gbps)`); speedRegex.MatchString(line) { + // 匹配速度格式1: Speed : 1000Mbps 或 Speed : 10Gbps + if speedRegex := regexp.MustCompile(`Speed\s*:\s*(\d+)\s*(Kbps|Mbps|Gbps)`); speedRegex.MatchString(line) { matches := speedRegex.FindStringSubmatch(line) - currentInterface.Speed = matches[1] + " " + matches[2] + currentInterface.Speed = matches[1] + matches[2] + } + // 匹配速度格式2: Speed: 1000, Loopback: not set (纯数字Mbps) + if speedRegex2 := regexp.MustCompile(`Speed\s*:\s*(\d+)(?:,|$)`); speedRegex2.MatchString(line) && currentInterface.Speed == "" { + matches := speedRegex2.FindStringSubmatch(line) + currentInterface.Speed = matches[1] + "Mbps" + } + + // 匹配双工: Duplex: Full 或 Duplex: Half + if duplexRegex := regexp.MustCompile(`Duplex\s*:\s*(\S+)`); duplexRegex.MatchString(line) && currentInterface.Duplex == "" { + currentInterface.Duplex = duplexRegex.FindStringSubmatch(line)[1] + } + + // 匹配VLAN信息: Port link-type: Access / Trunk / Hybrid + if linkTypeRegex := regexp.MustCompile(`Port link-type\s*:\s*(\S+)`); linkTypeRegex.MatchString(line) { + linkType := linkTypeRegex.FindStringSubmatch(line)[1] + currentInterface.VLAN = linkType + } + // 匹配Untagged VLAN: Untagged VLAN ID: 10 + if untaggedRegex := regexp.MustCompile(`Untagged VLAN ID\s*:\s*(\S+)`); untaggedRegex.MatchString(line) { + untagged := untaggedRegex.FindStringSubmatch(line)[1] + if untagged != "none" && untagged != "--" { + if currentInterface.VLAN != "" { + currentInterface.VLAN = currentInterface.VLAN + " " + untagged + } else { + currentInterface.VLAN = untagged + } + } + } + // 匹配Tagged VLAN: Tagged VLAN ID: 100-200 + if taggedRegex := regexp.MustCompile(`Tagged VLAN ID\s*:\s*(\S+)`); taggedRegex.MatchString(line) { + tagged := taggedRegex.FindStringSubmatch(line)[1] + if tagged != "none" && tagged != "--" { + if currentInterface.VLAN != "" { + currentInterface.VLAN = currentInterface.VLAN + " (T:" + tagged + ")" + } else { + currentInterface.VLAN = "T:" + tagged + } + } } } } @@ -276,19 +344,133 @@ func normalizeMACFormat(mac string) string { return mac } +// expandH3CInterfaceName 将H3C brief中的缩写接口名展开为全名 +func expandH3CInterfaceName(shortName string) string { + // GE1/0/10 -> GigabitEthernet1/0/10 + if strings.HasPrefix(shortName, "GE") { + return "GigabitEthernet" + shortName[2:] + } + // TGE1/0/52 -> Ten-GigabitEthernet1/0/52 + if strings.HasPrefix(shortName, "TGE") { + return "Ten-GigabitEthernet" + shortName[3:] + } + // FGE1/0/53 -> FortyGigE1/0/53 + if strings.HasPrefix(shortName, "FGE") { + return "FortyGigE" + shortName[3:] + } + // HGE1/0/1 -> HundredGigE1/0/1 + if strings.HasPrefix(shortName, "HGE") { + return "HundredGigE" + shortName[3:] + } + // XGE1/0/1 -> Ten-GigabitEthernet1/0/1 (有些型号用XGE) + if strings.HasPrefix(shortName, "XGE") { + return "Ten-GigabitEthernet" + shortName[3:] + } + // Vlan8 -> Vlan-interface8 + if strings.HasPrefix(shortName, "Vlan") { + return "Vlan-interface" + shortName[4:] + } + return shortName +} + func (p *H3CParser) parseInterfaceBrief(output string) map[string]models.Interface { interfaces := make(map[string]models.Interface) lines := strings.Split(output, "\n") + // 状态机: 0=未开始, 1=route mode数据, 2=bridge mode数据 + mode := 0 + for _, line := range lines { - fields := strings.Fields(line) - if len(fields) >= 4 { - iface := models.Interface{ - Name: fields[0], - IP: fields[1], - Status: strings.ToLower(fields[3]), + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "---") { + continue + } + + // 检测 route mode section + if strings.Contains(trimmed, "route mode") { + mode = 1 + continue + } + // 检测 bridge mode section + if strings.Contains(trimmed, "bridge mode") { + mode = 2 + continue + } + + // 跳过表头行 + fields := strings.Fields(trimmed) + if len(fields) > 0 && (fields[0] == "Interface" || fields[0] == "interface") { + continue + } + + // Route mode: Interface Link Protocol Primary IP Description + if mode == 1 && len(fields) >= 3 { + shortName := fields[0] + fullName := expandH3CInterfaceName(shortName) + ip := "" + if len(fields) >= 4 && fields[3] != "--" { + ip = fields[3] } - interfaces[iface.Name] = iface + iface := models.Interface{ + Name: fullName, + Status: strings.ToLower(fields[1]), + IP: ip, + } + interfaces[fullName] = iface + } + + // Bridge mode: Interface Link Speed Duplex Type PVID Description + if mode == 2 && len(fields) >= 5 { + shortName := fields[0] + fullName := expandH3CInterfaceName(shortName) + + speed := fields[2] + if speed == "auto" { + speed = "auto" + } + + duplex := fields[3] + switch duplex { + case "A": + duplex = "auto" + case "F(a)", "F": + duplex = "full" + case "H": + duplex = "half" + } + + // VLAN: Type(A/T/H) + PVID + vlan := "" + if len(fields) >= 5 { + linkType := fields[4] + switch linkType { + case "A": + vlan = "Access" + case "T": + vlan = "Trunk" + case "H": + vlan = "Hybrid" + } + } + if len(fields) >= 6 { + vlan = vlan + " " + fields[5] + } + + iface := models.Interface{ + Name: fullName, + Status: strings.ToLower(fields[1]), + Speed: speed, + Duplex: duplex, + VLAN: strings.TrimSpace(vlan), + } + + // 如果 route mode 已有此接口(通常不会有), 保留 IP 信息 + if existing, ok := interfaces[fullName]; ok { + if existing.IP != "" { + iface.IP = existing.IP + } + } + interfaces[fullName] = iface } } diff --git a/internal/device/huawei.go b/internal/device/huawei.go index 121d505..0917ef8 100644 --- a/internal/device/huawei.go +++ b/internal/device/huawei.go @@ -18,7 +18,7 @@ func (p *HuaweiParser) GetCommands() []string { return []string{ "display version", "display interface", - "display ip interface brief", + "display interface brief", "display lldp neighbor", } } @@ -84,6 +84,15 @@ func (p *HuaweiParser) parseInterfaces(interfaceOutput, briefOutput string) []mo if brief, ok := briefMap[currentInterface.Name]; ok { currentInterface.IP = brief.IP + if currentInterface.Speed == "" { + currentInterface.Speed = brief.Speed + } + if currentInterface.Duplex == "" { + currentInterface.Duplex = brief.Duplex + } + if currentInterface.VLAN == "" { + currentInterface.VLAN = brief.VLAN + } } } @@ -105,11 +114,41 @@ func (p *HuaweiParser) parseInterfaces(interfaceOutput, briefOutput string) []mo currentInterface.Mask = matches[2] } - // 带宽 - if speedRegex := regexp.MustCompile(`(\d+)\s+(Kbps|Mbps|Gbps)`); speedRegex.MatchString(line) { + // 带宽格式1: Speed : 1000Mbps + if speedRegex := regexp.MustCompile(`Speed\s*:\s*(\d+)\s*(Kbps|Mbps|Gbps)`); speedRegex.MatchString(line) { matches := speedRegex.FindStringSubmatch(line) + currentInterface.Speed = matches[1] + matches[2] + } + // 带宽格式2: BW 1000000 Kbit + if speedRegex2 := regexp.MustCompile(`BW\s+(\d+)\s+(Kbit|Mbit|Gbit)`); speedRegex2.MatchString(line) && currentInterface.Speed == "" { + matches := speedRegex2.FindStringSubmatch(line) currentInterface.Speed = matches[1] + " " + matches[2] } + + // VLAN信息: Port link-type + if linkTypeRegex := regexp.MustCompile(`Port link-type\s*:\s*(\S+)`); linkTypeRegex.MatchString(line) { + currentInterface.VLAN = linkTypeRegex.FindStringSubmatch(line)[1] + } + if untaggedRegex := regexp.MustCompile(`Untagged VLAN ID\s*:\s*(\S+)`); untaggedRegex.MatchString(line) { + untagged := untaggedRegex.FindStringSubmatch(line)[1] + if untagged != "none" && untagged != "--" { + if currentInterface.VLAN != "" { + currentInterface.VLAN = currentInterface.VLAN + " " + untagged + } else { + currentInterface.VLAN = untagged + } + } + } + if taggedRegex := regexp.MustCompile(`Tagged VLAN ID\s*:\s*(\S+)`); taggedRegex.MatchString(line) { + tagged := taggedRegex.FindStringSubmatch(line)[1] + if tagged != "none" && tagged != "--" { + if currentInterface.VLAN != "" { + currentInterface.VLAN = currentInterface.VLAN + " (T:" + tagged + ")" + } else { + currentInterface.VLAN = "T:" + tagged + } + } + } } } @@ -124,15 +163,85 @@ func (p *HuaweiParser) parseInterfaceBrief(output string) map[string]models.Inte interfaces := make(map[string]models.Interface) lines := strings.Split(output, "\n") + mode := 0 // 0=未开始, 1=route mode, 2=bridge mode for _, line := range lines { - fields := strings.Fields(line) - if len(fields) >= 4 { - iface := models.Interface{ - Name: fields[0], - IP: fields[1], - Status: strings.ToLower(fields[3]), + trimmed := strings.TrimSpace(line) + if trimmed == "" || strings.HasPrefix(trimmed, "---") { + continue + } + + if strings.Contains(trimmed, "route mode") { + mode = 1 + continue + } + if strings.Contains(trimmed, "bridge mode") { + mode = 2 + continue + } + + fields := strings.Fields(trimmed) + if len(fields) > 0 && (fields[0] == "Interface" || fields[0] == "interface") { + continue + } + + // Route mode: Interface Link Protocol Primary IP Description + if mode == 1 && len(fields) >= 3 { + fullName := expandH3CInterfaceName(fields[0]) + ip := "" + if len(fields) >= 4 && fields[3] != "--" { + ip = fields[3] } - interfaces[iface.Name] = iface + iface := models.Interface{ + Name: fullName, + Status: strings.ToLower(fields[1]), + IP: ip, + } + interfaces[fullName] = iface + } + + // Bridge mode: Interface Link Speed Duplex Type PVID Description + if mode == 2 && len(fields) >= 5 { + fullName := expandH3CInterfaceName(fields[0]) + + speed := fields[2] + duplex := fields[3] + switch duplex { + case "A": + duplex = "auto" + case "F(a)", "F": + duplex = "full" + case "H": + duplex = "half" + } + + vlan := "" + if len(fields) >= 5 { + switch fields[4] { + case "A": + vlan = "Access" + case "T": + vlan = "Trunk" + case "H": + vlan = "Hybrid" + } + } + if len(fields) >= 6 { + vlan = vlan + " " + fields[5] + } + + iface := models.Interface{ + Name: fullName, + Status: strings.ToLower(fields[1]), + Speed: speed, + Duplex: duplex, + VLAN: strings.TrimSpace(vlan), + } + if existing, ok := interfaces[fullName]; ok { + if existing.IP != "" { + iface.IP = existing.IP + } + } + interfaces[fullName] = iface } } diff --git a/internal/topology/builder.go b/internal/topology/builder.go index 9139f71..f9f2ed5 100644 --- a/internal/topology/builder.go +++ b/internal/topology/builder.go @@ -32,6 +32,16 @@ func (b *Builder) AddDevices(devices []models.Device) { b.devices = append(b.devices, devices...) } +// RemoveDevice 根据ID或IP移除设备 +func (b *Builder) RemoveDevice(id string) { + for i, d := range b.devices { + if d.ID == id || d.IP == id { + b.devices = append(b.devices[:i], b.devices[i+1:]...) + return + } + } +} + // Build 构建拓扑图 func (b *Builder) Build() models.TopologyGraph { graph := models.TopologyGraph{ diff --git a/pkg/models/models.go b/pkg/models/models.go index 421e5fd..4905363 100644 --- a/pkg/models/models.go +++ b/pkg/models/models.go @@ -41,6 +41,7 @@ type Interface struct { Speed string `json:"speed"` Duplex string `json:"duplex"` MTU int `json:"mtu"` + VLAN string `json:"vlan"` // VLAN信息(PVID/Access/Trunk) InBytes int64 `json:"in_bytes"` OutBytes int64 `json:"out_bytes"` InPackets int64 `json:"in_packets"` diff --git a/web/css/style.css b/web/css/style.css index bbd0b23..eea6f91 100644 --- a/web/css/style.css +++ b/web/css/style.css @@ -82,6 +82,16 @@ header h1 { color: white; } +.btn-secondary { + background: #607D8B; + color: white; +} + +.btn-danger { + background: #f44336; + color: white; +} + .main-content { display: flex; flex: 1; @@ -290,17 +300,30 @@ header h1 { /* SSH终端样式 */ .terminal-modal-content { - width: 800px; - max-width: 90vw; + width: 95vw; + max-width: 1200px; + margin: 20px auto; + max-height: 90vh; + display: flex; + flex-direction: column; + cursor: default; +} + +.terminal-modal-content .modal-header-drag { + cursor: move; + padding-bottom: 10px; + border-bottom: 1px solid #eee; + margin-bottom: 5px; + user-select: none; } .terminal-container { width: 100%; - height: 500px; + height: calc(85vh - 80px); background: #1e1e1e; border-radius: 5px; overflow: hidden; - margin-top: 15px; + margin-top: 10px; } .terminal-status { diff --git a/web/index.html b/web/index.html index 5d62173..d24fcf5 100644 --- a/web/index.html +++ b/web/index.html @@ -23,6 +23,7 @@ + @@ -84,8 +85,10 @@ + + + `).join('')} @@ -784,4 +842,69 @@ function closeTerminal() { } document.getElementById('modal-terminal').classList.remove('active'); document.getElementById('terminal-container').innerHTML = ''; + // 重置终端模态框位置 + var modal = document.querySelector('.terminal-modal-content'); + if (modal) { + modal.style.position = ''; + modal.style.left = ''; + modal.style.top = ''; + modal.style.margin = ''; + } +} + +// 删除设备 +async function deleteDevice(deviceId) { + if (!confirm('确定要删除设备 ' + deviceId + ' 吗?')) return; + try { + const response = await fetch(`/api/device/${deviceId}`, { + method: 'DELETE' + }); + if (response.ok) { + alert('删除成功'); + document.getElementById('detail-panel').classList.remove('active'); + // 重新加载拓扑和设备列表 + loadTopology(); + loadDeviceList(); + } else { + alert('删除失败'); + } + } catch (error) { + alert('删除失败: ' + error.message); + } +} + +// 打开编辑设备模态框 +function openEditDevice(id, hostname, type) { + document.getElementById('edit-device-id').value = id; + document.getElementById('edit-hostname').value = hostname; + document.getElementById('edit-type').value = type; + document.getElementById('modal-edit-device').classList.add('active'); +} + +// 保存编辑设备 +async function saveEditDevice(event) { + event.preventDefault(); + const id = document.getElementById('edit-device-id').value; + const hostname = document.getElementById('edit-hostname').value; + const type = document.getElementById('edit-type').value; + + try { + const response = await fetch(`/api/device/${id}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ hostname, type }) + }); + if (response.ok) { + alert('修改成功'); + document.getElementById('modal-edit-device').classList.remove('active'); + document.getElementById('detail-panel').classList.remove('active'); + loadTopology(); + loadDeviceList(); + } else { + const data = await response.json(); + alert('修改失败: ' + (data.error || '未知错误')); + } + } catch (error) { + alert('修改失败: ' + error.message); + } } diff --git a/web/login.html b/web/login.html new file mode 100644 index 0000000..e01940b --- /dev/null +++ b/web/login.html @@ -0,0 +1,137 @@ + + + + + + 登录 - 网络拓扑发现系统 + + + +
+

🌐 网络拓扑发现系统

+

请登录以继续

+
+
+ + +
+
+ + +
+ +
+
+
+ + +