gosnmp

package module
v1.35.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 16, 2023 License: BSD-2-Clause, BSD-3-Clause Imports: 31 Imported by: 0

README

gosnmp

Mentioned in Awesome Go

Build Status PkgGoDev

GoSNMP is an SNMP client library fully written in Go. It provides Get, GetNext, GetBulk, Walk, BulkWalk, Set and Traps. It supports IPv4 and IPv6, using SNMPv1, SNMPv2c or SNMPv3. Builds are tested against linux/amd64 and linux/386.

About

gosnmp was started by Andreas Louca, then completely rewritten by Sonia Hamilton (2012-2020), and now ownership has been transferred to the community at gosnmp/gosnmp.

For support and help, join us in the #snmp channel of Gophers Slack.

Overview

GoSNMP has the following SNMP functions:

  • Get (single or multiple OIDs)
  • GetNext
  • GetBulk (SNMPv2c and SNMPv3 only)
  • Walk - retrieves a subtree of values using GETNEXT.
  • BulkWalk - retrieves a subtree of values using GETBULK (SNMPv2c and SNMPv3 only).
  • BulkWalkAll - similar to BulkWalk but returns a filled array of all values rather than using a callback function to stream results.
  • Set - supports Integers and OctetStrings.
  • SendTrap - send SNMP TRAPs.
  • Listen - act as an NMS for receiving TRAPs.

GoSNMP has the following helper functions:

  • ToBigInt - treat returned values as *big.Int
  • Partition - facilitates dividing up large slices of OIDs

gosnmp/gosnmp has completely diverged from alouca/gosnmp, your code will require modification in these (and other) locations:

  • the Get function has a different method signature
  • the NewGoSNMP function has been removed, use Connect instead (see Usage below). Connect uses the GoSNMP struct; gosnmp.Default is provided for you to build on.
  • GoSNMP no longer relies on alouca/gologger - you can use your logger if it conforms to the gosnmp.LoggerInterface interface; otherwise debugging will disabled.
type LoggerInterface interface {
    Print(v ...interface{})
    Printf(format string, v ...interface{})
}

To enable logging, you must call gosnmp.NewLogger() function, and pass a pointer to your logging interface, for example with standard *log.Logger:

gosnmp.Default.Logger = gosnmp.NewLogger(log.New(os.Stdout, "", 0))

or

g := &gosnmp.GoSNMP{
    ...
    Logger:    gosnmp.NewLogger(log.New(os.Stdout, "", 0)),
}

You can completely remove the logging code from your application using the golang build tag "gosnmp_nodebug", for example:

go build -tags gosnmp_nodebug

This will completely disable the logging of the gosnmp library, even if the logger interface is specified in the code. This provides a small performance improvement.

Installation

go get github.com/gosnmp/gosnmp

Documentation

https://pkg.go.dev/github.com/gosnmp/gosnmp

Usage

Here is examples/example/main.go, demonstrating how to use GoSNMP:

// Default is a pointer to a GoSNMP struct that contains sensible defaults
// eg port 161, community public, etc
g.Default.Target = "192.168.1.10"
err := g.Default.Connect()
if err != nil {
    log.Fatalf("Connect() err: %v", err)
}
defer g.Default.Conn.Close()

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

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

    // the Value of each variable returned by Get() implements
    // interface{}. You could do a type switch...
    switch variable.Type {
    case g.OctetString:
        bytes := variable.Value.([]byte)
        fmt.Printf("string: %s\n", string(bytes))
    default:
        // ... or often you're just interested in numeric values.
        // ToBigInt() will return the Value as a BigInt, for plugging
        // into your calculations.
        fmt.Printf("number: %d\n", g.ToBigInt(variable.Value))
    }
}

Running this example gives the following output (from my printer):

% go run example.go
0: oid: 1.3.6.1.2.1.1.4.0 string: Administrator
1: oid: 1.3.6.1.2.1.1.7.0 number: 104
  • examples/example2.go is similar to example.go, however it uses a custom &GoSNMP rather than g.Default
  • examples/walkexample.go demonstrates using BulkWalk
  • examples/example3.go demonstrates SNMPv3
  • examples/trapserver.go demonstrates writing an SNMP v2c trap server

MIB Parser

I don't have any plans to write a mib parser. Others have suggested https://github.com/sleepinggenius2/gosmi

Contributions

Contributions are welcome, especially ones that have packet captures (see below).

If you've never contributed to a Go project before, here is an example workflow.

  1. fork this repo on the GitHub webpage
  2. go get github.com/gosnmp/gosnmp
  3. cd $GOPATH/src/github.com/gosnmp/gosnmp
  4. git remote rename origin upstream
  5. git remote add origin git@github.com:<your-github-username>/gosnmp.git
  6. git checkout -b development
  7. git push -u origin development (setup where you push to, check it works)

Packet Captures

Create your packet captures in the following way:

Expected output, obtained via an snmp command. For example:

% snmpget -On -v2c -c public 203.50.251.17 1.3.6.1.2.1.1.7.0 \
  1.3.6.1.2.1.2.2.1.2.6 1.3.6.1.2.1.2.2.1.5.3
.1.3.6.1.2.1.1.7.0 = INTEGER: 78
.1.3.6.1.2.1.2.2.1.2.6 = STRING: GigabitEthernet0
.1.3.6.1.2.1.2.2.1.5.3 = Gauge32: 4294967295

A packet capture, obtained while running the snmpget. For example:

sudo tcpdump -s 0 -i eth0 -w foo.pcap host 203.50.251.17 and port 161

Bugs

Rane's document SNMP: Simple? Network Management Protocol was useful when learning the SNMP protocol.

Please create an issue on Github with packet captures (upload capture to Google Drive, Dropbox, or similar) containing samples of missing BER types, or of any other bugs you find. If possible, please include 2 or 3 examples of the missing/faulty BER type.

The following BER types have been implemented:

  • 0x00 UnknownType
  • 0x01 Boolean
  • 0x02 Integer
  • 0x03 BitString
  • 0x04 OctetString
  • 0x05 Null
  • 0x06 ObjectIdentifier
  • 0x07 ObjectDescription
  • 0x40 IPAddress (IPv4 & IPv6)
  • 0x41 Counter32
  • 0x42 Gauge32
  • 0x43 TimeTicks
  • 0x44 Opaque (Float & Double)
  • 0x45 NsapAddress
  • 0x46 Counter64
  • 0x47 Uinteger32
  • 0x78 OpaqueFloat
  • 0x79 OpaqueDouble
  • 0x80 NoSuchObject
  • 0x81 NoSuchInstance
  • 0x82 EndOfMibView

Running the Tests

Local testing in Docker

docker build -t gosnmp/gosnmp:latest .
docker run -it gosnmp/gosnmp:latest

or

export GOSNMP_TARGET=1.2.3.4
export GOSNMP_PORT=161
export GOSNMP_TARGET_IPV4=1.2.3.4
export GOSNMP_PORT_IPV4=161
export GOSNMP_TARGET_IPV6='0:0:0:0:0:ffff:102:304'
export GOSNMP_PORT_IPV6=161
go test -v -tags all        # for example
go test -v -tags helper     # for example

Tests are grouped as follows:

  • Unit tests (validating data packing and marshalling):
    • marshal_test.go
    • misc_test.go
  • Public API consistency tests:
    • gosnmp_api_test.go
  • End-to-end integration tests:
    • generic_e2e_test.go

The generic end-to-end integration test generic_e2e_test.go should work against any SNMP MIB-2 compliant host (e.g. a router, NAS box, printer).

Mocks were generated using:

mockgen -source=interface.go -destination=mocks/gosnmp_mock.go -package=mocks

However they're currently removed, as they were breaking linting.

To profile cpu usage:

go test -cpuprofile cpu.out
go test -c
go tool pprof gosnmp.test cpu.out

To profile memory usage:

go test -memprofile mem.out
go test -c
go tool pprof gosnmp.test mem.out

To check test coverage:

go get github.com/axw/gocov/gocov
go get github.com/matm/gocov-html
gocov test github.com/gosnmp/gosnmp | gocov-html > gosnmp.html && firefox gosnmp.html &

License

Parts of the code are taken from the Golang project (specifically some functions for unmarshaling BER responses), which are under the same terms and conditions as the Go language. The rest of the code is under a BSD license.

See the LICENSE file for more details.

The remaining code is Copyright 2012 the GoSNMP Authors - see AUTHORS.md for a list of authors.

Documentation

Index

Constants

View Source
const (
	// MaxOids is the maximum number of OIDs permitted in a single call,
	// otherwise error. MaxOids too high can cause remote devices to fail
	// strangely. 60 seems to be a common value that works, but you will want
	// to change this in the GoSNMP struct
	MaxOids = 60

	// Max oid sub-identifier value
	// https://tools.ietf.org/html/rfc2578#section-7.1.3
	MaxObjectSubIdentifierValue = 4294967295
)
View Source
const AsnContext = 0x80
View Source
const AsnExtensionID = 0x1F
View Source
const AsnExtensionTag = (AsnContext | AsnExtensionID) // 0x9F

Variables

View Source
var (
	ErrBase128IntegerTooLarge  = errors.New("base 128 integer too large")
	ErrBase128IntegerTruncated = errors.New("base 128 integer truncated")
	ErrFloatTooLarge           = errors.New("float too large")
	ErrIntegerTooLarge         = errors.New("integer too large")
	ErrInvalidOidLength        = errors.New("invalid OID length")
	ErrInvalidPacketLength     = errors.New("invalid packet length")
	ErrZeroByteBuffer          = errors.New("zero byte buffer")
	ErrZeroLenInteger          = errors.New("zero length integer")
)

helper error modes

View Source
var (
	ErrDecryption            = errors.New("decryption error")
	ErrInvalidMsgs           = errors.New("invalid messages")
	ErrNotInTimeWindow       = errors.New("not in time window")
	ErrUnknownEngineID       = errors.New("unknown engine id")
	ErrUnknownPDUHandlers    = errors.New("unknown pdu handlers")
	ErrUnknownReportPDU      = errors.New("unknown report pdu")
	ErrUnknownSecurityLevel  = errors.New("unknown security level")
	ErrUnknownSecurityModels = errors.New("unknown security models")
	ErrUnknownUsername       = errors.New("unknown username")
	ErrWrongDigest           = errors.New("wrong digest")
)
View Source
var Default = &GoSNMP{
	Port:               161,
	Transport:          udp,
	Community:          "public",
	Version:            Version2c,
	Timeout:            time.Duration(2) * time.Second,
	Retries:            3,
	ExponentialTimeout: true,
	MaxOids:            MaxOids,
}

Default connection settings

Functions

func Check added in v1.10.0

func Check(err error)

Check makes checking errors easy, so they actually get a minimal check

func Partition added in v1.2.0

func Partition(currentPosition, partitionSize, sliceLength int) bool

Partition - returns true when dividing a slice into partitionSize lengths, including last partition which may be smaller than partitionSize. This is useful when you have a large array of OIDs to run Get() on. See the tests for example usage.

For example for a slice of 8 items to be broken into partitions of length 3, Partition returns true for the currentPosition having the following values:

0 1 2 3 4 5 6 7

T        T     T

func ToBigInt

func ToBigInt(value interface{}) *big.Int

ToBigInt converts SnmpPDU.Value to big.Int, or returns a zero big.Int for non int-like types (eg strings).

This is a convenience function to make working with SnmpPDU's easier - it reduces the need for type assertions. A big.Int is convenient, as SNMP can return int32, uint32, and uint64.

Types

type Asn1BER

type Asn1BER byte

Asn1BER is the type of the SNMP PDU

const (
	EndOfContents     Asn1BER = 0x00
	UnknownType       Asn1BER = 0x00
	Boolean           Asn1BER = 0x01
	Integer           Asn1BER = 0x02
	BitString         Asn1BER = 0x03
	OctetString       Asn1BER = 0x04
	Null              Asn1BER = 0x05
	ObjectIdentifier  Asn1BER = 0x06
	ObjectDescription Asn1BER = 0x07
	IPAddress         Asn1BER = 0x40
	Counter32         Asn1BER = 0x41
	Gauge32           Asn1BER = 0x42
	TimeTicks         Asn1BER = 0x43
	Opaque            Asn1BER = 0x44
	NsapAddress       Asn1BER = 0x45
	Counter64         Asn1BER = 0x46
	Uinteger32        Asn1BER = 0x47
	OpaqueFloat       Asn1BER = 0x78
	OpaqueDouble      Asn1BER = 0x79
	NoSuchObject      Asn1BER = 0x80
	NoSuchInstance    Asn1BER = 0x81
	EndOfMibView      Asn1BER = 0x82
)

Asn1BER's - http://www.ietf.org/rfc/rfc1442.txt

func (Asn1BER) String added in v1.35.2

func (i Asn1BER) String() string

type BitStringValue

type BitStringValue struct {
	Bytes     []byte // bits packed into bytes.
	BitLength int    // length in bits.
}

BitStringValue is the structure to use when you want an ASN.1 BIT STRING type. A bit string is padded up to the nearest byte in memory and the number of valid bits is recorded. Padding bits will be zero.

func (BitStringValue) At

func (b BitStringValue) At(i int) int

At returns the bit at the given index. If the index is out of range it returns false.

func (BitStringValue) RightAlign

func (b BitStringValue) RightAlign() []byte

RightAlign returns a slice where the padding bits are at the beginning. The slice may share memory with the BitString.

type GoSNMP

type GoSNMP struct {
	// Conn is net connection to use, typically established using GoSNMP.Connect().
	Conn net.Conn

	// Target is an ipv4 address.
	Target string

	// Port is a port.
	Port uint16

	// Transport is the transport protocol to use ("udp" or "tcp"); if unset "udp" will be used.
	Transport string

	// Community is an SNMP Community string.
	Community string

	// Version is an SNMP Version.
	Version SnmpVersion

	// Context allows for overall deadlines and cancellation.
	Context context.Context

	// Timeout is the timeout for one SNMP request/response.
	Timeout time.Duration

	// Set the number of retries to attempt.
	Retries int

	// Double timeout in each retry.
	ExponentialTimeout bool

	// Logger is the GoSNMP.Logger to use for debugging.
	// For verbose logging to stdout:
	// x.Logger = NewLogger(log.New(os.Stdout, "", 0))
	// For Release builds, you can turn off logging entirely by using the go build tag "gosnmp_nodebug" even if the logger was installed.
	Logger Logger

	// Message hook methods allow passing in a functions at various points in the packet handling.
	// For example, this can be used to collect packet timing, add metrics, or implement tracing.
	/*

	 */
	// PreSend is called before a packet is sent.
	PreSend func(*GoSNMP)

	// OnSent is called when a packet is sent.
	OnSent func(*GoSNMP)

	// OnRecv is called when a packet is received.
	OnRecv func(*GoSNMP)

	// OnRetry is called when a retry attempt is done.
	OnRetry func(*GoSNMP)

	// OnFinish is called when the request completed.
	OnFinish func(*GoSNMP)

	// MaxOids is the maximum number of oids allowed in a Get().
	// (default: MaxOids)
	MaxOids int

	// MaxRepetitions sets the GETBULK max-repetitions used by BulkWalk*
	// Unless MaxRepetitions is specified it will use defaultMaxRepetitions (50)
	// This may cause issues with some devices, if so set MaxRepetitions lower.
	// See comments in https://github.com/gosnmp/gosnmp/issues/100
	MaxRepetitions uint32

	// NonRepeaters sets the GETBULK max-repeaters used by BulkWalk*.
	// (default: 0 as per RFC 1905)
	NonRepeaters int

	// UseUnconnectedUDPSocket if set, changes net.Conn to be unconnected UDP socket.
	// Some multi-homed network gear isn't smart enough to send SNMP responses
	// from the address it received the requests on. To work around that,
	// we open unconnected UDP socket and use sendto/recvfrom.
	UseUnconnectedUDPSocket bool

	// If Control is not nil, it is called after creating the network
	// connection but before actually dialing.
	//
	// Can be used when UseUnconnectedUDPSocket is set to false or when using TCP
	// in scenario where specific options on the underlying socket are nedded.
	// Refer to https://pkg.go.dev/net#Dialer
	Control func(network, address string, c syscall.RawConn) error

	// LocalAddr is the local address in the format "address:port" to use when connecting an Target address.
	// If the port parameter is empty or "0", as in
	// "127.0.0.1:" or "[::1]:0", a port number is automatically (random) chosen.
	LocalAddr string

	// netsnmp has '-C APPOPTS - set various application specific behaviours'
	//
	// - 'c: do not check returned OIDs are increasing' - use AppOpts = map[string]interface{"c":true} with
	//   Walk() or BulkWalk(). The library user needs to implement their own policy for terminating walks.
	// - 'p,i,I,t,E' -> pull requests welcome
	AppOpts map[string]interface{}

	// MsgFlags is an SNMPV3 MsgFlags.
	MsgFlags SnmpV3MsgFlags

	// SecurityModel is an SNMPV3 Security Model.
	SecurityModel SnmpV3SecurityModel

	// SecurityParameters is an SNMPV3 Security Model parameters struct.
	SecurityParameters SnmpV3SecurityParameters

	// ContextEngineID is SNMPV3 ContextEngineID in ScopedPDU.
	ContextEngineID string

	// ContextName is SNMPV3 ContextName in ScopedPDU
	ContextName string
	// contains filtered or unexported fields
}

GoSNMP represents GoSNMP library state.

func (*GoSNMP) BulkWalk added in v1.3.0

func (x *GoSNMP) BulkWalk(rootOid string, walkFn WalkFunc) error

BulkWalk retrieves a subtree of values using GETBULK. As the tree is walked walkFn is called for each new value. The function immediately returns an error if either there is an underlaying SNMP error (e.g. GetBulk fails), or if walkFn returns an error.

func (*GoSNMP) BulkWalkAll added in v1.3.0

func (x *GoSNMP) BulkWalkAll(rootOid string) (results []SnmpPDU, err error)

BulkWalkAll is similar to BulkWalk but returns a filled array of all values rather than using a callback function to stream results. Caution: if you have set x.AppOpts to 'c', BulkWalkAll may loop indefinitely and cause an Out Of Memory - use BulkWalk instead.

func (*GoSNMP) Check added in v1.10.0

func (x *GoSNMP) Check(err error)

Check makes checking errors easy, so they actually get a minimal check

func (*GoSNMP) Connect added in v1.2.0

func (x *GoSNMP) Connect() error

Connect creates and opens a socket. Because UDP is a connectionless protocol, you won't know if the remote host is responding until you send packets. Neither will you know if the host is regularly disappearing and reappearing.

For historical reasons (ie this is part of the public API), the method won't be renamed to Dial().

func (*GoSNMP) ConnectIPv4 added in v1.11.0

func (x *GoSNMP) ConnectIPv4() error

ConnectIPv4 forces an IPv4-only connection

func (*GoSNMP) ConnectIPv6 added in v1.11.0

func (x *GoSNMP) ConnectIPv6() error

ConnectIPv6 forces an IPv6-only connection

func (*GoSNMP) Get

func (x *GoSNMP) Get(oids []string) (result *SnmpPacket, err error)

Get sends an SNMP GET request

func (*GoSNMP) GetBulk added in v1.2.0

func (x *GoSNMP) GetBulk(oids []string, nonRepeaters uint8, maxRepetitions uint32) (result *SnmpPacket, err error)

GetBulk sends an SNMP GETBULK request

For maxRepetitions greater than 255, use BulkWalk() or BulkWalkAll()

func (*GoSNMP) GetNext added in v1.2.0

func (x *GoSNMP) GetNext(oids []string) (result *SnmpPacket, err error)

GetNext sends an SNMP GETNEXT request

func (*GoSNMP) SendTrap added in v1.10.0

func (x *GoSNMP) SendTrap(trap SnmpTrap) (result *SnmpPacket, err error)

SendTrap sends a SNMP Trap

pdus[0] can a pdu of Type TimeTicks (with the desired uint32 epoch time). Otherwise a TimeTicks pdu will be prepended, with time set to now. This mirrors the behaviour of the Net-SNMP command-line tools.

SendTrap doesn't wait for a return packet from the NMS (Network Management Station).

See also Listen() and examples for creating an NMS.

NOTE: the trap code is currently unreliable when working with snmpv3 - pull requests welcome

func (*GoSNMP) Set added in v1.2.0

func (x *GoSNMP) Set(pdus []SnmpPDU) (result *SnmpPacket, err error)

Set sends an SNMP SET request

func (*GoSNMP) SetMsgID added in v1.14.0

func (x *GoSNMP) SetMsgID(msgID uint32)

SetMsgID sets the base ID value for future messages

func (*GoSNMP) SetRequestID added in v1.14.0

func (x *GoSNMP) SetRequestID(reqID uint32)

SetRequestID sets the base ID value for future requests

func (*GoSNMP) SnmpDecodePacket added in v1.13.0

func (x *GoSNMP) SnmpDecodePacket(resp []byte) (*SnmpPacket, error)

SnmpDecodePacket exposes SNMP packet parsing to external callers. This is useful for processing traffic from other sources and building test harnesses.

func (*GoSNMP) SnmpEncodePacket added in v1.13.0

func (x *GoSNMP) SnmpEncodePacket(pdutype PDUType, pdus []SnmpPDU, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error)

SnmpEncodePacket exposes SNMP packet generation to external callers. This is useful for generating traffic for use over separate transport stacks and creating traffic samples for test purposes.

func (*GoSNMP) UnmarshalTrap added in v1.10.0

func (x *GoSNMP) UnmarshalTrap(trap []byte, useResponseSecurityParameters bool) (result *SnmpPacket, err error)

UnmarshalTrap unpacks the SNMP Trap.

NOTE: the trap code is currently unreliable when working with snmpv3 - pull requests welcome

func (*GoSNMP) Walk

func (x *GoSNMP) Walk(rootOid string, walkFn WalkFunc) error

Walk retrieves a subtree of values using GETNEXT - a request is made for each value, unlike BulkWalk which does this operation in batches. As the tree is walked walkFn is called for each new value. The function immediately returns an error if either there is an underlaying SNMP error (e.g. GetNext fails), or if walkFn returns an error.

func (*GoSNMP) WalkAll added in v1.3.0

func (x *GoSNMP) WalkAll(rootOid string) (results []SnmpPDU, err error)

WalkAll is similar to Walk but returns a filled array of all values rather than using a callback function to stream results. Caution: if you have set x.AppOpts to 'c', WalkAll may loop indefinitely and cause an Out Of Memory - use Walk instead.

type Handler added in v1.12.0

type Handler interface {
	// Connect creates and opens a socket. Because UDP is a connectionless
	// protocol, you won't know if the remote host is responding until you send
	// packets. And if the host is regularly disappearing and reappearing, you won't
	// know if you've only done a Connect().
	//
	// For historical reasons (ie this is part of the public API), the method won't
	// be renamed.
	Connect() error

	// ConnectIPv4 connects using IPv4
	ConnectIPv4() error

	// ConnectIPv6 connects using IPv6
	ConnectIPv6() error

	// Get sends an SNMP GET request
	Get(oids []string) (result *SnmpPacket, err error)

	// GetBulk sends an SNMP GETBULK request
	GetBulk(oids []string, nonRepeaters uint8, maxRepetitions uint32) (result *SnmpPacket, err error)

	// GetNext sends an SNMP GETNEXT request
	GetNext(oids []string) (result *SnmpPacket, err error)

	// Walk retrieves a subtree of values using GETNEXT - a request is made for each
	// value, unlike BulkWalk which does this operation in batches. As the tree is
	// walked walkFn is called for each new value. The function immediately returns
	// an error if either there is an underlaying SNMP error (e.g. GetNext fails),
	// or if walkFn returns an error.
	Walk(rootOid string, walkFn WalkFunc) error

	// WalkAll is similar to Walk but returns a filled array of all values rather
	// than using a callback function to stream results.
	WalkAll(rootOid string) (results []SnmpPDU, err error)

	// BulkWalk retrieves a subtree of values using GETBULK. As the tree is
	// walked walkFn is called for each new value. The function immediately returns
	// an error if either there is an underlaying SNMP error (e.g. GetBulk fails),
	// or if walkFn returns an error.
	BulkWalk(rootOid string, walkFn WalkFunc) error

	// BulkWalkAll is similar to BulkWalk but returns a filled array of all values
	// rather than using a callback function to stream results.
	BulkWalkAll(rootOid string) (results []SnmpPDU, err error)

	// SendTrap sends a SNMP Trap (v2c/v3 only)
	//
	// pdus[0] can a pdu of Type TimeTicks (with the desired uint32 epoch
	// time).  Otherwise a TimeTicks pdu will be prepended, with time set to
	// now. This mirrors the behaviour of the Net-SNMP command-line tools.
	//
	// SendTrap doesn't wait for a return packet from the NMS (Network
	// Management Station).
	//
	// See also Listen() and examples for creating an NMS.
	SendTrap(trap SnmpTrap) (result *SnmpPacket, err error)

	// UnmarshalTrap unpacks the SNMP Trap.
	UnmarshalTrap(trap []byte, useResponseSecurityParameters bool) (result *SnmpPacket, err error)

	// Set sends an SNMP SET request
	Set(pdus []SnmpPDU) (result *SnmpPacket, err error)

	// Check makes checking errors easy, so they actually get a minimal check
	Check(err error)

	// Close closes the connection
	Close() error

	// Target gets the Target
	Target() string

	// SetTarget sets the Target
	SetTarget(target string)

	// Port gets the Port
	Port() uint16

	// SetPort sets the Port
	SetPort(port uint16)

	// Community gets the Community
	Community() string

	// SetCommunity sets the Community
	SetCommunity(community string)

	// Version gets the Version
	Version() SnmpVersion

	// SetVersion sets the Version
	SetVersion(version SnmpVersion)

	// Timeout gets the Timeout
	Timeout() time.Duration

	// SetTimeout sets the Timeout
	SetTimeout(timeout time.Duration)

	// Retries gets the Retries
	Retries() int

	// SetRetries sets the Retries
	SetRetries(retries int)

	// GetExponentialTimeout gets the ExponentialTimeout
	GetExponentialTimeout() bool

	// SetExponentialTimeout sets the ExponentialTimeout
	SetExponentialTimeout(value bool)

	// Logger gets the Logger
	Logger() Logger

	// SetLogger sets the Logger
	SetLogger(logger Logger)

	// MaxOids gets the MaxOids
	MaxOids() int

	// SetMaxOids sets the MaxOids
	SetMaxOids(maxOids int)

	// MaxRepetitions gets the maxRepetitions
	MaxRepetitions() uint32

	// SetMaxRepetitions sets the maxRepetitions
	SetMaxRepetitions(maxRepetitions uint32)

	// NonRepeaters gets the nonRepeaters
	NonRepeaters() int

	// SetNonRepeaters sets the nonRepeaters
	SetNonRepeaters(nonRepeaters int)

	// MsgFlags gets the MsgFlags
	MsgFlags() SnmpV3MsgFlags

	// SetMsgFlags sets the MsgFlags
	SetMsgFlags(msgFlags SnmpV3MsgFlags)

	// SecurityModel gets the SecurityModel
	SecurityModel() SnmpV3SecurityModel

	// SetSecurityModel sets the SecurityModel
	SetSecurityModel(securityModel SnmpV3SecurityModel)

	// SecurityParameters gets the SecurityParameters
	SecurityParameters() SnmpV3SecurityParameters

	// SetSecurityParameters sets the SecurityParameters
	SetSecurityParameters(securityParameters SnmpV3SecurityParameters)

	// ContextEngineID gets the ContextEngineID
	ContextEngineID() string

	// SetContextEngineID sets the ContextEngineID
	SetContextEngineID(contextEngineID string)

	// ContextName gets the ContextName
	ContextName() string

	// SetContextName sets the ContextName
	SetContextName(contextName string)
}

Handler is a GoSNMP interface

Handler is provided to assist with testing using mocks

func NewHandler added in v1.12.0

func NewHandler() Handler

NewHandler creates a new Handler using gosnmp

type Logger added in v1.2.0

type Logger struct {
	// contains filtered or unexported fields
}

func NewLogger added in v1.35.2

func NewLogger(logger LoggerInterface) Logger

func (*Logger) Print added in v1.2.0

func (l *Logger) Print(v ...interface{})

func (*Logger) Printf added in v1.2.0

func (l *Logger) Printf(format string, v ...interface{})

type LoggerInterface added in v1.35.2

type LoggerInterface interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger For verbose logging to stdout: gosnmp_logger = NewLogger(log.New(os.Stdout, "", 0))

type PDUType added in v1.2.0

type PDUType byte

PDUType describes which SNMP Protocol Data Unit is being sent.

const (
	Sequence       PDUType = 0x30
	GetRequest     PDUType = 0xa0
	GetNextRequest PDUType = 0xa1
	GetResponse    PDUType = 0xa2
	SetRequest     PDUType = 0xa3
	Trap           PDUType = 0xa4 // v1
	GetBulkRequest PDUType = 0xa5
	InformRequest  PDUType = 0xa6
	SNMPv2Trap     PDUType = 0xa7 // v2c, v3
	Report         PDUType = 0xa8 // v3
)

The currently supported PDUType's

func (PDUType) String added in v1.35.3

func (i PDUType) String() string

type SNMPError added in v1.10.0

type SNMPError uint8

SNMPError is the type for standard SNMP errors.

const (
	NoError             SNMPError = iota // No error occurred. This code is also used in all request PDUs, since they have no error status to report.
	TooBig                               // The size of the Response-PDU would be too large to transport.
	NoSuchName                           // The name of a requested object was not found.
	BadValue                             // A value in the request didn't match the structure that the recipient of the request had for the object. For example, an object in the request was specified with an incorrect length or type.
	ReadOnly                             // An attempt was made to set a variable that has an Access value indicating that it is read-only.
	GenErr                               // An error occurred other than one indicated by a more specific error code in this table.
	NoAccess                             // Access was denied to the object for security reasons.
	WrongType                            // The object type in a variable binding is incorrect for the object.
	WrongLength                          // A variable binding specifies a length incorrect for the object.
	WrongEncoding                        // A variable binding specifies an encoding incorrect for the object.
	WrongValue                           // The value given in a variable binding is not possible for the object.
	NoCreation                           // A specified variable does not exist and cannot be created.
	InconsistentValue                    // A variable binding specifies a value that could be held by the variable but cannot be assigned to it at this time.
	ResourceUnavailable                  // An attempt to set a variable required a resource that is not available.
	CommitFailed                         // An attempt to set a particular variable failed.
	UndoFailed                           // An attempt to set a particular variable as part of a group of variables failed, and the attempt to then undo the setting of other variables was not successful.
	AuthorizationError                   // A problem occurred in authorization.
	NotWritable                          // The variable cannot be written or created.
	InconsistentName                     // The name in a variable binding specifies a variable that does not exist.
)

SNMP Errors

func (SNMPError) String added in v1.35.2

func (i SNMPError) String() string

type SnmpPDU

type SnmpPDU struct {
	// The value to be set by the SNMP set, or the value when
	// sending a trap
	Value interface{}

	// Name is an oid in string format eg ".1.3.6.1.4.9.27"
	Name string

	// The type of the value eg Integer
	Type Asn1BER
}

SnmpPDU will be used when doing SNMP Set's

type SnmpPacket

type SnmpPacket struct {
	Version            SnmpVersion
	MsgFlags           SnmpV3MsgFlags
	SecurityModel      SnmpV3SecurityModel
	SecurityParameters SnmpV3SecurityParameters // interface
	ContextEngineID    string
	ContextName        string
	Community          string
	PDUType            PDUType
	MsgID              uint32
	RequestID          uint32
	MsgMaxSize         uint32
	Error              SNMPError
	ErrorIndex         uint8
	NonRepeaters       uint8
	MaxRepetitions     uint32
	Variables          []SnmpPDU
	Logger             Logger

	// v1 traps have a very different format from v2c and v3 traps.
	//
	// These fields are set via the SnmpTrap parameter to SendTrap().
	SnmpTrap
}

SnmpPacket struct represents the entire SNMP Message or Sequence at the application layer.

func (*SnmpPacket) Check added in v1.10.0

func (packet *SnmpPacket) Check(err error)

Check makes checking errors easy, so they actually get a minimal check

func (*SnmpPacket) MarshalMsg added in v1.10.0

func (packet *SnmpPacket) MarshalMsg() ([]byte, error)

MarshalMsg marshalls a snmp packet, ready for sending across the wire

func (*SnmpPacket) SafeString added in v1.35.3

func (packet *SnmpPacket) SafeString() string

type SnmpTrap added in v1.10.0

type SnmpTrap struct {
	Variables []SnmpPDU

	// If true, the trap is an InformRequest, not a trap. This has no effect on
	// v1 traps, as Inform is not part of the v1 protocol.
	IsInform bool

	// These fields are required for SNMPV1 Trap Headers
	Enterprise   string
	AgentAddress string
	GenericTrap  int
	SpecificTrap int
	Timestamp    uint
}

SnmpTrap is used to define a SNMP trap, and is passed into SendTrap

type SnmpV3AuthProtocol added in v1.10.0

type SnmpV3AuthProtocol uint8

SnmpV3AuthProtocol describes the authentication protocol in use by an authenticated SnmpV3 connection.

const (
	NoAuth SnmpV3AuthProtocol = 1
	MD5    SnmpV3AuthProtocol = 2
	SHA    SnmpV3AuthProtocol = 3
	SHA224 SnmpV3AuthProtocol = 4
	SHA256 SnmpV3AuthProtocol = 5
	SHA384 SnmpV3AuthProtocol = 6
	SHA512 SnmpV3AuthProtocol = 7
)

NoAuth, MD5, and SHA are implemented

func (SnmpV3AuthProtocol) HashType added in v1.35.2

func (authProtocol SnmpV3AuthProtocol) HashType() crypto.Hash

HashType maps the AuthProtocol's hash type to an actual crypto.Hash object.

func (SnmpV3AuthProtocol) String added in v1.35.2

func (i SnmpV3AuthProtocol) String() string

type SnmpV3MsgFlags added in v1.10.0

type SnmpV3MsgFlags uint8

SnmpV3MsgFlags contains various message flags to describe Authentication, Privacy, and whether a report PDU must be sent.

const (
	NoAuthNoPriv SnmpV3MsgFlags = 0x0 // No authentication, and no privacy
	AuthNoPriv   SnmpV3MsgFlags = 0x1 // Authentication and no privacy
	AuthPriv     SnmpV3MsgFlags = 0x3 // Authentication and privacy
	Reportable   SnmpV3MsgFlags = 0x4 // Report PDU must be sent.
)

Possible values of SnmpV3MsgFlags

func (SnmpV3MsgFlags) String added in v1.35.3

func (i SnmpV3MsgFlags) String() string

type SnmpV3PrivProtocol added in v1.10.0

type SnmpV3PrivProtocol uint8

SnmpV3PrivProtocol is the privacy protocol in use by an private SnmpV3 connection.

const (
	NoPriv  SnmpV3PrivProtocol = 1
	DES     SnmpV3PrivProtocol = 2
	AES     SnmpV3PrivProtocol = 3
	AES192  SnmpV3PrivProtocol = 4 // Blumenthal-AES192
	AES256  SnmpV3PrivProtocol = 5 // Blumenthal-AES256
	AES192C SnmpV3PrivProtocol = 6 // Reeder-AES192
	AES256C SnmpV3PrivProtocol = 7 // Reeder-AES256
)

NoPriv, DES implemented, AES planned Changed: AES192, AES256, AES192C, AES256C added

func (SnmpV3PrivProtocol) String added in v1.35.2

func (i SnmpV3PrivProtocol) String() string

type SnmpV3SecurityModel added in v1.10.0

type SnmpV3SecurityModel uint8

SnmpV3SecurityModel describes the security model used by a SnmpV3 connection

const (
	UserSecurityModel SnmpV3SecurityModel = 3
)

UserSecurityModel is the only SnmpV3SecurityModel currently implemented.

func (SnmpV3SecurityModel) String added in v1.35.3

func (i SnmpV3SecurityModel) String() string

type SnmpV3SecurityParameters added in v1.10.0

type SnmpV3SecurityParameters interface {
	Log()
	Copy() SnmpV3SecurityParameters
	Description() string
	SafeString() string
	// contains filtered or unexported methods
}

SnmpV3SecurityParameters is a generic interface type to contain various implementations of SnmpV3SecurityParameters

type SnmpVersion

type SnmpVersion uint8

SnmpVersion 1, 2c and 3 implemented

const (
	Version1  SnmpVersion = 0x0
	Version2c SnmpVersion = 0x1
	Version3  SnmpVersion = 0x3
)

SnmpVersion 1, 2c and 3 implemented

func (SnmpVersion) String

func (s SnmpVersion) String() string

type TrapHandlerFunc added in v1.35.2

type TrapHandlerFunc func(s *SnmpPacket, u *net.UDPAddr)

TrapHandlerFunc is a callback function type which receives SNMP Trap and Inform packets when they are received. If this callback is null, Trap and Inform PDUs will not be received (Inform responses will still be sent, however). This callback should not modify the contents of the SnmpPacket nor the UDPAddr passed to it, and it should copy out any values it wishes to use instead of retaining references in order to avoid memory fragmentation.

The general effect of received Trap and Inform packets do not differ for the receiver, and the response is handled by the caller of the handler, so there is no need for the application to handle Informs any different than Traps. Nonetheless, the packet's Type field can be examined to determine what type of event this is for e.g. statistics gathering functions, etc.

type TrapListener added in v1.10.0

type TrapListener struct {
	sync.Mutex

	// Params is a reference to the TrapListener's "parent" GoSNMP instance.
	Params *GoSNMP

	// OnNewTrap handles incoming Trap and Inform PDUs.
	OnNewTrap TrapHandlerFunc
	// contains filtered or unexported fields
}

A TrapListener defines parameters for running a SNMP Trap receiver. nil values will be replaced by default values.

func NewTrapListener added in v1.10.0

func NewTrapListener() *TrapListener

NewTrapListener returns an initialized TrapListener.

NOTE: the trap code is currently unreliable when working with snmpv3 - pull requests welcome

func (*TrapListener) Close added in v1.10.0

func (t *TrapListener) Close()

Close terminates the listening on TrapListener socket

NOTE: the trap code is currently unreliable when working with snmpv3 - pull requests welcome

func (*TrapListener) Listen added in v1.10.0

func (t *TrapListener) Listen(addr string) error

Listen listens on the UDP address addr and calls the OnNewTrap function specified in *TrapListener for every trap received.

NOTE: the trap code is currently unreliable when working with snmpv3 - pull requests welcome

func (*TrapListener) Listening added in v1.10.0

func (t *TrapListener) Listening() <-chan bool

Listening returns a sentinel channel on which one can block until the listener is ready to receive requests.

NOTE: the trap code is currently unreliable when working with snmpv3 - pull requests welcome

func (*TrapListener) SendUDP added in v1.35.2

func (t *TrapListener) SendUDP(packet *SnmpPacket, addr *net.UDPAddr) error

SendUDP sends a given SnmpPacket to the provided address using the currently opened connection.

type UsmSecurityParameters added in v1.10.0

type UsmSecurityParameters struct {
	AuthoritativeEngineID    string
	AuthoritativeEngineBoots uint32
	AuthoritativeEngineTime  uint32
	UserName                 string
	AuthenticationParameters string
	PrivacyParameters        []byte

	AuthenticationProtocol SnmpV3AuthProtocol
	PrivacyProtocol        SnmpV3PrivProtocol

	AuthenticationPassphrase string
	PrivacyPassphrase        string

	SecretKey  []byte
	PrivacyKey []byte

	Logger Logger
	// contains filtered or unexported fields
}

UsmSecurityParameters is an implementation of SnmpV3SecurityParameters for the UserSecurityModel

func (*UsmSecurityParameters) Copy added in v1.10.0

Copy method for UsmSecurityParameters used to copy a SnmpV3SecurityParameters without knowing it's implementation

func (*UsmSecurityParameters) Description added in v1.35.2

func (sp *UsmSecurityParameters) Description() string

Description logs authentication paramater information to the provided GoSNMP Logger

func (*UsmSecurityParameters) Log added in v1.10.0

func (sp *UsmSecurityParameters) Log()

Log logs security paramater information to the provided GoSNMP Logger

func (*UsmSecurityParameters) SafeString added in v1.35.3

func (sp *UsmSecurityParameters) SafeString() string

SafeString returns a logging safe (no secrets) string of the UsmSecurityParameters

type VarBind

type VarBind struct {
	Name  asn1.ObjectIdentifier
	Value asn1.RawValue
}

VarBind struct represents an SNMP Varbind.

type WalkFunc added in v1.3.0

type WalkFunc func(dataUnit SnmpPDU) error

WalkFunc is the type of the function called for each data unit visited by the Walk function. If an error is returned processing stops.

Directories

Path Synopsis
examples
logger
building this code with the gosnmp_nodebug tag will completely disable compiler-level logging.
building this code with the gosnmp_nodebug tag will completely disable compiler-level logging.
walkexample
This program demonstrates BulkWalk.
This program demonstrates BulkWalk.
walktcpexample
This program demonstrates BulkWalk.
This program demonstrates BulkWalk.
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL