代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。