-
Notifications
You must be signed in to change notification settings - Fork 27
/
uptimestat.go
50 lines (40 loc) · 1.01 KB
/
uptimestat.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
package sw
import (
"fmt"
"log"
"math"
"strconv"
"strings"
"time"
)
func SysUpTime(ip, community string, timeout int) (string, error) {
oid := "1.3.6.1.2.1.1.3.0"
method := "get"
defer func() {
if r := recover(); r != nil {
log.Println(ip+" Recovered in Uptime", r)
}
}()
snmpPDUs, err := RunSnmp(ip, community, oid, method, timeout)
if err == nil {
for _, pdu := range snmpPDUs {
durationStr := parseTime(pdu.Value.(int))
return durationStr, err
}
}
return "", err
}
func parseTime(d int) string {
timestr := strconv.Itoa(d / 100)
duration, _ := time.ParseDuration(timestr + "s")
totalHour := duration.Hours()
day := int(totalHour / 24)
modTime := math.Mod(totalHour, 24)
modTimeStr := strconv.FormatFloat(modTime, 'f', 3, 64)
modDuration, _ := time.ParseDuration(modTimeStr + "h")
modDurationStr := modDuration.String()
if strings.Contains(modDurationStr, ".") {
modDurationStr = strings.Split(modDurationStr, ".")[0] + "s"
}
return fmt.Sprintf("%dday %s", day, modDurationStr)
}