Solved

Python Fun

Posted on 2014-11-03
2
301 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

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
This article will show the steps for installing Python on Ubuntu Operating System. I have created a virtual machine with Ubuntu Operating system 8.10 and this installing process also works with upgraded version of Ubuntu OS. For installing Py…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

808 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