要申請 GMail 應用程式密碼,需要開啟 兩步驟驗證
選取應用程式時,雖然有郵件,但要選擇 其他
#!/usr/bin/python3
import urllib.request
from ipaddress import ip_address
import smtplib
def GetExternalIP():
try:
ip_b = urllib.request.urlopen("https://api.ipify.org").read()
except:
return ''
ip_s = ip_b.decode('utf-8')
try:
ip_address(ip_s)
return ip_s
except:
return ''
def GetBackupIP():
try:
file = open('/tmp/ExternalIp.txt', 'r')
ip = file.readline()
file.close()
except:
return ''
return ip
def WriteBackupIP(ip):
try:
file = open('/tmp/ExternalIp.txt', 'w')
file.write(ip)
file.close()
except:
return
def SendMail(ip):
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()
smtp.login('name@gmail.com', 'lkmvemxzkegzrhwqj')
from_addr = 'name@gmail.com'
to_addr = 'name@yahoo.com.tw'
msg = 'Subject:External IP\n' + ip + '\n'
status = smtp.sendmail(from_addr, to_addr, msg)
if status == {}:
print('SendMail success!')
else:
print('SendMail fail!')
smtp.quit
external_ip = GetExternalIP()
print('external ip {}'.format(external_ip))
backup_ip = GetBackupIP()
print('backup ip {}'.format(backup_ip))
if external_ip != '':
if external_ip != backup_ip:
SendMail(external_ip)
WriteBackupIP(external_ip)
沒有留言:
張貼留言