āáǎà

Email:findmsg@gmail.com

邮件获取公网ip地址

邮件获取公网ip地址


  • 邮件获取公司路由器公网ip脚本,方便下班回家远程:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import smtplib
import urllib2
import re
import time
from email.mime.text import MIMEText
mailto_list=["findmsg@gmail.com"] ##可以添加多个邮件地址
mail_host="smtp.126.com"
mail_user="xxxx"
mail_pass="xxxxxxx"
mail_postfix="126.com"
######################
def get_Public_ip():
    '''
    获取当前路由器公网ip地址
    '''
    url="http://members.3322.org/dyndns/getip"
    res=urllib2.urlopen(url).read()
    ipAddr=re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}",res)
    return ipAddr
    
def send_mail(to_list,sub,content):
    '''
    to_list:收件人列表
    sub:邮件主题
    content:邮件内容
    send_mail("email@126.com","sub","content")
    '''
    me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False
if __name__ == '__main__':
    ip_old="127.0.0.1"
    while(1):
        now_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        ip_new=get_Public_ip()[0]
        if ip_new == ip_old:
                print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" ip地址未发生变化"
                time.sleep(60)
                continue
        if send_mail(mailto_list,"[公网IP地址]",now_time+' 新公网IP地址:'+ip_new):
                print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" 邮件发送成功"
        else:
                print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+" 邮件发送失败"
                continue
        ip_old = ip_new

博文最后更新时间:


评论

  • 暂无评论

发表评论

博客统计

访问量:18422

博文总数:5 评论总数:161

原创5 翻译0 转载0