forked from schollz/find3-cli-scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
97 lines (88 loc) · 2.34 KB
/
utils.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
package main
import (
"bytes"
"math/rand"
"os"
"os/exec"
"strings"
"time"
log "github.com/cihub/seelog"
)
func RunCommand(tDuration time.Duration, commands string) (string, string) {
log.Debug(commands)
command := strings.Fields(commands)
cmd := exec.Command(command[0])
if len(command) > 0 {
cmd = exec.Command(command[0], command[1:]...)
}
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
err := cmd.Start()
if err != nil {
log.Error(err)
log.Flush()
os.Exit(1)
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(tDuration):
if err := cmd.Process.Kill(); err != nil {
log.Debug("failed to kill: ", err)
}
log.Debugf("%s killed as timeout reached", commands)
case err := <-done:
if err != nil {
log.Debugf("err running %s: %s", commands, err.Error())
} else {
log.Debugf("%s done gracefully without error", commands)
}
}
return strings.TrimSpace(outb.String()), strings.TrimSpace(errb.String())
}
func Average(nums []float64) float64 {
total := float64(0)
for _, num := range nums {
total += num
}
return float64(int(total/float64(len(nums))*10)) / 10
}
// src is seeds the random generator for generating random strings
var src = rand.NewSource(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
func RandomString(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// exists returns whether the given file or directory exists or not
// from http://stackoverflow.com/questions/10510691/how-to-check-whether-a-file-or-directory-denoted-by-a-path-exists-in-golang
func Exists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}