Welcome, guest | Sign In | My Account | Store | Cart

Use: To notify whomever that your IP address has changed if you have a non-static IP address and run a web server, game server, etc. Utilizes nested functions.

Python, 102 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
'****************************************************'
'Created by C. Nichols #B0)~                         '
'E-mail: oldnich@digitaldarknet.net                  '
'Created: 11/16/02                                   '
'Updated! 11/19/02                                   '
'Version: Python 2+                                  '
'Desc: IPy Notify for Micro$oft Windoze              '
'Use: To notify whomever that your IP address has    '
'changed if you have a non-static IP address and run '
'a web server, game server, etc.                     '
'****************************************************'
'                                                    '
'                                                    '
'                        #                           '
'                       0 0                          '
'~~~~~~~~~~~~~~~~~uuu~~~~U~~~~uuu~~~~~~~~~~~~~~~~~~~~'
"!!!!!!!!!!!!HERE'S LOOKING AT YOU KID!!!!!!!!!!!!!!!"
'****************************************************'
import os, os.path, string, time
import smtplib, socket
import win32api
# GLOBALS --------------------------------------------
(head,tail) = os.path.split(win32api.GetSystemDirectory()) # Get the win path.
(ldrive,os_root) = os.path.split(head) # Now get the local drive.

# The path will generally, if not always be c:\
# Path_log = ldrive+'\yourdir\IPy_Notify.log'
# will specify a dir of your choice - dir must be created.
Path_dat = ldrive+'IPy_Notify.dat' # Program requires this file to run properly.
Path_log = ldrive+'IPy_Notify.log'

Name = win32api.GetComputerName() # Get actual machine name.

#Add your server name, mail server, and email addresses receiving notification.
MailServer = 'smtp.yourprovider.com'
Address    = ['yourmail@yourprovider.com']
#Address    = ['yourmail@yourprovider.com','yourfriend@something.com'] # Multiple Addresses - uncomment will override above.
Frm_add    = 'yourmail@yourprovider.com' # From must be a valid e-mail address or the mail function will fail.

# If your ISP requires authentication, leave blank if unsure and test.
User       = ''
Pass       = ''

# Functions ------------------------------------------

def mail(to='',frm='',subj='',body='',server=''):
    try:
        message='From: %s\r\nTo: %s\r\nSubject: %s\r\n%s'%(frm,to,subj,body)            
        mail=smtplib.SMTP(server)
        mail.sendmail(frm,to,message)
        mail.close()
    except:
        try:
            # Logon to the server... If needed
            message='From: %s\r\nTo: %s\r\nSubject: %s\r\n%s'%(frm,to,subj,body)            
            mail=smtplib.SMTP(server)
            mail.login(User,Pass) 
            mail.sendmail(frm,to,message)
            mail.close()
        except:
            print 'ERROR: Unable to send notification! - '+time.ctime()
            open(Path_log,'a').write(time.ctime()+' \nERROR: Unable to send notification!')

def start():
    def getIP(name, path):
        print 'IPy Notify by C. Nichols, 2002.\n'
        ip = socket.gethostbyname(name)
        print 'Current ip: '+str(ip)
        open(path,'w').write(ip) #Save the current IP address.
        out(name,Path_dat)

    def out(name, path, stat=1):
        while stat:
            cur_ip = open(path,'r').readline()
            new_ip = str(socket.gethostbyname(name))
            if cur_ip==new_ip:
                print 'Sleeping...'
                time.sleep(15) # Sleep in seconds - adjust polling interval to your taste.
                print 'Polling: '+new_ip+', '+time.ctime()
            else:
                print 'IP address has changed: '+new_ip
                open(Path_log,'a').write(time.ctime()+'\nINFO: IP address has changed: '+new_ip)

                print 'sending notification...'
                for add in Address:
                    mail(to=add,frm=Frm_add,subj='Message from '+name,body='New IP address: '+new_ip+' assigned to '+name, server=MailServer)
                getIP(name,Path_dat) 
                stat=0

    getIP(Name,Path_dat)
    
# Run ------------------------------------------------
# Make sure this is started via the command line or
# by a .cmd file in startup - The command window can
# be hidden from a cmd file if you hate it like I do.
# Download Python @ www.python.org or PythonWin
# (active python) from www.activestate.com.
try:
    open(Path_log,'a').write(time.ctime()+' START: IP Polling\n------------------------------------------\n')
    start()
except:
    open(Path_log,'a').write(time.ctime()+' \nERROR: IPy Notify failed!')

7 comments

Justin Shaw 18 years, 10 months ago  # | flag

Nice.

Tony C 17 years, 2 months ago  # | flag

Can you update this so it works if you have DSL or Cable modem, or if you are behind a router ? Gethostbyname() will only return the INTERNAL address of your machine, which is not addressable from the outside world, UNLESS you know your cable/DSL modem address.

Charles Nichols (author) 16 years, 12 months ago  # | flag

Give this a try ;). This will give you the ip or the gateway, which is what you need. Just replace ip=socket.gethostbyname(blah) with this code.

import os,string

address={}

cmd = 'c:/windows/system32/ipconfig.exe /all' # whatever your path

junk, txtOut = os.popen2(cmd)

for x in txtOut.readlines():

 if x.find('IP Address') != -1:

      address.setdefault('ip',x.split(':')[-1].strip())

 if x.find('Default Gateway') != -1:

      address.setdefault('gate',x.split(':')[-1].strip())

print address['gate']

ip=address['gate'] #replace the old ip way with this.

print address['ip']

Jorge Besada 16 years, 10 months ago  # | flag

Detect current ip using http://checkip.dyndns.org. I added this function to read the ip address from http://checkip.dyndns.org

def readip(): import re, urllib f = urllib.urlopen('http://checkip.dyndns.org') s = f.read() m = re.search('([\d].[\d].[\d].[\d])', s) return m.group(0)

and changed the calls to socket.gethostbyname(name) by calls to the new function. The start() function ended up like this:

def start(): def getIP(name, path): ip = readip() print 'Current ip: '+str(ip) open(path,'w').write(ip) #Save the current IP address. out(name,Path_dat)

def out(name, path, stat=1):
    while stat:
        cur_ip = open(path,'r').readline()
        new_ip = readip()
        if cur_ip==new_ip:
            print 'Sleeping...'
            time.sleep(15) # Sleep in seconds - adjust polling interval to your taste.
            print 'Polling: '+new_ip+', '+time.ctime()
        else:
            print 'IP address has changed: '+new_ip
            open(Path_log,'a').write(time.ctime()+'\nINFO: IP address has changed: '+new_ip)
            print 'sending notification...'
            for add in Address:
                mail(to=add,frm=Frm_add,subj='Message from '+name,body='New IP address: '+new_ip+' assigned to '+name, server=MailServer)
            getIP(name,Path_dat)
            stat=0

getIP(Name,Path_dat)

Thanks for posting this useful program! Later I will work on updating the entry in www.dyndns.org, to have the complete package: detection of the IP change and update of the dns record in www.dyndns.org.

Jorge Besada 16 years, 10 months ago  # | flag

Detect current ip using http://checkip.dyndns.org - fixed format. My previous post did not display well, this is the fixed and shortened version.

I added this function to read the ip address from http://checkip.dyndns.org

There are other places that provide the same service (free); the function should work with many of them with minor o none modifications: it will parse the first occurrance of an ip-address like string and return it.

def readip():

import re, urllib

f = urllib.urlopen('http://checkip.dyndns.org')

s = f.read()

m = re.search('([\d].[\d].[\d].[\d])', s)

return m.group(0)

I changed the calls to socket.gethostbyname(name) by calls to the new function readip()

Thanks for posting this useful program! Later I will work on updating the entry in www.dyndns.org, to have the complete package: detection of the IP change and update of the dns record in www.dyndns.org.

muttu math 15 years, 2 months ago  # | flag

How can i check the change of ip adrress of a remote machine. I have some 10 machines in my network, and two machines ip adresses are overlapping with each other, so i want to know which are the two machines among those 10 machines that have the same ip adresses. Yogi

Ayaz Ahmed Khan 14 years, 8 months ago  # | flag

Re: Detect current ip using http://checkip.dyndns.org. This piece of code is simpler and cleaner:

In [18]: import urllib2
In [20]: urllib2.urlopen('http://whatismyip.org').read()
Out[20]: 'xxx.yyy.zzz.www'

--

Ayaz Ahmed Khan