This repository has been archived by the owner on Feb 1, 2021. It is now read-only.
forked from alouca/gosnmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gosnmp.go
254 lines (209 loc) · 6.15 KB
/
gosnmp.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright 2012 Andreas Louca. All rights reserved.
// Use of this source code is goverend by a BSD-style
// license that can be found in the LICENSE file.
package gosnmp
import (
"fmt"
l "github.com/alouca/gologger"
"net"
"strings"
"time"
)
type GoSNMP struct {
Target string
Community string
Version SnmpVersion
Timeout time.Duration
conn net.Conn
Log *l.Logger
}
var DEFAULT_PORT = 161
// Creates a new SNMP Client. Target is the IP address, Community the SNMP Community String and Version the SNMP version.
// Currently only v2c is supported. Timeout parameter is measured in seconds.
func NewGoSNMP(target, community string, version SnmpVersion, timeout int64) (*GoSNMP, error) {
if !strings.Contains(target, ":") {
target = fmt.Sprintf("%s:%d", target, DEFAULT_PORT)
}
// Open a UDP connection to the target
conn, err := net.DialTimeout("udp", target, time.Duration(timeout)*time.Second)
if err != nil {
return nil, fmt.Errorf("Error establishing connection to host: %s\n", err.Error())
}
s := &GoSNMP{target, community, version, time.Duration(timeout) * time.Second, conn, l.CreateLogger(false, false)}
return s, nil
}
// Enables verbose logging
func (x *GoSNMP) SetVerbose(v bool) {
x.Log.VerboseFlag = v
}
// Enables debugging
func (x *GoSNMP) SetDebug(d bool) {
x.Log.DebugFlag = d
}
// Sets the timeout for network read/write functions. Defaults to 5 seconds.
func (x *GoSNMP) SetTimeout(seconds int64) {
if seconds <= 0 {
seconds = 5
}
x.Timeout = time.Duration(seconds) * time.Second
}
// StreamWalk will start walking a specified OID, and push through a channel the results
// as it receives them, without waiting for the whole process to finish to return the
// results
func (x *GoSNMP) StreamWalk(oid string, c chan *Variable) error {
return nil
}
// Walk will SNMP walk the target, blocking until the process is complete
func (x *GoSNMP) Walk(oid string) (results []SnmpPDU, err error) {
if oid == "" {
return nil, fmt.Errorf("No OID given\n")
}
results = make([]SnmpPDU, 0)
requestOid := oid
for {
res, err := x.GetNext(oid)
if err != nil {
return results, err
}
if res != nil {
if len(res.Variables) > 0 {
if strings.Index(res.Variables[0].Name, requestOid) > -1 {
results = append(results, res.Variables[0])
// Set to the next
oid = res.Variables[0].Name
x.Log.Debug("Moving to %s\n", oid)
} else {
x.Log.Debug("Root OID mismatch, stopping walk\n")
break
}
} else {
break
}
} else {
break
}
}
return
}
// Marshals & send an SNMP request. Unmarshals the response and returns back the parsed
// SNMP packet
func (x *GoSNMP) sendPacket(packet *SnmpPacket) (*SnmpPacket, error) {
// Set timeouts on the connection
deadline := time.Now()
x.conn.SetDeadline(deadline.Add(x.Timeout))
// Marshal it
fBuf, err := packet.marshal()
if err != nil {
return nil, err
}
// Send the packet!
_, err = x.conn.Write(fBuf)
if err != nil {
return nil, fmt.Errorf("Error writing to socket: %s\n", err.Error())
}
// Try to read the response
resp := make([]byte, 2048, 2048)
n, err := x.conn.Read(resp)
if err != nil {
return nil, fmt.Errorf("Error reading from UDP: %s\n", err.Error())
}
// Unmarshal the read bytes
pdu, err := Unmarshal(resp[:n])
if err != nil {
return nil, fmt.Errorf("Unable to decode packet: %s\n", err.Error())
} else {
if len(pdu.Variables) < 1 {
return nil, fmt.Errorf("No responses received.")
} else {
return pdu, nil
}
}
return nil, nil
}
// Sends an SNMP Get Next Request to the target. Returns the next variable response from the OID given or an error
func (x *GoSNMP) GetNext(oid string) (*SnmpPacket, error) {
var err error
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
// Create the packet
packet := new(SnmpPacket)
packet.Community = x.Community
packet.Error = 0
packet.ErrorIndex = 0
packet.RequestType = GetNextRequest
packet.Version = 1 // version 2
packet.Variables = []SnmpPDU{SnmpPDU{Name: oid, Type: Null}}
return x.sendPacket(packet)
}
// Debug function. Unmarshals raw bytes and returns the result without the network part
func (x *GoSNMP) Debug(data []byte) (*SnmpPacket, error) {
packet, err := Unmarshal(data)
if err != nil {
return nil, fmt.Errorf("Unable to decode packet: %s\n", err.Error())
}
return packet, nil
}
// Sends an SNMP BULK-GET request to the target. Returns a Variable with the response or an error
func (x *GoSNMP) GetBulk(non_repeaters, max_repetitions uint8, oids ...string) (*SnmpPacket, error) {
var err error
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
// Create the packet
packet := new(SnmpPacket)
packet.Community = x.Community
packet.NonRepeaters = non_repeaters
packet.MaxRepetitions = max_repetitions
packet.RequestType = GetBulkRequest
packet.Version = 1 // version 2
packet.Variables = make([]SnmpPDU, len(oids))
for i, oid := range oids {
packet.Variables[i] = SnmpPDU{Name: oid, Type: Null}
}
return x.sendPacket(packet)
return x.sendPacket(packet)
}
// Sends an SNMP GET request to the target. Returns a Variable with the response or an error
func (x *GoSNMP) Get(oid string) (*SnmpPacket, error) {
var err error
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
// Create the packet
packet := new(SnmpPacket)
packet.Community = x.Community
packet.Error = 0
packet.ErrorIndex = 0
packet.RequestType = GetRequest
packet.Version = 1 // version 2
packet.Variables = []SnmpPDU{SnmpPDU{Name: oid, Type: Null}}
return x.sendPacket(packet)
}
// Sends an SNMP GET request to the target. Returns a Variable with the response or an error
func (x *GoSNMP) GetMulti(oids []string) (*SnmpPacket, error) {
var err error
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
// Create the packet
packet := new(SnmpPacket)
packet.Community = x.Community
packet.Error = 0
packet.ErrorIndex = 0
packet.RequestType = GetRequest
packet.Version = 1 // version 2
packet.Variables = make([]SnmpPDU, len(oids))
for i, oid := range oids {
packet.Variables[i] = SnmpPDU{Name: oid, Type: Null}
}
return x.sendPacket(packet)
}