golang实现R6900路由器外网IP更新通知程序
程序一分钟执行一次,检测路由器外网IP地址变更则自动发送邮件,使用网易126 smtp协议发送邮件,邮箱地址及授权码请自行替换,getIp函数中的grep根据自己的网卡信息调试替换
R6900路由器的交叉编译语句:CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build xxxx.go
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) }