Skip to content

Instantly share code, notes, and snippets.

@winston-wen
Last active September 10, 2021 03:35
Show Gist options
  • Save winston-wen/1d7f1941ab564c19ba757d2661b0c417 to your computer and use it in GitHub Desktop.
Save winston-wen/1d7f1941ab564c19ba757d2661b0c417 to your computer and use it in GitHub Desktop.
package main
import (
"net/smtp"
"log"
"os/exec"
"fmt"
)
func main() {
// Set up authentication information.
user := "[email protected]"
pswd := "blabla.password"
server := "mail.ustc.edu.cn"
wlt_host := "202.38.64.59"
auth := smtp.PlainAuth("", user, pswd, server)
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
hostname, err := exec.Command("hostname").Output()
if err != nil {
log.Fatal(err)
}
ip, err := exec.Command("/bin/ip", "route", "get", wlt_host).Output()
if err != nil {
log.Fatal(err)
}
msg := fmt.Sprintf("Subject: Labrador from %s\nTo: %s\n\n %s", hostname, user, ip)
dest := fmt.Sprintf("%s:%d", server, 25)
err = smtp.SendMail(dest, auth, user, []string{user}, []byte(msg))
if err != nil {
log.Fatal(err)
}
}
@winston-wen
Copy link
Author

winston-wen commented May 28, 2021

Create /etc/systemd/system/labrador.service

[Unit]
Description=Automatically send IP address to [email protected]
Wants=network-online.target
After=network.target network-online.target

[Service]
Type=simple
User=root
Restart=no
ExecStartPre=/bin/bash -c 'until host mail.ustc.edu.cn; do sleep 1; done'
ExecStart=/root/labrador

[Install]
WantedBy=multi-user.target

Then execute systemctl enable labrador.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment