-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.go
82 lines (64 loc) · 1.49 KB
/
shell.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
package main
import (
"context"
"log"
"os"
"os/exec"
"time"
)
func getShell() []string {
shells := [][]string{
{"/bin/bash", "-c"},
{"/bin/sh", "-c"},
{"/system/bin/sh", "-c"},
{"/vendor/bin/sh", "-c"},
}
for _, sh := range shells {
if _, err := os.Stat(sh[0]); os.IsNotExist(err) {
continue
}
return sh
}
log.Panic("No suitable shell found!")
return []string{}
}
func RunInitCmd(cmd string) error {
var executable []string
executable = append(executable, getShell()...)
executable = append(executable, cmd)
c := exec.Command(executable[0], executable[1:]...)
return c.Run()
}
func RunCmd(ctx context.Context, cmd CmdConfig, col int, output chan LogEntry) {
var executable []string
executable = append(executable, getShell()...)
executable = append(executable, cmd.Cmd)
for {
c := exec.CommandContext(ctx, executable[0], executable[1:]...)
o, e := c.StdoutPipe()
if e != nil {
output <- LogEntry{time.Now(), col, "[ Error starting " + cmd.Cmd + ": " + e.Error() + " ]"}
}
if err := c.Start(); err != nil {
output <- LogEntry{time.Now(), col, "[ Error starting " + cmd.Cmd + ": " + err.Error() + " ]"}
continue
}
data := make([]byte, 4096, 4096)
for {
n, err := o.Read(data)
if n <= 0 {
break
}
if err == nil {
output <- LogEntry{time.Now(), col, string(data[0:n])}
}
}
c.Wait()
if !cmd.Params.Loop {
break
}
if cmd.Params.IntervalMs > 0 {
time.Sleep(time.Duration(cmd.Params.IntervalMs * 1_000_000))
}
}
}