cmd.go 1.16 KB
Newer Older
duanjinfei's avatar
duanjinfei committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
package operate

import (
	"example.com/m/log"
	"fmt"
	"github.com/go-cmd/cmd"
	"os/exec"
)

type Command struct {
	cmd        string
	params     []byte
	scriptPath string
}

func GetSystemCommand(cmd string, params []byte) *Command {
	return &Command{}
}

func (c *Command) ExecCommand(name string, param []string) {
	// 创建一个新的 cmd.Cmd 结构体,表示要执行的 curl 命令
	command := cmd.NewCmd(name, param...)

	// 阻塞并等待命令执行完成
	status := <-command.Start()

	// 检查命令执行的状态
	if status.Error != nil {
		fmt.Println("Error executing command:", status.Error)
		return
	}

	// 打印命令的标准输出
	if len(status.Stdout) > 0 {
		log.Info("Command output:", status.Stdout)
	}

	// 打印命令的标准错误
	if len(status.Stderr) > 0 {
		log.Error("Command error:", status.Stderr)
	}
}

func (c *Command) ExecShell() {
	// 使用 exec.Command 执行脚本文件
	shellCmd := exec.Command("sh", c.scriptPath)

	// 执行命令并捕获输出
	output, err := shellCmd.CombinedOutput()
	if err != nil {
		log.Error("Error executing script:", err)
		return
	}

	// 打印输出结果
	log.Info("Script output:", string(output))
}