prod
This commit is contained in:
+216
-15
@@ -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 {
|
||||
|
||||
@@ -30,5 +30,10 @@
|
||||
"scanner": {
|
||||
"concurrency": 10,
|
||||
"timeout": 2
|
||||
},
|
||||
"auth": {
|
||||
"enabled": true,
|
||||
"username": "admin",
|
||||
"password": "admin123"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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"`
|
||||
|
||||
+27
-4
@@ -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 {
|
||||
|
||||
+32
-2
@@ -23,6 +23,7 @@
|
||||
<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>
|
||||
|
||||
@@ -84,8 +85,10 @@
|
||||
<!-- SSH终端模态框 -->
|
||||
<div id="modal-terminal" class="modal">
|
||||
<div class="modal-content terminal-modal-content">
|
||||
<span class="close-terminal">×</span>
|
||||
<h2>SSH 终端 - <span id="terminal-device-name"></span></h2>
|
||||
<div class="modal-header-drag">
|
||||
<span class="close-terminal">×</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>
|
||||
@@ -167,6 +170,33 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 编辑设备模态框 -->
|
||||
<div id="modal-edit-device" class="modal">
|
||||
<div class="modal-content">
|
||||
<span class="close-edit-device">×</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="cisco">Cisco</option>
|
||||
<option value="huawei">Huawei</option>
|
||||
<option value="h3c">H3C</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">
|
||||
|
||||
+124
-1
@@ -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,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);
|
||||
}
|
||||
}
|
||||
|
||||
+137
@@ -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>
|
||||
Reference in New Issue
Block a user