之前写在新浪博客里了,今天把它换到ITEye上来,直接copy过来。
买了VPS,已经不需要这么做了,不过我记忆力超差,我只能靠烂笔头儿,还是记录一下的比较好。
----------------------------------------------------------------------------------------------------------------------------------------
来源: 我的新浪博客
时间: 2011-03-22
自己家中的电脑有时候需要做为服务器,以便为了在公司用 或 给认识的人用。
原因..........
自己在花生壳申请了动态域名,但偶尔它也抽风,所以写了这个脚本:
定时得到网络的公网IP -> 发送到自己的邮箱
刚开始看了点python, 算练手了,
。
代码如下:
#!/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\n Test Server : http://" + urlParam['domain' ] + urlParam['uri' ])
ip = getRequestIpInfo(urlParam)
if ip is None :
ipInfo.append(" \r\n Test Fail!!!!!!!!!!!!!!!!!" )
ipInfo.append(" \r\n ----------" )
else :
ipInfo.append(" \r\n Test OK!" )
ipInfo.append(" \r\n Result: \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\n Write 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))
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com