func Exec(command string) error { in := bytes.NewBuffer(nil) cmd := exec.Command("sh") cmd.Stdin = in in.WriteString(command) in.WriteString("exit\n") if err := cmd.Run(); err != nil { return err } return nil } func (h *Headscale) GetRoutesIp(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var req GetRoutesIpReq jsonerr := json.NewDecoder(r.Body).Decode(&req) if jsonerr != nil { http.Error(w, "Failed to decode JSON", http.StatusBadRequest) return } response := GetRoutesIpResp{} cmd := exec.Command("/root/digital_guard/headscale", "routes", "list") routesCmdString := cmd.String() output, cmderr := cmd.CombinedOutput() if cmderr != nil { log.Info().Msgf("Failed to execute shell command: %s", cmderr.Error()) response.Messge = append(response.Messge, routesCmdString) } data := string(output) lines := strings.Split(data, "\n") for _, ipToFinds := range req.Ip { for _, line := range lines { if strings.Contains(line, ipToFinds) && strings.Contains(line, req.Name) { fields := strings.Fields(line) if len(fields) >= 3 { id := fields[0] // s := []string{"/root/digital_guard/headscale routes enable --route ", "1", " set-Advertised=true set-Enabled=true"} // s[1] = id // strCmdbyte := strings.Join(s, "") // errs := Exec(strCmdbyte) errs := Exec("/root/digital_guard/headscale routes enable --route " + id + " set-Advertised=true set-Enabled=true") if errs != nil { // log.Info().Msg(fmt.Sprintf("-----------err------shell命令----------: %s", strCmdbyte)) // response.Messge = append(response.Messge, strCmdbyte) } else { response.Code = 1 } } } } } respJSON, err := json.Marshal(response) if err != nil { http.Error(w, "Failed to encode JSON", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) w.Write(respJSON) } 这样执行的linux命令失败
时间: 2024-03-17 17:46:58 浏览: 22
根据您提供的代码,我看到您尝试执行的 Linux 命令是 `/root/digital_guard/headscale routes enable --route <id> set-Advertised=true set-Enabled=true`,您说该命令执行失败,但是没有提供具体的错误信息。如果您能够提供该命令执行失败的具体错误信息,我可以更好地帮助您解决问题。
除此之外,您的代码中使用了 `exec.Command` 来执行命令,但是并没有设置 `cmd.Dir` 来指定命令执行的工作目录。如果命令需要在特定的工作目录下执行,您可以设置 `cmd.Dir` 来指定。例如:
```
cmd := exec.Command("ls")
cmd.Dir = "/home/user"
output, err := cmd.CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
```
另外,执行 Shell 命令时最好使用 `bash` 而不是 `sh`,因为 `sh` 的行为可能会与您预期的不同。如果您的系统上没有 `bash`,可以尝试安装一下。
相关问题
package main import ( "bytes" "encoding/json" "fmt" "net/http" "github.com/gin-gonic/gin" ) type AlertData struct { Receiver string `json:"receiver"` Status string `json:"status"` Alerts []Alert `json:"alerts"` GroupLabels map[string]string `json:"groupLabels"` CommonLabels map[string]string `json:"commonLabels"` CommonAnnotations map[string]string `json:"commonAnnotations"` ExternalURL string `json:"externalURL"` } type Alert struct { Status string `json:"status"` Labels map[string]string `json:"labels"` Annotations map[string]string `json:"annotations"` } func main() { router := gin.Default() router.POST("/webhook", handleWebhook) router.Run(":8080") } func handleWebhook(c *gin.Context) { var alertData AlertData err := c.BindJSON(&alertData) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Error decoding JSON"}) return } // Process the received alert data for _, alert := range alertData.Alerts { // Extract information from alert alertName := alert.Labels["alertname"] instance := alert.Labels["instance"] severity := alert.CommonLabels["severity"] description := alert.Annotations["description"] summary := alert.Annotations["summary"] // Compose the message to be sent to Enterprise WeChat group using Markdown format message := fmt.Sprintf(`**Alert Name:** %s **Instance:** %s **Severity:** %s **Description:** %s **Summary:** %s`, alertName, instance, severity, description, summary) // Send the message to Enterprise WeChat group using the WeChat bot API sendToEnterpriseWeChatGroup(message) } c.JSON(http.StatusOK, gin.H{"message": "Alerts processed successfully"}) } func sendToEnterpriseWeChatGroup(message string) { // Replace 'YOUR_WECHAT_BOT_URL' with the actual URL of your Enterprise WeChat bot wechatBotURL := "YOUR_WECHAT_BOT_URL" data := map[string]interface{}{ "msgtype": "markdown", "markdown": map[string]string{ "content": message, }, } jsonData, _ := json.Marshal(data) _, err := http.Post(wechatBotURL, "application/json", bytes.NewReader(jsonData)) if err != nil { fmt.Println("Error sending message to Enterprise WeChat group:", err) } } 将以上代码拆分成多个模块
将以上代码拆分为多个模块,可以按照以下方式进行组织:
**main.go:**
```go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.POST("/webhook", handleWebhook)
router.Run(":8080")
}
```
**alert.go:**
```go
package main
type AlertData struct {
Receiver string `json:"receiver"`
Status string `json:"status"`
Alerts []Alert `json:"alerts"`
GroupLabels map[string]string `json:"groupLabels"`
CommonLabels map[string]string `json:"commonLabels"`
CommonAnnotations map[string]string `json:"commonAnnotations"`
ExternalURL string `json:"externalURL"`
}
type Alert struct {
Status string `json:"status"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
}
```
**webhook.go:**
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
func handleWebhook(c *gin.Context) {
var alertData AlertData
err := c.BindJSON(&alertData)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Error decoding JSON"})
return
}
// Process the received alert data
for _, alert := range alertData.Alerts {
// Extract information from alert
alertName := alert.Labels["alertname"]
instance := alert.Labels["instance"]
severity := alert.CommonLabels["severity"]
description := alert.Annotations["description"]
summary := alert.Annotations["summary"]
// Compose the message to be sent to Enterprise WeChat group using Markdown format
message := fmt.Sprintf(`**Alert Name:** %s
**Instance:** %s
**Severity:** %s
**Description:** %s
**Summary:** %s`,
alertName, instance, severity, description, summary)
// Send the message to Enterprise WeChat group using the WeChat bot API
sendToEnterpriseWeChatGroup(message)
}
c.JSON(http.StatusOK, gin.H{"message": "Alerts processed successfully"})
}
```
**wechat.go:**
```go
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func sendToEnterpriseWeChatGroup(message string) {
// Replace 'YOUR_WECHAT_BOT_URL' with the actual URL of your Enterprise WeChat bot
wechatBotURL := "YOUR_WECHAT_BOT_URL"
data := map[string]interface{}{
"msgtype": "markdown",
"markdown": map[string]string{
"content": message,
},
}
jsonData, _ := json.Marshal(data)
_, err := http.Post(wechatBotURL, "application/json", bytes.NewReader(jsonData))
if err != nil {
fmt.Println("Error sending message to Enterprise WeChat group:", err)
}
}
```
通过将不同功能的代码拆分到不同的模块中,可以更好地组织代码,提高代码的可读性和可维护性。在`main.go`中导入其他模块,并在适当的地方调用相应的函数即可。
func UpdateUser() gin.HandlerFunc { return func(c *gin.Context) { username := c.Param("username") //username:=c.Query("username") var updatedUser User if err := c.ShouldBind(&updatedUser); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } for i, user := range usersDB { if user.Username == username { usersDB[i].Password = updatedUser.Password c.JSON(http.StatusOK, gin.H{"message": "User updated successfully"}) return } } c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) } }把里面的username := c.Param("username")改成username:=c.query("username)
如果将`username := c.Param("username")`改为`username := c.Query("username")`,则会从URL查询参数中获取`username`的值,而不是从URL路径参数中获取。因此,需要将路由中的`:username`改为`?username=`的形式,即将路由中的`/users/:username`改为`/users`。
修改后的代码如下:
```
func UpdateUser() gin.HandlerFunc {
return func(c *gin.Context) {
username := c.Query("username")
var updatedUser User
if err := c.ShouldBind(&updatedUser); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
for i, user := range usersDB {
if user.Username == username {
usersDB[i].Password = updatedUser.Password
c.JSON(http.StatusOK, gin.H{"message": "User updated successfully"})
return
}
}
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
}
}
```
但需要注意的是,如果将路由中的`:username`改为`?username=`的形式,则无法使用`c.Param("username")`获取URL路径参数的值,因为URL路径参数已经被改为了查询参数。