Using Python to dynamically detect external IP concurrent mail to mailboxes under Windows

Source: Internet
Author: User

We know that the operators assigned to the dynamic IP,IP address over a period of time will be their own changes, which will require static address of the application inconvenience, such as building a server or remote control of the computer, this situation must know their own computer IP, using Python can easily detect and send mailboxes to the mailbox.

However, the personal network is generally through the router to the Internet, directly detect the computer's IP is not feasible, need to get the IP of the extranet. The intranet computer can be mapped to the external network via port mapping. The principle of detection is as follows:

1, through their own computer information is not very good to obtain the external network IP, fortunately there are some Lei Feng website can help us to detect, for example

Http://city.ip138.com/ip2city.asp

http://www.whereismyip.com/

Http://www.net.cn/static/customercare/yourip.asp

We just need to crawl to his web page and extract the IP.

2, the external network IP in the dynamic change, but also not every second is changing, so we just need to detect a bit at a time there is no change on the line

3, the script to boot startup is possible, but in the lower right corner to keep a thing really look uncomfortable, made service is perfect

Here's a look at the code:

(1) Script for IP detection ip_detect.py

#coding =utf-8
#IP_Detect. Pyimport smtplib,email,sys,socket,threading, Re, urllib2, timefrom email. Message Import messagefrom Threading Import Timerclass mail:def __init__ (self, smtpserver, Smtpport, Smtpuser, smtppwd, SE Ndto): Self. Server = Smtpserverself.port = Smtpportself.user = Smtpuserself.pwd = Smtppwdself.to = Sendtodef SendMessage (self, subj, C ontent): msg = Message () msg[' mime-version ']= ' 1.0 ' msg[' from '] = self. usermsg[' to ') = self. tomsg[' Subject ' = subjmsg.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,exprint ' 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 myipsmtpserver= ' SMTP. xxxx.com ' #邮件发送帐户的smtp服务器地址smtpPort = ' #邮件发送帐户的smtp服务器发送端口smtpUser = ' xxxx ' #邮件发送帐户名smtpPwd = ' xxxx ' #邮件发送帐户密码, I'm going to play the X example here, but man has to fill it out. sendto= ' XXXXX ' #接收邮箱地址def run: Body = "None" while True:getmyip=getmyip () Localip = Getmyip.getip ( ) IPList = SOCKET.GETHOSTBYNAME_EX (Socket.gethostname ()) Mailbody=str (iplist) + "External IP is:" +localipif MailBody! = Body:body = Mailbodymymail=mail (SmtpServer, Smtpport, Smtpuser, Smtppwd, SendTo) mymail.sendmessage ("IP message", Mailbody) Print bodytime.sleep (+) #十分钟够了吧if __name__== "__main__": Run ("")

(2) Script for window service winservice.py

Note To install the relevant module Pywin32, or import win32serviceutil error, here to download http://sourceforge.net/projects/pywin32/files/pywin32/

#coding =utf-8# winservice.py## A sample demonstrating the smallest possible service written in Python.import Win32serviceu Tilimport win32serviceimport win32eventfrom ip_detect import runclass 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'll use to wait on.        # the "Service Stop" request would set this event. Self.hwaitstop = win32event. CreateEvent (None, 0, 0, none) def svcstop (self): # Before we did anything, tell the SCM we is starting the stop        Process. Self. Reportservicestatus (Win32service.        service_stop_pending) # and set my event. Win32event. SetEvent (self.hwaitstop) def svcdorun (self): Run ("") # Put your program code here on the OK win32event. WaitForSingleObject (Self.hwaitstop, win32event. INFINITE) If __name__== ' __main__ ': Win32serviceutil. Handlecommandline (Smallestpythonservice) # The name in parentheses can be changed to something else and must match the class name;

How to use:

winservice.py installwinservice.py startwinservice.py Stop

OK, go to Window's service management to see if there is a smallest possible Python service, then manually turn the service into auto-start, then see if you can get the mail, each time you start the system or the external IP changes will send an email

This article takes advantage of some of the code of the predecessors , not a thank you

Using Python to dynamically detect external IP concurrent mail to mailboxes under Windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.