程式一分鐘執行一次,檢測路由器外網IP地址變更則自動傳送郵件,使用網易126 smtp協議傳送郵件,郵箱地址及授權碼請自行替換,getIp函式中的grep根據自己的網路卡資訊除錯替換
R6900路由器的交叉編譯語句:CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build xxxx.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
|
package main import ( "fmt" "gopkg.in/gomail.v2" "io/ioutil" "log" "os/exec" "strconv" "time" ) // 郵件主題 var subject = "路由器外網IP更新" //定義收件人 var mailTo = []string{ "****@qq.com" , "****@163.com" , } // ip地址 var ip string func main() { ip := getIp() send(ip) ticker := time.NewTicker(time.Minute * 1) for range ticker.C { newIp := getIp() if newIp != ip { ip = newIp send(ip) } } } // 獲取當前ip func getIp() string { return execCmd( "/usr/sbin/ip a | grep 'scope global ppp0' | awk '{print $2}'" ) } // 傳送郵件 func send(ip string) { body := "新的外網IP為:" + ip log.Print(body) err := execSend(mailTo, subject, body) if err != nil { log.Print( "mail send fail" ) log.Print(err) return } log.Print( "mail send successfully" ) } // 執行傳送 func execSend(mailTo []string, subject string, body string) error { mailConn := map [string]string{ "user" : "****@126.com" , "pass" : "********" , "host" : "smtp.126.com" , "port" : "25" , } port, _ := strconv.Atoi(mailConn[ "port" ]) m := gomail.NewMessage() m.SetHeader( "From" , m.FormatAddress(mailConn[ "user" ], "路由器R6900" )) m.SetHeader( "To" , mailTo...) //傳送給多個使用者 m.SetHeader( "Subject" , subject) //設定郵件主題 m.SetBody( "text/html" , body) //設定郵件正文 d := gomail.NewDialer(mailConn[ "host" ], port, mailConn[ "user" ], mailConn[ "pass" ]) err := d.DialAndSend(m) return err } // 執行shell命令 func execCmd(command string) string { cmd := exec.Command( "/bin/sh" , "-c" , command) stdout, _ := cmd.StdoutPipe() if err := cmd.Start(); err != nil { fmt.Println( "Execute failed when Start:" + err.Error()) return "" } out_bytes, _ := ioutil.ReadAll(stdout) stdout.Close() if err := cmd.Wait(); err != nil { fmt.Println( "Execute failed when Wait:" + err.Error()) return "" } return string(out_bytes) } |