forked from Ullaakut/nmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (66 loc) · 1.86 KB
/
main.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
package main
import (
"fmt"
"log"
"strings"
"github.com/Ullaakut/nmap"
)
func main() {
var (
resultBytes []byte
errorBytes []byte
)
// Equivalent to `/usr/local/bin/nmap -p 80,443,843 google.com facebook.com youtube.com`,
// with a 5 minute timeout.
s, err := nmap.NewScanner(
nmap.WithTargets("google.com", "facebook.com", "youtube.com"),
nmap.WithPorts("80,443,843"),
)
if err != nil {
log.Fatalf("unable to create nmap scanner: %v", err)
}
// Executes asynchronously, allowing results to be streamed in real time.
if err := s.RunAsync(); err != nil {
panic(err)
}
// Connect to stdout of scanner.
stdout := s.GetStdout()
// Connect to stderr of scanner.
stderr := s.GetStderr()
// Goroutine to watch for stdout and print to screen. Additionally it stores
// the bytes intoa variable for processiing later.
go func() {
for stdout.Scan() {
fmt.Println(stdout.Text())
resultBytes = append(resultBytes, stdout.Bytes()...)
}
}()
// Goroutine to watch for stderr and print to screen. Additionally it stores
// the bytes intoa variable for processiing later.
go func() {
for stderr.Scan() {
errorBytes = append(errorBytes, stderr.Bytes()...)
}
}()
// Blocks main until the scan has completed.
if err := s.Wait(); err != nil {
panic(err)
}
// Parsing the results into corresponding structs.
result, err := nmap.Parse(resultBytes)
// Parsing the results into the NmapError slice of our nmap Struct.
result.NmapErrors = strings.Split(string(errorBytes), "\n")
if err != nil {
panic(err)
}
// Use the results to print an example output
for _, host := range result.Hosts {
if len(host.Ports) == 0 || len(host.Addresses) == 0 {
continue
}
fmt.Printf("Host %q:\n", host.Addresses[0])
for _, port := range host.Ports {
fmt.Printf("\tPort %d/%s %s %s\n", port.ID, port.Protocol, port.State, port.Service.Name)
}
}
}