[Tutor] Looking for peer review

Andrei Kulakov ak@silmarill.org
Thu, 11 Jul 2002 13:03:03 -0400


I think this would be much better done with dyndns type of service.
dyndns.org.

On Thu, Jul 11, 2002 at 12:48:53PM -0400, Joel Ricker wrote:
> Below is a program that I've been working on that reports changes in ipaddresses.  I work in a retail store and we have two other stores about an hour drive away.  Once a week the owner comes down and makes backups of our inventory and gives us copies of inventories from the other two stores.  The owner decided to set us all up with a broadband connection and use PCAnywhere to connect and make changes to the system.
> 
> Of course the problem is that the ip addresses of all the connections will change at least once a day.  When he complained about having to call us for the ip address whenever he wanted to login, I knew Python would do the trick :)
> 
> The purpose of this program is to check the ip address periodically and if it changes, connect to an smtp server and send an e-mail reporting the change.  That way, he should always have the current ip address of our system.
> 
> I'd like for everyone to critique my program and give me any pointers on making it better and helping me become a better python programmer.  This is my first "real" python program -- something that's not throw away code and that will be used by someone else. 
> 
> ## ipwatch.py
> import socket, getopt, sys, time, smtplib
> 
> def usage(evalue):
>     ''' Show instructions and pass exit evalue '''
>     
>     print
>     print "ipwatch by Joel Ricker (joel@prettyhipprogramming.com)"
>     print "Monitors current machines IP address and reports any changes by e-mail."
>     print    
>     print "Usage:python ipwatch.py --help | --to <to address> --from <from address> "
>     print "[--smtp <smtp address>] [--port <port>] [--user <username>] [--pass <password>] [--wait <minutes>]"    
>     print
>     print "Options:"
>     print "\t--help\tShows this help message."
>     print "\t--to\tE-mail address to send reports to."
>     print "\t--from\tE-mail address to set as reply to."
>     print "\t--smtp\tAddress of smtp server to send mail through."
>     print "\t\tDefaults to localhost."
>     print "\t--port\tPort address of smtp server. Defaults to 25"
>     print "\t--user\tIf smtp server requires authorization, the username to login as."
>     print "\t--pass\tIf smtp server requires authorization, the password to login as."
>     print "\t--wait\tTime in minutes to wait between ip address checks."
>     
>     sys.exit(evalue)    
>     
> 
> def get_addy():
>     try:
>         addy = socket.gethostbyname(socket.getfqdn())
>     except:
>         sys.stderr.write("Socket Error: Couldn't aquire address of this machine.")
>         sys.exit(2)
>     else:
>         return addy
>         
> def main():      
> 
>     # Load the file that holds the current ip address of this machine    
>     try:
>         f = file("ipwatch.dat", "r")
>         addy = f.readline()
>         f.close()
>     except:
>         f = file("ipwatch.dat", "w")
>         addy = get_addy()        
>         f.write(addy)
>         f.close()        
>     
>     # Load command line options
>     try:
>         opts, args = getopt.getopt(sys.argv[1:], "hs:p:t:f:u:p:w:",
>                                      ["help", "smtp=", "port=", "to=", "from=", "user=", "pass=", "wait="])
>     except getopt.GetoptError:
>         # print help information and exit:
>         usage(2)        
>     else:
>         if not len(opts):
>             usage(2)            
> 
>     smtpaddy = 'localhost'
>     port = 25
>     fromwho = None
>     towho = None
>     user = None
>     password = None
>     wait = None
> 
>     print opts
>     print args
>     # Process options
>     for o, a in opts:
>         
>         # Help - prints out the instructions for use
>         if o in ("-h", "--help"):
>             usage(0)            
>             
>         # SMTP - the address of the smtp server to send the e-mail through
>         if o in ("-s", "--smtp"):
>             smtpaddy = a
> 
>         # Port - port
>         if o in ("-p", "--port"):
>             port = a
> 
>         # To - the address to send the e-mail to
>         if o in ("-t", "--to"):
>             towho = a
> 
>         # From - the reply address
>         if o in ("-f", "--from"):
>             fromwho = a
>             
>         # Username - the username to login as if required
>         if o in ("-u", "--user"):
>             user = a
>             
>         # Password - the password of the smtp server if required
>         if o in ("-p", "--pass"):
>             password = a
> 
>         # Time - amount of time in minutes to wait
>         if o in ("-w", "--wait"):            
>             wait = int(a) * 60      
> 
>     # Check for required and valid command-line options
>     if towho is None:
>         sys.stderr.write("To address required.")
>         usage(2)        
>     if fromwho is None:
>         sys.stderr.write("From address required.")
>         usage(2)    
>     if wait < 300:
>         sys.stderr.write("Invalid wait value.")
>         usage(2)
>         
>         
>     
>     # Now we loop, checking the current address of the machine against the address stored
>     # in the file.  If we have a new address, we store that address in the file and report
>     # the new address by e-mail.  We're depending on Window's shutdown signal to stop
>     # properly
>     while (1):
>         newaddy = get_addy()
>         if addy != newaddy:
>             print "New addy: ", newaddy
>             f = open("ipwatch.dat", "w")
>             f.write(newaddy)
>             f.close()
>                
>             try:
>                 s = smtplib.connect(smtpaddy, port)
>                 if user is not None:                    
>                     try:
>                         s.login(user, password)
>                     except SMTPAuthenticationError:
>                         sys.stderr.write("Error logging into SMTP server.  Check username and password and re-attempt")
>                 s.sendmail(towho, fromwho, newaddy)
>                 s.quit()
>                 
> 
>             except SMTPException, reason:
>                 sys.stderr.write("SMTP Error: %s", (reason))
>             addy = newaddy
>         print "The current address is", addy
>         time.sleep(wait)   
>         
>     
> 
> if __name__ == "__main__":
>     main()
>     
> Thanks
> Joel

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org