forked from Jrohy/trojan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
86 lines (79 loc) · 1.86 KB
/
command.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
package util
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"strings"
)
// CheckCommandExists 检查命令是否存在
func CheckCommandExists(command string) bool {
if _, err := exec.LookPath(command); err != nil {
return false
}
return true
}
// RunWebShell 运行网上的脚本
func RunWebShell(webShellPath string) {
if !strings.HasPrefix(webShellPath, "http") && !strings.HasPrefix(webShellPath, "https") {
fmt.Printf("shell path must start with http or https!")
return
}
resp, err := http.Get(webShellPath)
if err != nil {
fmt.Println(err.Error())
}
defer resp.Body.Close()
installShell, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
}
ExecCommand(string(installShell))
}
// ExecCommand 运行命令并实时查看运行结果
func ExecCommand(command string) error {
cmd := exec.Command("bash", "-c", command)
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
if err := cmd.Start(); err != nil {
fmt.Println("Error:The command is err: ", err.Error())
return err
}
ch := make(chan string, 100)
stdoutScan := bufio.NewScanner(stdout)
stderrScan := bufio.NewScanner(stderr)
go func() {
for stdoutScan.Scan() {
line := stdoutScan.Text()
ch <- line
}
}()
go func() {
for stderrScan.Scan() {
line := stderrScan.Text()
ch <- line
}
}()
var err error
go func() {
err = cmd.Wait()
if err != nil && !strings.Contains(err.Error(), "exit status") {
fmt.Println("wait:", err.Error())
}
close(ch)
}()
for line := range ch {
fmt.Println(line)
}
return err
}
// ExecCommandWithResult 运行命令并获取结果
func ExecCommandWithResult(command string) string {
out, err := exec.Command("bash", "-c", command).CombinedOutput()
if err != nil && !strings.Contains(err.Error(), "exit status") {
fmt.Println("err: " + err.Error())
return ""
}
return string(out)
}