4 Commits

Author SHA1 Message Date
Your Name a7e51c5bea feat: 优化拓扑匹配策略,使用12字符MAC前缀提高匹配精度 2026-04-27 18:32:29 +08:00
Your Name 07adc3ac5c feat: 修复网络拓扑匹配逻辑,使用双向LLDP对称匹配策略 2026-04-27 00:02:09 +08:00
Your Name 606e29a53c 优化设备类型顺序:H3C优先 2026-04-26 22:21:50 +08:00
Your Name 2a97f458a9 prod 2026-04-26 22:00:03 +08:00
11 changed files with 1076 additions and 101 deletions
+216 -15
View File
@@ -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("<h1>网络拓扑发现系统</h1><p>Web界面文件未找到</p>"))
})
}
// 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 {
+5
View File
@@ -30,5 +30,10 @@
"scanner": {
"concurrency": 10,
"timeout": 2
},
"auth": {
"enabled": true,
"username": "admin",
"password": "admin123"
}
}
+20 -6
View File
@@ -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"
}
}
+197 -15
View File
@@ -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
}
}
+119 -10
View File
@@ -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
}
}
+78 -45
View File
@@ -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{
@@ -147,49 +157,90 @@ func (b *Builder) Build() models.TopologyGraph {
}
}
// 策略3b: 通过MAC前缀匹配(改进:排除歧义前缀
// 当精确MAC匹配失败时,尝试通过MAC前缀匹配
// 但如果同一前缀匹配到多台设备,则跳过(避免错误连接)
// 策略3b: MAC前缀匹配(使用12字符前缀 - 更精确
// 同品牌设备虽然4字符前缀相同,但12字符前缀通常不同
if targetIP == "" && neighbor.RemoteMAC != "" {
neighborMACPrefix := getMACPrefix(neighbor.RemoteMAC)
fmt.Printf(" Trying MAC prefix match: %s (prefix: %s)\n", neighbor.RemoteMAC, neighborMACPrefix)
// 先统计有多少台设备匹配此MAC前缀
type prefixMatch struct {
ip string
matchingMACs int
// 使用12字符前缀(例如:642f-c7e0-03
macPrefix := ""
if len(neighbor.RemoteMAC) >= 12 {
macPrefix = neighbor.RemoteMAC[:12]
} else {
macPrefix = neighbor.RemoteMAC
}
var matches []prefixMatch
fmt.Printf(" Trying MAC prefix match (12 chars): %s (prefix: %s)\n", neighbor.RemoteMAC, macPrefix)
var matchedDevices []string
for _, d := range b.devices {
if d.IP == device.IP {
continue // 跳过自己
}
// 检查设备d的MAC地址是否有匹配的前缀
matchingMACs := 0
for _, mac := range d.MACAddresses {
if getMACPrefix(mac) == neighborMACPrefix {
if len(mac) >= 12 && mac[:12] == macPrefix {
matchingMACs++
}
}
if matchingMACs >= 3 {
matches = append(matches, prefixMatch{ip: d.IP, matchingMACs: matchingMACs})
matchedDevices = append(matchedDevices, d.IP)
}
}
// 只唯一匹配时使用前缀匹配
if len(matches) == 1 && getSubnet(matches[0].ip) == getSubnet(device.IP) {
targetIP = matches[0].ip
matchMethod = fmt.Sprintf("MAC-prefix(%s)", neighborMACPrefix)
fmt.Printf(" ✓ Matched by MAC prefix: %s (device has %d MACs with prefix %s, same subnet) -> %s\n",
neighbor.RemoteMAC, matches[0].matchingMACs, neighborMACPrefix, targetIP)
} else if len(matches) > 1 {
fmt.Printf(" ✗ Skipping MAC prefix match: %d devices share prefix %s (ambiguous)\n", len(matches), neighborMACPrefix)
// 只唯一匹配时才建立连接
if len(matchedDevices) == 1 {
targetIP = matchedDevices[0]
matchMethod = fmt.Sprintf("MAC-prefix-12(%s)", macPrefix)
fmt.Printf(" ✓ Matched by MAC prefix-12 (unique): %s -> %s\n", neighbor.RemoteMAC, targetIP)
} else if len(matchedDevices) > 1 {
fmt.Printf(" ✗ Ambiguous MAC prefix-12 match: %s matched %v\n", macPrefix, matchedDevices)
} else {
fmt.Printf(" ✗ No device matches MAC prefix-12 %s\n", macPrefix)
}
}
// 策略3c: LLDP接口匹配(改进 - 单向但要求唯一性)
// 如果设备A的LLDP信息显示它连接到接口Y
// 而设备B有接口Y,则A连接到B
// 但如果有多个设备都有接口Y,则不匹配(避免歧义)
if targetIP == "" && neighbor.RemoteMAC != "" && neighbor.RemoteInterface != "" {
fmt.Printf(" Trying LLDP interface match: looking for device with interface %s\n", neighbor.RemoteInterface)
var matchedDevices []string
for _, d := range b.devices {
if d.IP == device.IP {
continue // 跳过自己
}
// 检查设备d是否有这个接口
for _, iface := range d.Interfaces {
if iface.Name == neighbor.RemoteInterface {
matchedDevices = append(matchedDevices, d.IP)
break
}
}
}
// 只有唯一匹配时才建立连接
if len(matchedDevices) == 1 {
targetIP = matchedDevices[0]
matchMethod = fmt.Sprintf("LLDP-interface(%s->%s)", neighbor.LocalInterface, neighbor.RemoteInterface)
fmt.Printf(" ✓ Matched by LLDP interface (unique): %s %s -> %s %s\n",
device.IP, neighbor.LocalInterface, targetIP, neighbor.RemoteInterface)
} else if len(matchedDevices) > 1 {
fmt.Printf(" ✗ Ambiguous: multiple devices have interface %s: %v\n",
neighbor.RemoteInterface, matchedDevices)
} else {
fmt.Printf(" ✗ No device found with interface %s\n", neighbor.RemoteInterface)
}
}
// 策略4: 通过本地接口IP网段匹配(新增)
// 注意:此策略容易产生误匹配,仅在必要时使用
if targetIP == "" {
// 查找本地接口的IP地址
localInterfaceIP := ""
@@ -201,7 +252,7 @@ func (b *Builder) Build() models.TopologyGraph {
}
if localInterfaceIP != "" {
fmt.Printf(" Trying subnet match: local interface %s has IP %s\n",
fmt.Printf(" Trying subnet match (risky): local interface %s has IP %s\n",
neighbor.LocalInterface, localInterfaceIP)
// 计算本地接口的网段
@@ -217,7 +268,7 @@ func (b *Builder) Build() models.TopologyGraph {
if getSubnet(d.IP) == localSubnet {
targetIP = d.IP
matchMethod = "subnet(management IP)"
fmt.Printf(" Matched by subnet: %s in %s\n", d.IP, localSubnet)
fmt.Printf(" Matched by subnet (risky): %s in %s\n", d.IP, localSubnet)
break
}
@@ -226,7 +277,7 @@ func (b *Builder) Build() models.TopologyGraph {
if iface.IP != "" && getSubnet(iface.IP) == localSubnet {
targetIP = d.IP
matchMethod = fmt.Sprintf("subnet(interface %s)", iface.Name)
fmt.Printf(" Matched by subnet: %s (%s) in %s\n",
fmt.Printf(" Matched by subnet (risky): %s (%s) in %s\n",
d.IP, iface.Name, localSubnet)
break
}
@@ -236,27 +287,9 @@ func (b *Builder) Build() models.TopologyGraph {
}
}
} else {
// 策略4b: 本地接口没有IP,尝试使用设备管理IP进行子网匹配(新增
// 注意:只有当该网段只有2台设备时才使用此策略(点对点连接)
fmt.Printf(" Trying subnet match with management IP: %s\n", device.IP)
localSubnet := getSubnet(device.IP)
// 统计在该网段的设备数量
var devicesInSubnet []string
for _, d := range b.devices {
if d.IP != device.IP && getSubnet(d.IP) == localSubnet {
devicesInSubnet = append(devicesInSubnet, d.IP)
}
}
// 只有当网段中恰好有1台其他设备时才匹配(点对点)
if len(devicesInSubnet) == 1 {
targetIP = devicesInSubnet[0]
matchMethod = "subnet(management IP both sides)"
fmt.Printf(" ✓ Matched by management subnet: %s in %s (only device in subnet)\n", targetIP, localSubnet)
} else if len(devicesInSubnet) > 1 {
fmt.Printf(" ✗ Skipping subnet match: %d devices in subnet %s (ambiguous)\n", len(devicesInSubnet)+1, localSubnet)
}
// 策略4b: 本地接口没有IP,尝试使用设备管理IP进行子网匹配(高风险策略 - 已禁用
// 此策略容易产生错误连接,暂时禁用
fmt.Printf(" ✗ Skipping subnet match with management IP (disabled - too risky)\n")
}
}
+1
View File
@@ -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"`
+60 -4
View File
@@ -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;
@@ -90,6 +100,8 @@ header h1 {
.sidebar {
width: 300px;
min-width: 200px;
max-width: 600px;
background: white;
padding: 20px;
overflow-y: auto;
@@ -180,6 +192,7 @@ header h1 {
.content {
flex: 1;
position: relative;
min-width: 400px;
}
#cy {
@@ -190,17 +203,47 @@ header h1 {
.detail-panel {
width: 600px;
min-width: 300px;
max-width: 1000px;
background: white;
padding: 20px;
overflow-y: auto;
box-shadow: -2px 0 5px rgba(0,0,0,0.1);
display: none;
position: relative;
}
.detail-panel.active {
display: block;
}
/* 拖拽手柄样式 */
.resizer {
width: 5px;
cursor: col-resize;
background: #e0e0e0;
position: relative;
z-index: 10;
transition: background 0.2s;
}
.resizer:hover,
.resizer.resizing {
background: #667eea;
}
.resizer::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 3px;
height: 30px;
background: rgba(0, 0, 0, 0.2);
border-radius: 2px;
}
.detail-panel h3 {
margin-bottom: 15px;
color: #667eea;
@@ -290,17 +333,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 {
+41 -5
View File
@@ -23,12 +23,13 @@
<button id="btn-scan" class="btn btn-primary">开始扫描</button>
<button id="btn-add-device" class="btn btn-success">添加设备</button>
<button id="btn-export" class="btn btn-info">导出拓扑</button>
<button id="btn-logout" class="btn btn-danger" style="margin-left:auto">登出</button>
</div>
</header>
<div class="main-content">
<!-- 侧边栏 -->
<aside class="sidebar">
<aside class="sidebar" id="sidebar">
<div class="panel">
<h3>扫描配置</h3>
<form id="scan-form">
@@ -68,11 +69,17 @@
</div>
</aside>
<!-- 左侧拖拽手柄 -->
<div class="resizer" id="resizer-left"></div>
<!-- 主内容区 -->
<main class="content">
<div id="cy"></div>
</main>
<!-- 右侧拖拽手柄 -->
<div class="resizer" id="resizer-right"></div>
<!-- 详情面板 -->
<aside class="detail-panel" id="detail-panel">
<h3>设备详情</h3>
@@ -84,8 +91,10 @@
<!-- SSH终端模态框 -->
<div id="modal-terminal" class="modal">
<div class="modal-content terminal-modal-content">
<span class="close-terminal">&times;</span>
<h2>SSH 终端 - <span id="terminal-device-name"></span></h2>
<div class="modal-header-drag">
<span class="close-terminal">&times;</span>
<h2 style="display:inline;margin:0">SSH 终端 - <span id="terminal-device-name"></span></h2>
</div>
<div id="terminal-container" class="terminal-container"></div>
<div id="terminal-status" class="terminal-status">已断开</div>
</div>
@@ -131,9 +140,9 @@
<div class="form-group">
<label for="device-type">设备类型:</label>
<select id="device-type" required>
<option value="cisco">Cisco</option>
<option value="huawei">华为</option>
<option value="h3c">H3C</option>
<option value="huawei">华为</option>
<option value="cisco">Cisco</option>
<option value="asa">ASA防火墙</option>
<option value="linux">Linux服务器</option>
<option value="windows">Windows Server</option>
@@ -167,6 +176,33 @@
</div>
</div>
<!-- 编辑设备模态框 -->
<div id="modal-edit-device" class="modal">
<div class="modal-content">
<span class="close-edit-device">&times;</span>
<h2>编辑设备</h2>
<form id="edit-device-form" onsubmit="saveEditDevice(event)">
<input type="hidden" id="edit-device-id">
<div class="form-group">
<label for="edit-hostname">主机名:</label>
<input type="text" id="edit-hostname" required placeholder="例: BJ-SW01">
</div>
<div class="form-group">
<label for="edit-type">设备类型:</label>
<select id="edit-type" required>
<option value="h3c">H3C</option>
<option value="huawei">Huawei</option>
<option value="cisco">Cisco</option>
<option value="asa">ASA</option>
<option value="linux">Linux</option>
<option value="windows">Windows</option>
</select>
</div>
<button type="submit" class="btn btn-primary" style="width:100%">保存</button>
</form>
</div>
</div>
<!-- 选择设备模态框 -->
<div id="modal-select-devices" class="modal">
<div class="modal-content select-devices-modal-content">
+202 -1
View File
@@ -98,6 +98,11 @@ function initEventListeners() {
document.getElementById('modal-new-topology').classList.remove('active');
});
// 关闭编辑设备模态框
document.querySelector('.close-edit-device').addEventListener('click', function() {
document.getElementById('modal-edit-device').classList.remove('active');
});
// 新建拓扑表单
document.getElementById('new-topology-form').addEventListener('submit', createTopology);
@@ -120,8 +125,47 @@ function initEventListeners() {
// 导出按钮
document.getElementById('btn-export').addEventListener('click', exportTopology);
// 登出按钮
var logoutBtn = document.getElementById('btn-logout');
if (logoutBtn) {
logoutBtn.addEventListener('click', function() {
window.location.href = '/api/logout';
});
}
// SSH终端相关
document.querySelector('.close-terminal').addEventListener('click', closeTerminal);
// 终端模态框拖动功能
(function() {
var dragHandle = document.querySelector('.modal-header-drag');
var modal = document.querySelector('.terminal-modal-content');
var isDragging = false;
var offsetX = 0, offsetY = 0;
if (dragHandle && modal) {
dragHandle.addEventListener('mousedown', function(e) {
if (e.target.classList.contains('close-terminal')) return;
isDragging = true;
var rect = modal.getBoundingClientRect();
offsetX = e.clientX - rect.left;
offsetY = e.clientY - rect.top;
modal.style.margin = '0';
modal.style.position = 'absolute';
modal.style.left = rect.left + 'px';
modal.style.top = rect.top + 'px';
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
modal.style.left = (e.clientX - offsetX) + 'px';
modal.style.top = (e.clientY - offsetY) + 'px';
});
document.addEventListener('mouseup', function() {
isDragging = false;
});
}
})();
document.querySelector('.close-ssh-creds').addEventListener('click', function() {
document.getElementById('modal-ssh-creds').classList.remove('active');
});
@@ -338,6 +382,14 @@ async function loadDeviceList() {
async function showDeviceDetail(deviceId) {
try {
const response = await fetch(`/api/device/${deviceId}`);
if (response.status === 401) {
window.location.href = '/login';
return;
}
if (!response.ok) {
console.error('获取设备详情失败:', response.status, response.statusText);
return;
}
const device = await response.json();
const detailPanel = document.getElementById('detail-panel');
@@ -351,7 +403,11 @@ async function showDeviceDetail(deviceId) {
<p><strong>类型:</strong> ${device.type}</p>
<p><strong>系统:</strong> ${device.os_version || 'N/A'}</p>
<p><strong>运行时间:</strong> ${device.uptime || 'N/A'}</p>
<button class="btn btn-primary" style="margin-top:10px;width:100%" onclick="openSSHTerminal('${device.ip}', '${device.hostname || device.ip}')">SSH 连接</button>
<div style="display:flex;gap:10px;margin-top:10px">
<button class="btn btn-primary" style="flex:1" onclick="openSSHTerminal('${device.ip}', '${device.hostname || device.ip}')">SSH 连接</button>
<button class="btn btn-secondary" style="flex:1" onclick="openEditDevice('${device.id}', '${device.hostname}', '${device.type}')">编辑</button>
<button class="btn btn-danger" style="flex:1" onclick="deleteDevice('${device.id}')">删除</button>
</div>
</div>
<div class="detail-section">
<h4>接口信息 (${device.interfaces.length})</h4>
@@ -363,6 +419,8 @@ async function showDeviceDetail(deviceId) {
<p>IP: ${iface.ip || 'N/A'}</p>
<p>MAC: ${iface.mac || 'N/A'}</p>
<p>速度: ${iface.speed || 'N/A'}</p>
<p>双工: ${iface.duplex || 'N/A'}</p>
<p>VLAN: ${iface.vlan || 'N/A'}</p>
</div>
</div>
`).join('')}
@@ -784,4 +842,147 @@ 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);
}
}
// 面板拖拽调整大小功能
(function() {
// 左侧面板拖拽
var resizerLeft = document.getElementById('resizer-left');
var sidebar = document.getElementById('sidebar');
if (resizerLeft && sidebar) {
var isResizingLeft = false;
resizerLeft.addEventListener('mousedown', function(e) {
isResizingLeft = true;
resizerLeft.classList.add('resizing');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isResizingLeft) return;
var newWidth = e.clientX;
var minWidth = 200;
var maxWidth = 600;
if (newWidth >= minWidth && newWidth <= maxWidth) {
sidebar.style.width = newWidth + 'px';
}
});
document.addEventListener('mouseup', function() {
if (isResizingLeft) {
isResizingLeft = false;
resizerLeft.classList.remove('resizing');
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
}
// 右侧面板拖拽
var resizerRight = document.getElementById('resizer-right');
var detailPanel = document.getElementById('detail-panel');
if (resizerRight && detailPanel) {
var isResizingRight = false;
resizerRight.addEventListener('mousedown', function(e) {
isResizingRight = true;
resizerRight.classList.add('resizing');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isResizingRight) return;
var containerWidth = document.querySelector('.main-content').offsetWidth;
var newWidth = containerWidth - e.clientX;
var minWidth = 300;
var maxWidth = 1000;
if (newWidth >= minWidth && newWidth <= maxWidth) {
detailPanel.style.width = newWidth + 'px';
}
});
document.addEventListener('mouseup', function() {
if (isResizingRight) {
isResizingRight = false;
resizerRight.classList.remove('resizing');
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
}
})();
+137
View File
@@ -0,0 +1,137 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 网络拓扑发现系统</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.login-card {
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 50px 40px;
width: 400px;
max-width: 90vw;
}
.login-card h1 {
text-align: center;
margin-bottom: 10px;
font-size: 24px;
color: #333;
}
.login-card p {
text-align: center;
color: #999;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 6px;
color: #555;
font-weight: 500;
}
.form-group input {
width: 100%;
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 15px;
transition: border-color 0.3s;
outline: none;
}
.form-group input:focus {
border-color: #667eea;
}
.login-btn {
width: 100%;
padding: 14px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: opacity 0.3s;
}
.login-btn:hover {
opacity: 0.9;
}
.login-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.error-msg {
color: #f44336;
text-align: center;
margin-top: 15px;
font-size: 14px;
display: none;
}
</style>
</head>
<body>
<div class="login-card">
<h1>🌐 网络拓扑发现系统</h1>
<p>请登录以继续</p>
<form id="login-form">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" id="username" name="username" required autofocus placeholder="请输入用户名">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" id="password" name="password" required placeholder="请输入密码">
</div>
<button type="submit" class="login-btn" id="login-btn">登 录</button>
<div class="error-msg" id="error-msg"></div>
</form>
</div>
<script>
document.getElementById('login-form').addEventListener('submit', async function(e) {
e.preventDefault();
var btn = document.getElementById('login-btn');
var errEl = document.getElementById('error-msg');
btn.disabled = true;
btn.textContent = '登录中...';
errEl.style.display = 'none';
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
try {
var resp = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: username, password: password })
});
var data = await resp.json();
if (resp.ok && data.success) {
window.location.href = '/';
} else {
errEl.textContent = data.message || '登录失败';
errEl.style.display = 'block';
}
} catch (err) {
errEl.textContent = '网络错误,请重试';
errEl.style.display = 'block';
}
btn.disabled = false;
btn.textContent = '登 录';
});
</script>
</body>
</html>