82 lines
1.9 KiB
Go
82 lines
1.9 KiB
Go
package command
|
|
|
|
import (
|
|
"iptables-helper/pkg/logger"
|
|
"os"
|
|
"os/exec"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
var log = logger.Log()
|
|
|
|
type Command interface {
|
|
execute(command string) (string, error)
|
|
}
|
|
|
|
type Commander struct {
|
|
}
|
|
|
|
func (c *Commander) Execute(command string) {
|
|
command = strings.TrimSpace(command)
|
|
commands := strings.SplitN(command, " ", 2)
|
|
order := commands[0]
|
|
|
|
var args []string
|
|
if len(commands) > 1 {
|
|
argStr := commands[1]
|
|
|
|
reg, _ := regexp.Compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'")
|
|
tmp := reg.FindAllString(argStr, -1)
|
|
|
|
for _, arg := range tmp {
|
|
// 双引号 则 去除 以用于 cmd /c 或 /bin/sh -c 传入字符串命令/参数使用
|
|
// 单引号 则 不去除 按普通参数处理
|
|
if strings.HasPrefix(arg, "\"") && strings.HasSuffix(arg, "\"") {
|
|
args = append(args, arg[1:len(arg)-1])
|
|
} else {
|
|
args = append(args, arg)
|
|
}
|
|
}
|
|
}
|
|
|
|
log.Infof("[+] 执行命令 %s %v\n", order, args)
|
|
cmd := exec.Command(order, args...)
|
|
cmd.Stdout = os.Stdout
|
|
cmd.Stderr = os.Stderr
|
|
err := cmd.Run()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func (c *Commander) ExecuteWithResult(command string) (string, error) {
|
|
command = strings.TrimSpace(command)
|
|
commands := strings.SplitN(command, " ", 2)
|
|
order := commands[0]
|
|
|
|
var args []string
|
|
if len(commands) > 1 {
|
|
argStr := commands[1]
|
|
|
|
reg, _ := regexp.Compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'")
|
|
tmp := reg.FindAllString(argStr, -1)
|
|
|
|
for _, arg := range tmp {
|
|
// 双引号 则 去除 以用于 cmd /c 或 /bin/sh -c 传入字符串命令/参数使用
|
|
// 单引号 则 不去除 按普通参数处理
|
|
if strings.HasPrefix(arg, "\"") && strings.HasSuffix(arg, "\"") {
|
|
args = append(args, arg[1:len(arg)-1])
|
|
} else {
|
|
args = append(args, arg)
|
|
}
|
|
}
|
|
}
|
|
|
|
log.Infof("[+] 执行命令 %s %v\n", order, args)
|
|
cmd := exec.Command(order, args...)
|
|
|
|
out, err := cmd.Output()
|
|
return string(out), err
|
|
}
|