A cosa serve?
Io ho utilizzato questo codice per verificare se una macchina collegata in rete era accesa oppure spenta.
Questo codice invia un’email quando non è più raggiungibile e quando ritorna attiva.
Codice Python
#!/usr/bin/python
import socket
import subprocess, platform
import smtplib, ssl
import datetime
import time
# check ping
def check_ping(sHost):
try:
output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
except Exception as e:
print 'ping False'
return 'False'
else:
print 'ping True'
return 'True'
# sent email with notification
def snet_email(body, host, receiver):
port = 465 # For SSL
smtp_server = "smtp.dominio.it"
sender_email = "utente@dominio.it" # Enter your address
receiver_email = receiver # Enter receiver address
password = "password"
subject = 'Allarme blackout !!! - {}'.format(host)
message = "From: %s\r\n" % sender_email + "To: %s\r\n" % receiver_email + "Subject: %s\r\n" % subject + "\r\n" + body + "\r\n"
context = ssl.create_default_context()
try:
server = smtplib.SMTP_SSL(smtp_server, port)
server.ehlo()
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
server.quit()
except Exception as e:
print e
return 'False'
else:
print 'mail send'
return 'True'
message_body = ''
pingBefore = ''
destinatari = ['prima-mail@gmail.com', 'seconda-mail@gmail.it']
#check the PING
while True:
host = '8.8.8.8'
ping_check = check_ping(host)
if ping_check == 'False' and pingBefore != ping_check:
message_body += 'SERVER: ' + 'DOWN' + "\r\nPING: " + "Failed\r\n"
pingBefore = ping_check
if ping_check == 'True' and pingBefore != ping_check:
message_body += 'SERVER: ' + 'UP :)' + "\r\nPING: " + "Passing\r\n"
pingBefore = ping_check
print message_body
#sent email notification
if message_body != '':
sent_message = snet_email(message_body, host, destinatari)
message_body = ''
time.sleep(300)