# setup
$ ifconfig eno1 |grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " " > /home/moonx/watch_ip_change/old_ip.txt
# 每分钟查看ip, 如果ip变了就把新ip发到邮箱
$ crontad -e
# 添加以下
*/1 * * * * bash /home/moonx/watch_ip_change/run.sh
run.sh
#!/bin/bash
device_name="eno1"
/sbin/ifconfig $device_name |grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " " > /home/moonx/watch_ip_change/new_ip.txt
cd /home/moonx/watch_ip_change/; python3 send_ip.py
/sbin/ifconfig $device_name |grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " " > /home/moonx/watch_ip_change/old_ip.txt
send_ip.py
import os
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def read_ip(ip_txt):
with open(ip_txt, 'r') as f:
ip = f.read().strip()
return ip
def send_email(send_email_flag, old_ip, new_ip):
if send_email_flag == False:
return
fromaddr = '782679034@qq.com'
password = '****************'
toaddrs = ['782679034@qq.com']
content = '新IP: ' + new_ip
textApart = MIMEText(content)
m = MIMEMultipart()
m.attach(textApart)
m['Subject'] = 'Rui的IP变了'
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
try:
server = smtplib.SMTP('smtp.qq.com')
server.login(fromaddr, password)
server.sendmail(fromaddr, toaddrs, m.as_string())
print('success')
with open("email.log", "a") as f:
f.write(now_time + ' 邮件发送成功!' + '之前IP: ' + old_ip + ' 变为: ' + new_ip + '\n')
server.quit()
except smtplib.SMTPException as e:
print('error:', e)
with open("email.log", "a") as f:
f.write(now_time + ' 邮件发送失败: ' + str(e) + '\n')
def main():
old_ip = read_ip("old_ip.txt")
new_ip = read_ip("new_ip.txt")
send_email_flag = old_ip != new_ip
send_email(send_email_flag, old_ip, new_ip)
if __name__ == "__main__":
main()