Solved

Python Fun

Posted on 2014-11-03
2
294 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
Comment Utility
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
Comment Utility
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

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Flask is a microframework for Python based on Werkzeug and Jinja 2. This requires you to have a good understanding of Python 2.7. Lets install Flask! To install Flask you can use a python repository for libraries tool called pip. Download this f…
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 …
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now