欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 检测本机公网IP,变化时邮件通知

程序员文章站 2022-05-23 15:19:23
...
【完全转载】http://tomxu.iteye.com/blog/1289216
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:      heidanine
# file:        checkWapIp.py
# modified:  2011/03/20 01:40
#
###########################################
# 检测外网的Ip,发送到指定邮箱
###########################################
# 初期设置:
#    1. 填写 myMail -> 你的邮箱哦
#    2. 填写 mySmtp -> host 你自己的smtp服务器。 user/pwd 用户名和密码
#    3. 填写 testUrlParams -> 这个除了保留的地址,你可以多找几个,防止哪个网站不好用了。
# 测试脚本可否执行:
#    python checkWanIp.py
#    如果没什么问题就可以把这个脚本的执行交给cron了。
# 配置cron(需要root权限),每10分钟检测一次,可自己按习惯定。
#    crontab -e
#    输入:
#         */10 * * * *  python checkWapIp.py
#

import os
import time
import httplib
import urllib
import urllib2
import smtplib
from email.mime.text import MIMEText

################
## 我发邮件的邮箱地址
myMail = "XXXXXXXX@126.com"
################
# 先发给自己就行了,想发给别人再加就可以了
toMailList= [myMail\
            #,'111@163.com'\
]
################
# 发邮件的SMTP服务器设置
mySmtp = {"host": "smtp.XXX.com"\
     ,"user": "XXXXXXXX"\
     ,"pwd": "XXXXXXXX"\
}

################
#检测外网IP的网站列表
testUrlParams = [{'domain': 'ifconfig.me', 'uri': '/ip'}\
                ,{'domain': 'icanhazip.com', 'uri': ''}\
                ]
# log文件名
logFileName = 'checkWanIp.log'
# log初始内容
logList = ['']
# 保存上次IP信息的文件
lastInfoFileName = '.lastInfo'

def getWanIpInfo():
    '''
    取得外网IP
    '''
    ipInfo = ['']
    for urlParam in testUrlParams:
        ipInfo.append("\r\n----------")
        ipInfo.append("\r\nTest Server : http://" + urlParam['domain'] + urlParam['uri'])
        
        ip = getRequestIpInfo(urlParam)
        
        if ip is None:
            ipInfo.append("\r\nTest Fail!!!!!!!!!!!!!!!!!")
            ipInfo.append("\r\n----------")
        else:
            ipInfo.append("\r\nTest OK!")
            ipInfo.append("\r\nResult: \r\n")
            ipInfo.append(ip)
            ipInfo.append("\r\n----------")
            return "".join(ipInfo)

def getRequestIpInfo(urlParam):
    '''
    从指定的测试IP的网站得到当前电脑所在网络的外网IP
    param['domain'] : 域名 (用httplib这个包访问不要加"http://")
    param['uri'] : URI
    '''
    global logList
    ip = None
    try:
        con = httplib.HTTPConnection(urlParam['domain'])
        con.request('GET', urlParam['uri'])
        res = con.getresponse()
        if res.status == 200 :
            ip = res.read()
        con.close()
    except Exception, e:
        logList.append(str(e))
    return ip

def sendMail(subject, info):
    '''
    发送邮件到指定的邮箱
    subject: 主题
    info:  邮件内容
    '''
    global logList
    msg = MIMEText(info)
    msg['Subject'] = subject
    msg['From'] = myMail
    msg['To'] = ";".join(toMailList)
    
    try:
        s = smtplib.SMTP();
        s.connect(mySmtp['host'])
        s.login(mySmtp['user'], mySmtp['pwd'])
        s.sendmail(myMail, toMailList, msg.as_string())
        s.close()
        return True
    except Exception, e:
        logList.append(str(e))
        return False

def readFile(fileName):
    '''
    读文件内容
    '''
    global logList
    try:  
        # 打开文件读取文件内容
        f = open(fileName, 'r')
        try:
            return f.read()
        finally:
            f.close()
    except IOError:
        logList.append("\r\n" + fileName + " - Can't open the file! Your maybe first run the script, or confirm the Read permission!")
        return None

def writeFile(fileName, str):
    return writeFileByMode(fileName , str, 'w') # 追加模式

def writeLog(str):
    '''
    写Log文件
    '''
    print str
    return writeFileByMode(logFileName ,str, 'a') # 追加模式

def writeFileByMode(fileName, str, mode):
    '''
    写文件内容
    '''
    global logList
    if mode is None:
        mode = 'w' # 默认写模式
    try:
        # 写入文件内容
        f= open(fileName, mode)
        try:
            f.write(str)
            return True
        finally:
            f.close()
    except IOError:
        logList.append("\r\n" + fileName + " - Can't write the file! Please confirm the write permission")
        return False

if __name__ == '__main__':
    try:
        # 从网站上取得IP
        ipInfo = getWanIpInfo()
        logList.append(ipInfo)
        #读取上次保存的内容
        lastInfo = readFile(lastInfoFileName)
        # 判断和上次取得的内容是否有变化
        if lastInfo == ipInfo:
            logList.append("\r\n\r\n:) IP is not change!")
            print "".join(logList)
        else:
            # 把取得的内容存入文件中,下次用来进行比较
            writeFile(lastInfoFileName, ipInfo)
            logList.append("\r\n\r\nWrite new IP to '" + lastInfoFileName + "'")
            # 取得开始时间字符串
            timeStr = time.strftime('%Y-%m-%-d %H:%M:%S', time.localtime(time.time()))
            # 设置邮件主题
            subject = '[Get IP]host:buhe9(' + timeStr + ')'
            # 发送到指定邮箱
            sendMail(subject, ipInfo)
            #写入log
            logList.append("\r\n Subject: " + subject)
            logList.append("\r\n Send mail ok!")
            logList.append("\r\n■■■■■■■■■■■■■■■■■■■■■■■■■■■")
            writeLog("".join(logList))
    except Exception, e:
        writeLog(str(e))
相关标签: python 脚本