背景:批量初始化机器的时候经常有个别机器SNMP连接不通导致机器调度不生效,把功能封装成借口,上线前可以批量检测。
snmp的文档比较少,抄袭还严重,做个笔记记录一下使用方法。
代码Demo:
package main import ( "fmt" g "github.com/gosnmp/gosnmp" "log" "net/http" "time" ) func snmpget(ip string)[]byte{ snmp := &g.GoSNMP{ Target: ip, Port: 161, Community: "public", Version: g.Version3, Timeout: time.Duration(30) * time.Second, SecurityModel: g.UserSecurityModel, MsgFlags: g.AuthNoPriv, //Authentication and no privacy SecurityParameters: &g.UsmSecurityParameters { UserName: "myUserName", //输入你设置的snmp用户名 AuthenticationProtocol: g.MD5, //经过身份验证的SnmpV3连接正在使用的身份验证协议。 AuthenticationPassphrase: "mypass", //输入你公司的密码 }, } err := snmp.Connect() if err != nil { log.Fatalf("Connect() err: %v", err) } defer snmp.Conn.Close() oids := []string{"1.3.6.1.2.1.1.5.0"} result, err := snmp.Get(oids) if err != nil { log.Fatalf("Get() err: %v", err) } fmt.Println(string(result.Variables[0].Value.([]byte))) return result.Variables[0].Value.([]byte) //for i, v := range result.Variables { // fmt.Printf("%d. oid: %s ", i, v.Name) // switch v.Type{ // case g.OctetString: // fmt.Printf("string: %s\n", string(v.Value.([]byte))) // default: // fmt.Printf("number: %d\n", g.ToBigInt(v.Value)) // } //} } func handle(w http.ResponseWriter,r *http.Request) { var ip string r.ParseForm() for k,v := range r.Form{ if k == "ip" { ip = v[0] } } if ip != ""{ hostname := snmpget(ip) w.Write(hostname) }else { w.Write([]byte("please input ip")) } } func main() { http.HandleFunc("/snmp",handle) http.ListenAndServe("0.0.0.0:8005",nil) }