-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnmap.go
91 lines (79 loc) · 1.6 KB
/
nmap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package nmap
import (
"fmt"
"os/exec"
"bytes"
"github.com/pkg/errors"
"encoding/xml"
)
type Nmap struct {
SystemPath string
Args []string
Ports string
Hosts string
Exclude string
Result []byte
}
func (n *Nmap) SetSystemPath(systemPath string) {
if systemPath != "" {
n.SystemPath = systemPath
}
}
func (n *Nmap) SetArgs(arg ...string) {
n.Args = arg
}
func (n *Nmap) SetPorts(ports string) {
n.Ports = ports
}
func (n *Nmap) SetHosts(hosts string) {
n.Hosts = hosts
}
// 排除扫描IP/IP段
func (n *Nmap) SetExclude(exclude string) {
n.Exclude = exclude
}
func (n *Nmap) Run() error {
var (
cmd *exec.Cmd
outb, errs bytes.Buffer
)
if n.Hosts != "" {
n.Args = append(n.Args, n.Hosts)
}
if n.Ports != "" {
n.Args = append(n.Args, "-p")
n.Args = append(n.Args, n.Ports)
}
if n.Exclude != "" {
n.Args = append(n.Args, "--exclude")
n.Args = append(n.Args, n.Exclude)
}
n.Args = append(n.Args, "-oX")
n.Args = append(n.Args, "-")
cmd = exec.Command(n.SystemPath, n.Args ...)
fmt.Println(cmd.Args)
cmd.Stdout = &outb
cmd.Stderr = &errs
err := cmd.Run()
if errs.Len() > 0 {
return errors.New(errs.String())
}
if err != nil {
return err
}
n.Result = outb.Bytes()
return nil
}
// Parse takes a byte array of nmap xml data and unmarshals it into an
// NmapRun struct. All elements are returned as strings, it is up to the caller
// to check and cast them to the proper type.
func (n *Nmap) Parse() (*NmapRun, error) {
r := &NmapRun{}
err := xml.Unmarshal(n.Result, r)
return r, err
}
func New() *Nmap {
return &Nmap{
SystemPath: "nmap",
}
}