Execf 安全执行 shell 命令
(shell string, args ...any)
| 54 | |
| 55 | // Execf 安全执行 shell 命令 |
| 56 | func Execf(shell string, args ...any) (string, error) { |
| 57 | if !preCheckArg(args) { |
| 58 | return "", errors.New("command contains illegal characters") |
| 59 | } |
| 60 | if len(args) > 0 { |
| 61 | shell = fmt.Sprintf(shell, args...) |
| 62 | } |
| 63 | |
| 64 | _ = os.Setenv("LC_ALL", "C") |
| 65 | cmd := exec.Command("bash", "-c", shell) |
| 66 | |
| 67 | var stdout, stderr bytes.Buffer |
| 68 | cmd.Stdout = &stdout |
| 69 | cmd.Stderr = &stderr |
| 70 | |
| 71 | if err := cmd.Run(); err != nil { |
| 72 | return strings.TrimSpace(stdout.String()), fmt.Errorf("run %s failed, err: %w, stderr: %s", shell, err, strings.TrimSpace(stderr.String())) |
| 73 | } |
| 74 | |
| 75 | return strings.TrimSpace(stdout.String()), nil |
| 76 | } |
| 77 | |
| 78 | // ExecfAsync 异步执行 shell 命令 |
| 79 | func ExecfAsync(shell string, args ...any) error { |
no test coverage detected