我们知道,运营商给分配的都是动态IP,IP地址过一段时间会自己变化,这就给需要静态地址的应用带来不便,例如搭建服务器或者远程控制电脑,这种情况必须知道自己电脑的IP,利用Python可以方便的自动检测并向邮箱发送邮箱。
但是,个人网络一般都是通过路由器来上网,直接检测电脑的IP并不可行,需要得到外网的IP。内网电脑可以通过端口映射来映射到外网。检测的原理如下:
1、通过自己的电脑信息不太好获取外网IP,幸好有一些雷锋网站可以帮助我们来检测,例如
http://city.ip138.com/ip2city.asp
http://www.whereismyip.com/
http://www.net.cn/static/customercare/yourip.asp
我们只需要抓取到他的网页并把IP提取出来即可
2、外网IP在动态的变化,但是也不是每一秒都在变,因此我们只需要隔一段时间检测一下有没变化就行
3、把脚本做成开机启动固然可以,但是在右下角保留个东西实在看着不爽,做成服务就完美了
下面看代码:
(1)IP检测的脚本 IP_Detect.py
#coding=utf-8
#IP_Detect.py import smtplib,email,sys,socket,threading, re, urllib2, time from email.Message import Message from threading import Timer class Mail: def __init__(self, smtpServer, smtpPort, smtpUser, smtpPwd, sendTo): self.Server = smtpServer self.Port = smtpPort self.User = smtpUser self.Pwd = smtpPwd self.To = sendTo def sendmessage(self, subj, content): msg = Message() msg[\'Mime-Version\']=\'1.0\' msg[\'From\'] = self.User msg[\'To\'] = self.To msg[\'Subject\'] = subj msg.set_payload(content) try: server=smtplib.SMTP(self.Server, self.Port) server.ehlo() server.login(self.User, self.Pwd) except Exception: print \'connect smtp server failed!\' try: failed = server.sendmail(self.User, self.To,str(msg)) except Exception ,ex: print Exception,ex print \'Error - send failed\' else: print \'send succeed!\' class Getmyip: def visit(self,url): opener = urllib2.urlopen(url) if url == opener.geturl(): str = opener.read() return re.search(\'\d+\.\d+\.\d+\.\d+\',str).group(0) def getip(self): try: myip = self.visit("http://city.ip138.com/ip2city.asp") except: try: myip = self.visit("http://www.whereismyip.com/") except: try: myip = self.visit("http://www.net.cn/static/customercare/yourip.asp") except: myip = "So sorry!!!" return myip smtpServer=\'smtp.XXXX.com\' #邮件发送帐户的smtp服务器地址 smtpPort=\'25\' #邮件发送帐户的smtp服务器发送端口 smtpUser=\'XXXX\' #邮件发送帐户名 smtpPwd=\'XXXX\' #邮件发送帐户密码,我这里打X号示例,但老兄得填真的 sendTo=\'XXXXX\' #接收邮箱地址 def run(self): Body = "None" while True: getmyip=Getmyip() localip = getmyip.getip() ipList = socket.gethostbyname_ex(socket.gethostname()) MailBody=str(ipList)+" external IP is: "+localip if MailBody != Body: Body = MailBody mymail=Mail(smtpServer, smtpPort, smtpUser, smtpPwd, sendTo) mymail.sendmessage("IP message", MailBody) print Body time.sleep(600)#十分钟够了吧 if __name__=="__main__": run("")
(2)做成window服务的脚本 WinService.py
注意要安装一下相关的模块pywin32 ,否则import win32serviceutil会出错,到这里下载http://sourceforge.net/projects/pywin32/files/pywin32/
#coding=utf-8 # WinService.py # # A sample demonstrating the smallest possible service written in Python. import win32serviceutil import win32service import win32event from IP_Detect import run class SmallestPythonService(win32serviceutil.ServiceFramework): _svc_name_ = "SmallestPythonService" _svc_display_name_ = "The smallest possible Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # And set my event. win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): run("") # 把你的程序代码放到这里就OK了 win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) if __name__==\'__main__\': win32serviceutil.HandleCommandLine(SmallestPythonService) # 括号里的名字可以改成其他的,必须与class名字一致;
使用方法:
WinService.py install WinService.py start WinService.py stop
好了,去window的服务管理里看看有没有The smallest possible Python Service服务,然后手动把服务变成自动启动,然后看看能不能收到邮件,每次启动系统或者外部IP变化都会发邮件
本文利用了前辈的一些代码,就不一一致谢了