-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
206 lines (172 loc) · 4.72 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package main
import (
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/Juniper/go-netconf/netconf"
ps "github.com/kotakanbe/go-pingscanner"
"github.com/potato2003/actioncable-client-go"
"golang.org/x/crypto/ssh"
)
var (
cidr string
username string
password string
netconfPort string
websocketServerAddress string
useWSS bool
actionCableSubscription *actioncable.Subscription
serverToken string
channelName string
debug bool
refreshRate int
excludedIPs []string
excludedIPList string
)
// ChannelSubscriptionEventHandler ...
type ChannelSubscriptionEventHandler struct {
actioncable.SubscriptionEventHandler
}
// OnConnected ...
func (h *ChannelSubscriptionEventHandler) OnConnected(se *actioncable.SubscriptionEvent) {
log.Println("Connected to websocket server", websocketServerAddress)
}
// OnDisconnected ...
func (h *ChannelSubscriptionEventHandler) OnDisconnected(se *actioncable.SubscriptionEvent) {
fmt.Println("On disconnect")
}
func main() {
getAndParseFlags()
connectToWebsocketServer()
for {
err := scanAndSend()
if err != nil {
debugLog(err)
}
<-time.After(time.Duration(refreshRate) * time.Second)
}
}
func scanAndSend() error {
scanner := ps.PingScanner{
CIDR: cidr,
PingOptions: []string{
"-c1",
"-W1",
},
NumOfConcurrency: 100,
}
aliveIPs, err := scanner.Scan()
if err != nil {
return err
} else {
if len(aliveIPs) < 1 {
fmt.Println("No alive hosts")
}
debugLog("Found", len(aliveIPs), "hosts")
for _, ip := range aliveIPs {
if contains(excludedIPs, ip) {
continue
}
d, err := getNetconfDataForHost(ip + netconfPort)
if err != nil {
debugLog(err)
continue
} else {
go sendDataToWebsocketServer(d)
}
}
}
return nil
}
func getAndParseFlags() {
flag.StringVar(&cidr, "cidr", "", "CIDR block to scan")
flag.StringVar(&username, "username", "admin", "The SSH username")
flag.StringVar(&password, "password", "", "The SSH password")
flag.StringVar(&netconfPort, "port", ":22", "The NETCONF port to use")
flag.StringVar(&websocketServerAddress, "server", "", "The websocket server address")
flag.StringVar(&serverToken, "token", "", "Websocket server password")
flag.StringVar(&channelName, "channel", "", "Websocket server channel")
flag.IntVar(&refreshRate, "refresh", 30, "Data fetch rate (in seconds)")
flag.BoolVar(&useWSS, "secure", true, "Use 'wss:// to connect to the websocket server")
flag.BoolVar(&debug, "debug", false, "debug")
flag.StringVar(&excludedIPList, "excluded-ips", "", "Excluded IPs from scan (comma separated) e.g. -excluded-ips=1.1.1.1,2.2.2.2")
flag.Parse()
excludedIPs = strings.Split(excludedIPList, ",")
}
func getNetconfDataForHost(host string) (Data, error) {
debugLog("Trying", host)
var returnData Data
sshConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{ssh.Password(password)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: time.Second * 3,
}
session, err := netconf.DialSSH(host, sshConfig)
if err != nil {
return returnData, fmt.Errorf("%s - %s", host, err)
}
defer session.Close()
reply, err := session.Exec(netconf.MethodGet("xpath", ""))
err = xml.Unmarshal([]byte(reply.Data), &returnData)
if err != nil {
return returnData, err
}
return returnData, nil
}
func connectToWebsocketServer() (err error) {
var scheme string
if useWSS {
scheme = "wss"
} else {
scheme = "ws"
}
u, _ := url.Parse(fmt.Sprintf("%s://%s/cable?token=%s", scheme, websocketServerAddress, serverToken))
log.Println("Connecting to websocket server", u)
header := http.Header{}
header.Set("Origin", "127.0.0.1")
opt := actioncable.NewConsumerOptions()
opt.SetHeader(&header)
consumer, err := actioncable.CreateConsumer(u, opt)
if err != nil {
log.Println(err)
}
consumer.Connect()
params := map[string]interface{}{
"token": serverToken,
}
id := actioncable.NewChannelIdentifier(channelName, params)
actionCableSubscription, err = consumer.Subscriptions.Create(id)
if err != nil {
log.Println(err)
}
actionCableSubscription.SetHandler(&ChannelSubscriptionEventHandler{})
return err
}
func sendDataToWebsocketServer(d Data) {
j, _ := json.Marshal(d)
data := map[string]interface{}{
"device_data": string(j),
"time": time.Now().UnixNano() / int64(time.Millisecond),
}
actionCableSubscription.Perform("device_update", data)
}
func debugLog(a ...interface{}) {
if debug {
log.Println(a...)
}
}
func contains(elems []string, v string) bool {
for _, s := range elems {
if v == s {
return true
}
}
return false
}