-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmdutils.go
More file actions
75 lines (66 loc) · 1.68 KB
/
cmdutils.go
File metadata and controls
75 lines (66 loc) · 1.68 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package cmdutils
import (
"fmt"
"os"
"os/exec"
// "strconv"
"time"
)
// Execute some commands with bash.
// The `cmdstr` param could be a single command such as `ls ~`,
// or a pipeline command such as `ps aux | grep 'dropbox' | grep -v 'grep'`,
// a complete script file content is also can be work.
// The `cmdstr` will be written to a temp file, and then execute that file with bash.
// The output of your command will be returned by this function.
func BashExecute(cmdstr string) (ret string, err error) {
dir := os.TempDir() + pathSeperator() + "goexec"
dirfile, err := os.Open(dir)
if err != nil {
if os.IsNotExist(err) {
err = os.Mkdir(dir, 0700)
if err != nil {
return "", err
}
} else {
return "", err
}
}
defer dirfile.Close()
filename := fmt.Sprintf("%s%s%d", dir, pathSeperator(), time.Now().Unix())
file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0664)
if err != nil {
return "", err
}
defer file.Close()
_, err = file.Write([]byte(cmdstr))
if err != nil {
return "", err
}
cmd := exec.Command("bash", filename)
retbytes, err := cmd.Output()
if err != nil {
return "", err
}
return string(retbytes), nil
}
func pathSeperator() string {
runs := make([]rune, 0, 1)
runs = append(runs, os.PathSeparator)
return string(runs)
}
// This function is a wrapper for cmd.Run()
// Pipe stdout, stderr, stdin of os to stdout, stderr, stdin of cmd
func Run(cmdname string, params ...string) {
cmd := exec.Command(cmdname, params...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err := cmd.Run()
checkErr(err)
}
func checkErr(err error) {
if err != nil {
fmt.Errorf("error: %s\n", err.Error())
os.Exit(2)
}
}