程序一分钟执行一次,检测路由器外网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)
}
|