Link to home
Start Free TrialLog in
Avatar of JamesonJendreas
JamesonJendreas

asked on

Python Fun

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...
Avatar of JamesonJendreas
JamesonJendreas

ASKER

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)
ASKER CERTIFIED SOLUTION
Avatar of clockwatcher
clockwatcher

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial