gosnmp

Форк
0
114 строк · 3.7 Кб
1
// Copyright 2012 The GoSNMP Authors. All rights reserved.  Use of this
2
// source code is governed by a BSD-style license that can be found in the
3
// LICENSE file.
4

5
/*
6
Example usage and output:
7

8
$ GOSNMP_TARGET=10.12.0.1 GOSNMP_PORT=161 go run main.go
9
SEND INIT
10
SENDING PACKET: gosnmp.SnmpPacket{Version:0x1, MsgFlags:0x0, SecurityModel:0x0, SecurityParameters:gosnmp.SnmpV3SecurityParameters(nil), ContextEngineID:"", ContextName:"", Community:"public", PDUType:0xa0, MsgID:0x0, RequestID:0x48ef671d, MsgMaxSize:0x0, Error:0x0, ErrorIndex:0x0, NonRepeaters:0x0, MaxRepetitions:0x0, Variables:[]gosnmp.SnmpPDU{gosnmp.SnmpPDU{Name:"1.3.6.1.2.1.1.4.0", Type:0x5, Value:interface {}(nil)}, gosnmp.SnmpPDU{Name:"1.3.6.1.2.1.1.7.0", Type:0x5, Value:interface {}(nil)}}, Logger:gosnmp.Logger(nil), SnmpTrap:gosnmp.SnmpTrap{Variables:[]gosnmp.SnmpPDU(nil), IsInform:false, Enterprise:"", AgentAddress:"", GenericTrap:0, SpecificTrap:0, Timestamp:0x0}}
11
WAITING RESPONSE...
12
2021/01/03 13:31:15 Query latency in seconds: 0.000625777
13
GET RESPONSE OK: [48 63 2 1 1 4 6 112 117 98 108 105 99 162 50 2 4 72 239 103 29 2 1 0 2 1 0 48 36 48 19 6 8 43 6 1 2 1 1 4 0 4 7 99 111 110 116 97 99 116 48 13 6 8 43 6 1 2 1 1 7 0 2 1 78]
14
Packet sanity verified, we got all the bytes (65)
15
parseRawField: version
16
Parsed version 1
17
parseRawField: community
18
Parsed community public
19
UnmarshalPayload Meet PDUType 0xa2. Offset 13
20
getResponseLength: 52
21
parseRawField: request id
22
requestID: 1223649053
23
parseRawField: error-status
24
errorStatus: 0
25
parseRawField: error index
26
error-index: 0
27
vblLength: 38
28
parseRawField: OID
29
OID: .1.3.6.1.2.1.1.4.0
30
decodeValue: msg: value
31
decodeValue: type is OctetString
32
decodeValue: value is []byte{0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74}
33
parseRawField: OID
34
OID: .1.3.6.1.2.1.1.7.0
35
decodeValue: msg: value
36
decodeValue: type is Integer
37
decodeValue: value is 78
38
0: oid: .1.3.6.1.2.1.1.4.0 string: contact
39
1: oid: .1.3.6.1.2.1.1.7.0 number: 78
40

41
*/
42

43
package main
44

45
import (
46
	"fmt"
47
	"log"
48
	"os"
49
	"strconv"
50
	"time"
51

52
	g "github.com/gosnmp/gosnmp"
53
)
54

55
func main() {
56

57
	// get Target and Port from environment
58
	envTarget := os.Getenv("GOSNMP_TARGET")
59
	envPort := os.Getenv("GOSNMP_PORT")
60
	if len(envTarget) <= 0 {
61
		log.Fatalf("environment variable not set: GOSNMP_TARGET")
62
	}
63
	if len(envPort) <= 0 {
64
		log.Fatalf("environment variable not set: GOSNMP_PORT")
65
	}
66
	port, _ := strconv.ParseUint(envPort, 10, 16)
67

68
	// Build our own GoSNMP struct, rather than using g.Default.
69
	// Do verbose logging of packets.
70
	params := &g.GoSNMP{
71
		Target:    envTarget,
72
		Port:      uint16(port),
73
		Community: "public",
74
		Version:   g.Version2c,
75
		Timeout:   time.Duration(2) * time.Second,
76
		Logger:    g.NewLogger(log.New(os.Stdout, "", 0)),
77
	}
78
	err := params.Connect()
79
	if err != nil {
80
		log.Fatalf("Connect() err: %v", err)
81
	}
82
	defer params.Conn.Close()
83

84
	// Function handles for collecting metrics on query latencies.
85
	var sent time.Time
86
	params.OnSent = func(x *g.GoSNMP) {
87
		sent = time.Now()
88
	}
89
	params.OnRecv = func(x *g.GoSNMP) {
90
		log.Println("Query latency in seconds:", time.Since(sent).Seconds())
91
	}
92

93
	oids := []string{"1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.7.0"}
94
	result, err2 := params.Get(oids) // Get() accepts up to g.MAX_OIDS
95
	if err2 != nil {
96
		log.Fatalf("Get() err: %v", err2)
97
	}
98

99
	for i, variable := range result.Variables {
100
		fmt.Printf("%d: oid: %s ", i, variable.Name)
101

102
		// the Value of each variable returned by Get() implements
103
		// interface{}. You could do a type switch...
104
		switch variable.Type {
105
		case g.OctetString:
106
			fmt.Printf("string: %s\n", string(variable.Value.([]byte)))
107
		default:
108
			// ... or often you're just interested in numeric values.
109
			// ToBigInt() will return the Value as a BigInt, for plugging
110
			// into your calculations.
111
			fmt.Printf("number: %d\n", g.ToBigInt(variable.Value))
112
		}
113
	}
114
}
115

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.