-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetAndRun.go
115 lines (90 loc) · 1.92 KB
/
GetAndRun.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strings"
"time"
)
/*
Simple program.
Get URL.
Parse its body as strings separated by ';'.
Run command on your system.
Profit.
*/
const HttpTimeout = 20 * time.Second
func main() {
// parse args
var url = flag.String("u", "", "URL")
var period = flag.Int("p", 0, "Repeat time period.")
var maxRepeat = flag.Int("m", 1, "Maximum number of repeats.")
var onBackGround = flag.Int("b", 1, "Run command at background.")
flag.Parse()
var reqCount = 1
if *url == "" {
log.Fatal("URL is empty")
}
// proceed request(s)
for true {
body := httpGet(*url)
if body != nil {
runCmd(string(body), *onBackGround)
}
if *period <= 1 || *maxRepeat == reqCount {
break
}
time.Sleep(time.Duration(*period) * time.Second)
if *maxRepeat != 0 {
reqCount++
}
}
}
func httpGet(url string) []byte {
client := http.Client{Timeout: HttpTimeout}
resp, err := client.Get(url)
if err != nil {
log.Printf("HTTP error [%s]\n", err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("HTTP request failed [%s]\n", resp.Status)
return nil
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Cannot read response body")
return nil
}
return body
}
func runCmd(input string, onBackGround int) {
commands := strings.Split(input, ";")
for _, cmd := range commands {
cmd = strings.TrimSpace(cmd)
slices := strings.Split(cmd, " ")
bin := slices[0]
args := slices[1:]
if bin == "" {
return
}
if onBackGround == 1 {
log.Printf("Running command [%s] at background", cmd)
err := exec.Command(bin, args...).Start()
if err != nil {
log.Println("Command failed")
}
} else {
log.Printf("Running command [%s]", cmd)
out, err := exec.Command(bin, args...).Output()
if err != nil {
log.Println("Command failed")
}
fmt.Printf("%s\n", out)
}
}
}