Fix: 增强SSH会话管理和错误处理
- 添加会话创建重试机制(最多3次) - 允许部分命令失败而不中断整个扫描 - 改进错误提示和日志输出 - 解决H3C设备LLDP命令会话拒绝问题
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
package device
|
package device
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"network-topology-discovery/pkg/models"
|
"network-topology-discovery/pkg/models"
|
||||||
sshclient "network-topology-discovery/internal/ssh"
|
sshclient "network-topology-discovery/internal/ssh"
|
||||||
)
|
)
|
||||||
@@ -74,12 +75,17 @@ func DiscoverDevice(ip string, deviceType models.DeviceType, username, password
|
|||||||
// 获取命令列表
|
// 获取命令列表
|
||||||
commands := parser.GetCommands()
|
commands := parser.GetCommands()
|
||||||
|
|
||||||
// 执行命令
|
// 执行命令 - 允许部分命令失败
|
||||||
outputs, err := client.ExecuteCommands(commands)
|
outputs := make([]string, 0, len(commands))
|
||||||
if err != nil {
|
for _, cmd := range commands {
|
||||||
device.ScanStatus = "failed"
|
output, err := client.ExecuteCommand(cmd)
|
||||||
device.ErrorMessage = err.Error()
|
if err != nil {
|
||||||
return device, err
|
// 记录警告但继续执行其他命令
|
||||||
|
fmt.Printf("Warning: command '%s' failed: %v\n", cmd, err)
|
||||||
|
outputs = append(outputs, "")
|
||||||
|
} else {
|
||||||
|
outputs = append(outputs, output)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析输出
|
// 解析输出
|
||||||
|
|||||||
@@ -121,9 +121,25 @@ func (c *Client) ExecuteCommand(command string) (string, error) {
|
|||||||
return "", fmt.Errorf("not connected")
|
return "", fmt.Errorf("not connected")
|
||||||
}
|
}
|
||||||
|
|
||||||
session, err := c.client.NewSession()
|
// 重试机制,处理会话创建失败的情况
|
||||||
|
var session *ssh.Session
|
||||||
|
var err error
|
||||||
|
maxRetries := 3
|
||||||
|
|
||||||
|
for i := 0; i < maxRetries; i++ {
|
||||||
|
session, err = c.client.NewSession()
|
||||||
|
if err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果是会话拒绝错误,等待后重试
|
||||||
|
if i < maxRetries-1 {
|
||||||
|
time.Sleep(time.Duration(i+1) * 500 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("failed to create session: %w", err)
|
return "", fmt.Errorf("failed to create session after %d retries: %w", maxRetries, err)
|
||||||
}
|
}
|
||||||
defer session.Close()
|
defer session.Close()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user