-
Notifications
You must be signed in to change notification settings - Fork 27
/
runsnmp.go
88 lines (77 loc) · 1.8 KB
/
runsnmp.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
package sw
import (
"strings"
"time"
"github.com/ulricqin/gosnmp"
)
func RunSnmp(ip, community, oid, method string, timeout int) (snmpPDUs []gosnmp.SnmpPDU, err error) {
cur_gosnmp, err := gosnmp.NewGoSNMP(ip, community, gosnmp.Version2c, int64(timeout))
if err != nil {
return nil, err
} else {
cur_gosnmp.SetTimeout(int64(timeout))
snmpPDUs, err := ParseSnmpMethod(oid, method, cur_gosnmp)
if err != nil {
return nil, err
} else {
return snmpPDUs, err
}
}
return
}
func ParseSnmpMethod(oid, method string, cur_gosnmp *gosnmp.GoSNMP) (snmpPDUs []gosnmp.SnmpPDU, err error) {
var snmpPacket *gosnmp.SnmpPacket
switch method {
case "get":
snmpPacket, err = cur_gosnmp.Get(oid)
if err != nil {
return nil, err
} else {
snmpPDUs = snmpPacket.Variables
return snmpPDUs, err
}
case "getnext":
snmpPacket, err = cur_gosnmp.GetNext(oid)
if err != nil {
return nil, err
} else {
snmpPDUs = snmpPacket.Variables
return snmpPDUs, err
}
default:
snmpPDUs, err = cur_gosnmp.Walk(oid)
return snmpPDUs, err
}
return
}
func snmpPDUNameToIfIndex(snmpPDUName string) string {
oidSplit := strings.Split(snmpPDUName, ".")
curIfIndex := oidSplit[len(oidSplit)-1]
return curIfIndex
}
func RunSnmpwalk(ip, community, oid string, retry int, timeout int) ([]gosnmp.SnmpPDU, error) {
method := "getnext"
oidnext := oid
var snmpPDUs = []gosnmp.SnmpPDU{}
var snmpPDU []gosnmp.SnmpPDU
var err error
for {
for i := 0; i < retry; i++ {
snmpPDU, err = RunSnmp(ip, community, oidnext, method, timeout)
if len(snmpPDU) > 0 {
break
}
time.Sleep(100 * time.Millisecond)
}
if err != nil {
break
}
oidnext = snmpPDU[0].Name
if strings.Contains(oidnext, oid) {
snmpPDUs = append(snmpPDUs, snmpPDU[0])
} else {
break
}
}
return snmpPDUs, err
}