1 Star 0 Fork 1

爱狸狸爱生活/goboot

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
snmp_helper.go 2.74 KB
一键复制 编辑 原始数据 按行查看 历史
package snmp
import (
"bytes"
"fmt"
"gitee.com/ixxyy/goboot/utils/text/gstr"
"log"
"os/exec"
"strings"
"time"
)
const MibSleepSecond = time.Duration(500) * time.Millisecond
type Target struct {
Host string // ip地址
Oid string
Community string // snmp的团体字
Version string // 1|2c|3
}
func ExecSnmpWalkWithTarget(target Target) ([]string, string, error, int) {
return ExecSnmpWalk(target.Host, target.Oid, target.Community, target.Version)
}
// @title 执行snmp扫描命令
// @author xv 11/6/20 7:56 PM
// @param host 待扫描机器的ip地址
// @param oid
// @param community snmp的团体字
// @param version 1|2c|3
// @return (result, command, error, lineNum)
func ExecSnmpWalk(host string, oid string, community string, version string) ([]string, string, error, int) {
lines, command, err, count := ExecSnmpWalkOnce(host, oid, community, version)
if err != nil {
log.Println("retry with ", host, oid)
time.Sleep(MibSleepSecond)
lines, command, err, count = ExecSnmpWalkOnce(host, oid, community, version)
}
return lines, command, err, count
}
func ExecSnmpWalkOnce(host string, oid string, community string, version string) ([]string, string, error, int) {
args := []string{"-c", community, "-v", version, "-Cc", host, oid, "-r", "2", "-t", "10"}
commandName := "snmpwalk"
sepSpace := " "
strCommand := commandName + sepSpace + strings.Join(args, sepSpace)
cmd := exec.Command(commandName, args...)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Start()
if err != nil {
log.Println(fmt.Sprint(err)+": "+stderr.String(), "command#", strCommand)
return nil, strCommand, fmt.Errorf("err#%v, %s, command#%s", err.Error(), stderr.String(), strCommand), 0
}
err = cmd.Wait()
content := out.String()
//log.Println(content)
if err != nil {
log.Println(fmt.Sprint(err)+": "+stderr.String(), "command#", strCommand)
return nil, strCommand, fmt.Errorf("err#%v, %s, command#%s", err.Error(), stderr.String(), strCommand), 0
}
if len(content) == 0 {
errContent := "content is empty"
log.Println(errContent, strCommand, err)
return nil, strCommand, fmt.Errorf("err#%s", errContent), 0
}
// bugs, split the line without '='
lines := gstr.SplitAndTrim(content, "\n")
var lineMap = make(map[int]string, len(lines))
var fullLine string
var lineIndex int
for index, line := range lines {
if strings.Contains(line, SepEqual) {
lineMap[lineIndex] = fullLine
fullLine = line
lineIndex = index
} else {
fullLine = fullLine + "\r\n" + line
}
}
lineMap[lineIndex] = fullLine
var fixLines []string
for _, line := range lineMap {
//log.Printf("line[%d]#%s", k, line)
fixLines = append(fixLines, line)
}
return fixLines, strCommand, err, len(fixLines)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ixxyy/goboot.git
git@gitee.com:ixxyy/goboot.git
ixxyy
goboot
goboot
v0.1.19

搜索帮助