forked from nxenon/port-scanner-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
130 lines (117 loc) · 2.59 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
"context"
"fmt"
"github.com/urfave/cli/v2"
"log"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"time"
)
var (
AppVersion = "development"
hostFlag = cli.StringSliceFlag{
Name: "host",
Required: true,
HasBeenSet: true,
Usage: "Target Host",
}
portFlag = cli.StringFlag{
Name: "port",
Required: false,
HasBeenSet: true,
Usage: "Ports Range e.g 80 or 1-1024 or 80,22,23",
DefaultText: `1-32000`,
Value: `1-32000`,
}
timeoutFlag = cli.StringFlag{
Name: "timeout",
Required: false,
HasBeenSet: true,
Usage: `TCP Timeout in Millisecond`,
Value: `500`,
}
parallelismFlag = cli.IntFlag{
Name: "parallelism",
Required: false,
HasBeenSet: true,
Usage: `How many parallel job to run`,
DefaultText: fmt.Sprintf(`%d`, runtime.NumCPU()),
Value: runtime.NumCPU(),
}
debugFlag = cli.BoolFlag{
Name: "debug",
Required: false,
Usage: `Enable Debug Logs`,
Value: false,
}
)
func main() {
cliApp := &cli.App{
Name: "port-scanner-go",
Version: AppVersion,
EnableBashCompletion: true,
Authors: []*cli.Author{
{
Name: "M Amin Nasiri",
Email: "[email protected]",
},
{
Name: "Dmytro Horkhover",
Email: "[email protected]",
},
},
Flags: []cli.Flag{
&hostFlag,
&portFlag,
&timeoutFlag,
¶llelismFlag,
&debugFlag,
},
Action: cliAction,
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
defer cancel()
if err := cliApp.RunContext(ctx, os.Args); err != nil {
log.Fatal(err)
}
}
func cliAction(c *cli.Context) error {
debug := c.Bool(debugFlag.Name)
tcpTimeout := time.Duration(c.Int(timeoutFlag.Name)) * time.Millisecond
concurrency := c.Int(parallelismFlag.Name)
hosts := c.StringSlice(hostFlag.Name)
var allIPs []string
for _, host := range hosts {
ips, err := nslookup(host)
if err != nil {
return err
}
allIPs = append(allIPs, ips...)
}
if len(allIPs) == 0 {
return fmt.Errorf(`nslookup returns empty list of IPs for hosts "%s"`, strings.Join(hosts, ", "))
}
portsList, err := getPortsList(c.String(portFlag.Name))
if err != nil {
return err
}
jobsCount := len(allIPs) * len(portsList)
executor := NewJobsExecutor(c.Context, jobsCount, concurrency)
defer executor.Shutdown()
for _, ip := range allIPs {
for _, port := range portsList {
s := scanner{
ip: ip,
port: port,
timeout: tcpTimeout,
debug: debug,
}
executor.Submit(s.scan)
}
}
return nil
}