fix: 远程命令直连SSH(去轮询) + 去掉无用命令分类
This commit is contained in:
1 parent
ed3bf59c3b
commit
b8b1a3d5f6
4 files changed
+70
-68
No files matched your search
@@ -254,3 +254,54 @@ func (h *AgentInstallHandler) BatchInstallAgent(c *gin.Context) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// RemoteExec 直连 SSH 执行命令(即时返回,无轮询)
|
||||
// POST /api/v1/agent/exec
|
||||
func (h *AgentInstallHandler) RemoteExec(c *gin.Context) {
|
||||
var req struct {
|
||||
Hostname string `json:"hostname"`
|
||||
Command string `json:"command"`
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Hostname == "" || req.Command == "" {
|
||||
c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请提供 hostname 和 command"})
|
||||
return
|
||||
}
|
||||
if req.Timeout <= 0 {
|
||||
req.Timeout = 30
|
||||
}
|
||||
|
||||
var server models.Server
|
||||
if err := h.db.Where("hostname = ? OR ip = ?", req.Hostname, req.Hostname).First(&server).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "未找到服务器: " + req.Hostname})
|
||||
return
|
||||
}
|
||||
|
||||
client, err := sshDial(server)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, models.Response{Code: 500, Message: "SSH连接失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
type result struct {
|
||||
out string
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
out, err := runSSHCommand(client, req.Command)
|
||||
done <- result{out, err}
|
||||
}()
|
||||
|
||||
select {
|
||||
case r := <-done:
|
||||
if r.err != nil {
|
||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "执行完成", Data: gin.H{"output": r.out, "error": r.err.Error()}})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, models.Response{Code: 200, Message: "执行成功", Data: gin.H{"output": r.out}})
|
||||
case <-time.After(time.Duration(req.Timeout) * time.Second):
|
||||
c.JSON(http.StatusOK, models.Response{Code: 408, Message: fmt.Sprintf("命令执行超时(%ds)", req.Timeout)})
|
||||
}
|
||||
}
|
||||
@@ -142,6 +142,9 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c
|
||||
agentInstallHandler := handlers.NewAgentInstallHandler(db)
|
||||
servers.POST("/:id/install-agent", agentInstallHandler.InstallAgent)
|
||||
servers.POST("/install-agent", agentInstallHandler.BatchInstallAgent)
|
||||
|
||||
// Agent 远程命令执行
|
||||
agentGroup.POST("/exec", agentInstallHandler.RemoteExec)
|
||||
}
|
||||
|
||||
// 云账号路由
|
||||
|
||||
Reference in new issue
Block a user