Solved

Python Fun

Posted on 2014-11-03
2
299 Views
Last Modified: 2016-08-13
Having some fun with a Raspberry Pi, setting up a little Python script to run a ping, and if it fails, send me an email via gmail - I'm a novice in Python, but using google-fu I was able to do just that (and I have full understanding of how this is working).

What I'd like to achieve, is be able to use a list (in a txt file) where I can have either by line or CSV, a list of hosts to run the script on .    

import smtplib
import datetime
import os
import sys
import time
#Set Host
host = "histname.com"
def sendmail(message):
    debuglevel = 0
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login('username@gmail.com', 'password')

    from_addr= 'fromuser@gmail.com'
    to_addr= 'touser@gmail.com'
    subj = "Network Down", host
    date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

    message_text= message
    
    msg = "From: %s\nTo: %s\nSubject: %s\n Date: %s\n%s" % ( from_addr, to_addr, subj, date, message_text )

    server.sendmail(from_addr, to_addr, msg)
    server.quit()
def ping(ipaddress):
    os.system("clear")
    result = os.system("ping -c 5 %s" %(ipaddress))
    os.system("clear")
    return result


ip = host
bFailed=False
ictr=0
while True:
    result =ping(ip)
    if result != 0:
        print ('Ping failed', host) 
        if bFailed==False:
            mess = ("Is Down", host) 
            sendmail(mess)
        bFailed=True
    else:
        if bFailed==True:
            mess= ("Mesasge Body 2") 
            sendmail(mess)
        bFailed=False
        ictr += 1
        if ictr==1:
            print ('Ping Ok !')
            ictr=0
    time.sleep(50)

Open in new window



Note this is mostly for fun - I quickly built the same for powershell, but if I could get this to work the same on a raspberry pi...
0
Comment
Question by:JamesonJendreas
2 Comments
 
LVL 1

Author Comment

by:JamesonJendreas
ID: 40420938
I should mention that i have a text file /home/pi/hosts.txt that I'd like to run it against.   I just can't figure out how to jam those lines in as the host variable (and how that would work to loop through).  Is there a for-each type thing i can do (which makes it sound like I need to kind of re-work this)
0
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
ID: 40421777
Retrieving the list from a file is pretty simple:
hosts = open('/home/pi/hosts.txt', 'r').read().split('\n')

Open in new window


That would get you a lists of hosts that you can iterate over:
for host in hosts:
   do stuff

Open in new window


The tougher part (for someone new to the language) would probably be keeping track of your last result for each host-  your bFailed variable.  You'd typically do that with a dictionary.  Give the following a try:
import smtplib
import datetime
import os
import sys
import time
from collections import defaultdict

def sendmail(message):
    debuglevel = 0
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login('username@gmail.com', 'password')

    from_addr= 'fromuser@gmail.com'
    to_addr= 'touser@gmail.com'
    subj = "Network Down", host
    date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

    message_text= message
    
    msg = "From: %s\nTo: %s\nSubject: %s\n Date: %s\n%s" % ( from_addr, to_addr, subj, date, message_text )

    server.sendmail(from_addr, to_addr, msg)
    server.quit()

def ping(ipaddress):
    os.system("clear")
    result = os.system("ping -c 5 %s" %(ipaddress))
    os.system("clear")
    return result


hostfile = '/home/pi/hosts.txt'
hosts = open(hostfile, 'r').read().split("\n")
hostFailed = defaultdict(lambda: False)  #set up a dictionary whose default value for an undefined key is False

ictr=0
while True:
    for host in hosts:
        if len(host.strip(' ')) == 0:
            # the file has an empty line skip it
            continue
        ip = host
        result = ping(ip)
        if result != 0:
            print ('Ping failed', host) 
            if hostFailed[host]==False:
                mess = ("Is Down", host) 
                sendmail(mess)
            hostFailed[host]=True
        else:
            if hostFailed[host]==True:
                mess= ("Mesasge Body 2") 
                sendmail(mess)
            hostFailed[host]=False
            ictr += 1
            if ictr==1:
                print ('{0} Ping Ok !'.format(host))
                ictr=0
    time.sleep(50)

Open in new window

0
Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question