-
Notifications
You must be signed in to change notification settings - Fork 0
/
unifimacreset.go
217 lines (178 loc) · 8.61 KB
/
unifimacreset.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
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"strings"
"github.com/gin-gonic/gin"
"github.com/kelseyhightower/envconfig"
)
func main() {
type ConfigSpecification struct {
Debug bool `default:"true"`
ValidateCertificates bool `default:"false"`
BaseURL string `default:"https://demo.ui.com"`
Username string `default:"admin"`
Password string `default:"password"`
}
var config ConfigSpecification
err := envconfig.Process("SwitchPortReset", &config)
if err != nil {
log.Fatal(err.Error())
}
type ResponseData struct {
Success bool `json:"success"`
Message string `json:"message"`
}
type ResetData struct {
MacAddress string `json:"mac"`
Port int64 `json:"port_idx"`
Command string `json:"cmd"`
}
if !config.Debug {
gin.SetMode(gin.ReleaseMode)
}
router := gin.Default()
// Setup
router.GET("/reset/:searchMac", func(context *gin.Context) {
searchMac := context.Param("searchMac")
cookieJar, err := cookiejar.New(nil)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error preparing cookie jar: " + err.Error()})
}
// Login
jsonLoginValue, err := json.Marshal(map[string]string{
"username": config.Username,
"password": config.Password,
})
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error logging in to UniFi server - processing JSON: " + err.Error()})
}
req, err := http.NewRequest("POST", config.BaseURL+"/api/login", bytes.NewBuffer(jsonLoginValue))
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error logging in to UniFi server - preparing request: " + err.Error()})
}
req.Header.Set("Origin", config.BaseURL)
req.Header.Set("Content-Type", "application/json")
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: !config.ValidateCertificates},
}
client := &http.Client{Jar: cookieJar, Transport: tr}
resp, err := client.Do(req)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error logging in to UniFi server: " + err.Error()})
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error logging in to UniFi server, returned status code: " + resp.Status + ". Error reading returned message: " + err.Error()})
}
bodyString := string(bodyBytes)
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error logging in to UniFi server, returned status code: " + resp.Status + ". Returned message: " + bodyString})
}
// Get list of sites
resp, err = client.Get(config.BaseURL + "/api/self/sites")
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of available sites from UniFi server: " + err.Error()})
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of available sites from UniFi server, returned status code: " + resp.Status + ". Error reading returned message: " + err.Error()})
}
bodyString := string(bodyBytes)
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of available sites from UniFi server, returned status code: " + resp.Status + ". Returned message: " + bodyString})
}
found := false
var jsonData interface{}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of available sites from UniFi server - reading from response into buffer: " + err.Error()})
}
err = json.Unmarshal(buf.Bytes(), &jsonData)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of available sites from UniFi server - processing JSON: " + err.Error()})
}
sitesData := jsonData.(map[string]interface{})
for _, siteJSON := range sitesData["data"].([]interface{}) {
siteName := siteJSON.(map[string]interface{})["name"].(string)
// Get clients
resp, err := client.Get(config.BaseURL + "/api/s/" + siteName + "/stat/sta")
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of clients from UniFi server: " + err.Error()})
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of clients from UniFi server, returned status code: " + resp.Status + ". Error reading returned message: " + err.Error()})
}
bodyString := string(bodyBytes)
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of clients from UniFi server, returned status code: " + resp.Status + ". Returned message: " + bodyString})
}
buf = new(bytes.Buffer)
_, err = buf.ReadFrom(resp.Body)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of clients from UniFi server - reading from response into buffer: " + err.Error()})
}
err = json.Unmarshal(buf.Bytes(), &jsonData)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error getting list of clients from UniFi server - processing JSON: " + err.Error()})
}
clientsData := jsonData.(map[string]interface{})
for _, clientJSON := range clientsData["data"].([]interface{}) {
// Find client
macAddress := clientJSON.(map[string]interface{})["mac"].(string)
if strings.ToLower(macAddress) == strings.ToLower(searchMac) && clientJSON.(map[string]interface{})["is_wired"].(bool) {
found = true
switchMac := clientJSON.(map[string]interface{})["sw_mac"].(string)
switchPort := clientJSON.(map[string]interface{})["sw_port"].(float64)
// Reset port power
resetValues := ResetData{
MacAddress: switchMac,
Port: int64(switchPort),
Command: "power-cycle",
}
jsonResetValue, err := json.Marshal(resetValues)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error requesting reset of switch port - processing JSON: " + err.Error()})
}
req, err = http.NewRequest("POST", config.BaseURL+"/api/s/"+siteName+"/cmd/devmgr", bytes.NewBuffer(jsonResetValue))
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error requesting reset of switch port - preparing request: " + err.Error()})
}
req.Header.Set("Origin", config.BaseURL)
req.Header.Set("Content-Type", "application/json")
resp, err = client.Do(req)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error requesting reset of switch port: " + err.Error()})
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error requesting reset of switch port, returned status code: " + resp.Status + ". Error reading returned message: " + err.Error()})
}
bodyString := string(bodyBytes)
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "Error requesting reset of switch port, returned status code: " + resp.Status + ". Returned message: " + bodyString})
}
context.JSON(http.StatusOK, ResponseData{Success: true, Message: "Successfully reset power to switch port connected to mac address " + strings.ToLower(searchMac)})
}
}
}
if !found {
context.AbortWithStatusJSON(http.StatusBadRequest, ResponseData{Success: false, Message: "No devices found on UniFi server with mac address " + strings.ToLower(searchMac)})
}
})
router.GET("/healthcheck", func(context *gin.Context) {
context.String(http.StatusOK, "OK")
})
router.Run(":9000")
}