Solved

Python Fun

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

Suggested Solutions

Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
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 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…

911 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

22 Experts available now in Live!

Get 1:1 Help Now