-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (93 loc) · 2.29 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
package main
import (
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
nested "github.com/antonfisher/nested-logrus-formatter"
log "github.com/sirupsen/logrus"
)
func main() {
log.SetFormatter(&nested.Formatter{
ShowFullLevel: true,
TrimMessages: true,
NoColors: true,
})
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
dynHosts, updateHost := GetDynHosts(os.Args[1])
var (
ip string
nochg uint
)
ip = GetIP()
for i, host := range dynHosts {
if updateHost[i] && UpdateDynHost(host, ip) {
nochg += 1
}
}
if nochg == uint(len(dynHosts)) {
log.Info("All IPs were up to date")
}
}
func GetIP() (ip string) {
ipGivers := [...]string{
"https://ipinfo.io/ip",
"http://checkip.dyndns.com/",
"https://api.ipify.org/?format=text",
"https://myexternalip.com/raw",
"http://whatismyip.akamai.com/"}
regex := regexp.MustCompile(`\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`)
failedCount := 0
for _, ipGiver := range ipGivers {
resp, err := http.Get(ipGiver)
if err != nil {
log.Debug("Could not get IP from " + ipGiver)
failedCount++
continue
}
body, err := ioutil.ReadAll(resp.Body)
ip = regex.FindString(string(body))
break
}
if failedCount == len(ipGivers) {
log.Fatal("Could not get public IP")
}
return
}
func GetUrl(urlTemplate, hostname, ip string) (url string) {
url = urlTemplate
url = strings.ReplaceAll(url, TEMPLATE_HOST, hostname)
url = strings.ReplaceAll(url, TEMPLATE_IP, ip)
return
}
func SendRequest(url, login, passwd string) string {
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Error(err)
}
req.SetBasicAuth(login, passwd)
resp, err := client.Do(req)
if err != nil {
log.Error(err)
}
bodyText, err := ioutil.ReadAll(resp.Body)
s := string(bodyText)
return s
}
func UpdateDynHost(host DynamicHost, ip string) (nochg bool) {
url := GetUrl(host.UrlTemplate, host.Hostname, ip)
resp := SendRequest(url, host.Login, host.Password)
nochg = false
if strings.Contains(resp, "good") {
log.Info("Update successful for " + host.Hostname + " : " + resp)
} else if strings.Contains(resp, "nochg") {
log.Debug("Update didn't do anything for " + host.Hostname + " : " + resp)
nochg = true
} else {
log.Error("Update failed for " + host.Hostname + " : " + resp)
}
return
}