-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
287 lines (263 loc) · 7.51 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/go-ping/ping"
"github.com/jaypipes/ghw"
)
// notes
// this needs to print any raspberry pi's found as one liner if not using this
// package after pinging all ip addresses on the network
// arp -a | awk '{print $2,$4}' | grep -e b8:27:eb -e dc:a6:32 -e e4:5f:01)
// can use any arbitrary trigram for any physical address identifier for devices
var matchPI = []string{"b8:27:eb", "dc:a6:32", "e4:5f:01"}
var ipFound []string
// finds out if an item in slice matches
func find(slice []string, val string) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
// checks for root user
func isRoot() bool {
currentUser, err := user.Current()
if err != nil {
log.Fatalf("[isRoot] Unable to get current user: %s", err)
}
return currentUser.Username == "root"
}
// handles writing data to a filename at user home folder
func writer(coolArray []string, fileName string) {
dirname, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
file, err := os.OpenFile(fmt.Sprintf("%s/%s", dirname, fileName), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
datawriter := bufio.NewWriter(file)
for _, data := range coolArray {
_, _ = datawriter.WriteString(data + "\n")
}
datawriter.Flush()
file.Close()
}
// ping each ip address
func pingMe(ipAddress string, wg *sync.WaitGroup) {
pinger, err := ping.NewPinger(ipAddress)
if err != nil {
panic(err)
}
defer pinger.Stop()
// pinger.SetPrivileged(true)
pinger.Count = 1
pinger.Timeout = time.Millisecond * 800
pinger.OnRecv = func(pkt *ping.Packet) {
ipFound = append(ipFound, pkt.IPAddr.String())
}
err = pinger.Run()
if err != nil {
panic(err)
}
pinger.Stop()
}
func basicPing(ipAddress string, wg *sync.WaitGroup) {
_, err := exec.Command("ping", ipAddress).Output()
if err != nil {
fmt.Println(err)
}
}
// set ulimit properly using rlimit
func setLimit() {
var rLimit syscall.Rlimit
err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {
fmt.Println("Error Getting Rlimit ", err)
}
// fmt.Println(rLimit)
rLimit.Max = 999999
rLimit.Cur = 999999
err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {
fmt.Println("Error Setting Rlimit ", err)
}
err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {
fmt.Println("Error Getting Rlimit ", err)
}
// fmt.Println("Rlimit Final", rLimit)
}
// split out the arp results into slices for device list and pi list
func splitAndStore(dataFromArp []byte) {
var sliceOfMac = []string{}
var piSlice = []string{}
// specific formatting shit from the arp command itself
stringer := strings.Split(string(dataFromArp), "?")
for _, item := range stringer {
// skip wasted strings
if strings.Contains(item, "incomplete") {
continue
}
// iterate and parse out just the macaddress and ip address from the arp string slice
if strings.ContainsAny(item, "(") {
ipData := strings.Split(strings.Split(item, "(")[1], ")")[0]
macAddressData := strings.Split(strings.Split(strings.Split(strings.Split(item, "(")[1], ")")[1], "at")[1], "on")[0]
macAddressData = strings.TrimSpace(macAddressData)
vendorMac := strings.Split(macAddressData, ":")
vendorMacString := fmt.Sprintf("%s:%s:%s", vendorMac[0], vendorMac[1], vendorMac[2])
// check to see if mac address trigram matches any of the pi trigrams
found := find(matchPI, vendorMacString)
updatedString := fmt.Sprintf("ip:%v mac:%v", ipData, macAddressData)
sliceOfMac = append(sliceOfMac, updatedString)
if found {
piSlice = append(piSlice, updatedString)
}
} else {
continue
}
}
writer(sliceOfMac, "devicesfound.txt")
writer(piSlice, "pilist.txt")
fmt.Printf("Found %v devices including %v raspberry pis on the network in\n", len(sliceOfMac), len(piSlice))
}
// runs the arp command example output below
// $ arp -a
// (192.168.1.1) at cc:40:d0:54:4e:f4 on en0 ifscope [ethernet]
// (192.168.1.3) at d4:ab:cd:7:4:13 on en0 ifscope [ethernet]
// (192.168.1.7) at c8:69:cd:4a:c1:27 on en0 ifscope [ethernet]
// (192.168.1.13) at 68:d9:3c:8a:ad:5c on en0 ifscope [ethernet]
func runCmd() []byte {
out, err := exec.Command("sudo", "arp", "-a").Output()
if err != nil {
fmt.Printf("%s", err)
fmt.Println("fucked")
}
return out
}
// removes the last ip address trigram
func splitMe(item string) string {
last := strings.Split(item, ".")
s := last[len(last)-1]
item = strings.Replace(item, fmt.Sprintf(".%s", s), ".0/24", -1)
return item
}
// appends all the ip addresses as strings
func appendMe(item string) []string {
arr := []string{}
i := 1
item = strings.Replace(item, ".0/24", ".", -1)
for i < 256 {
arr = append(arr, fmt.Sprintf("%v%v", item, i))
i++
}
return arr
}
// gets the core count for the cpu info
func getCores() uint32 {
if runtime.GOOS == "darwin" {
out, err := exec.Command("sysctl", "machdep.cpu.thread_count").Output()
if err != nil {
fmt.Println(err)
}
var totalCores uint32
if _, err := fmt.Sscanf(string(out), "machdep.cpu.thread_count: %2d", &totalCores); err == nil {
return totalCores
}
} else {
cpuData, err := ghw.CPU()
if err != nil {
fmt.Println(err)
}
totalCores := cpuData.TotalCores
return totalCores
}
return 0
}
func main() {
// rootUserBool := isRoot()
// if !rootUserBool {
// fmt.Println("Must run as root / sudo")
// os.Exit(1)
// }
setLimit()
// used for goroutine to avoid memory errors
var w sync.WaitGroup
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
}
var currentIP string
var listOfIps []string
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
// = GET LOCAL IP ADDRESS
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
// fmt.Println("Current IP address : ", ipnet.IP.String())
currentIP = ipnet.IP.String()
listOfIps = append(listOfIps, currentIP)
if err != nil {
fmt.Println("fuck you")
fmt.Println(err)
}
}
}
}
// print all of the network interface options
for i, item := range listOfIps {
last := strings.Split(item, ".")
s := last[len(last)-1]
item = strings.Replace(item, fmt.Sprintf(".%s", s), ".0/24", -1)
fmt.Println("Option:", i, item)
}
// get user to select option number and press enter
fmt.Printf("You have %v cores available for processing.\n", getCores())
fmt.Print("select option for finding pi on what network: ")
input := bufio.NewScanner(os.Stdin)
input.Scan()
if len(input.Text()) > 1 {
panic("input is wrong, must be a single number")
}
startTime := time.Now()
i1, err := strconv.Atoi(input.Text())
if err != nil {
fmt.Println(i1)
}
// ensure to signify selected ip address
chosenIP := listOfIps[i1]
// convert selected ip address to 0/24
fixedip := splitMe(chosenIP)
// explode out selection to 1 through 256
stringArray := appendMe(fixedip)
// loop through ip range and ping each in parallel
for i := 0; i < len(stringArray); i++ {
w.Add(1)
go pingMe(stringArray[i], &w)
w.Done()
}
w.Wait()
// run arp command to get all pinged devices found
data := runCmd()
// iterate through found devices and save pilist and devicelist
splitAndStore(data)
// get time it took to run after the input
endTime := time.Now()
diff := endTime.Sub(startTime)
fmt.Printf("%f seconds\n", diff.Seconds())
fmt.Println("devicesfound.txt and pilist.txt saved to user's home folder")
}