MerakiApiUtilities/deviceCheck.py

80 lines
No EOL
2.6 KiB
Python

#Imports and such.
import requests, time, smtplib, os
from datetime import datetime, timezone
from email.message import EmailMessage
from dotenv import load_dotenv
#Load environment variables, and then assign them to internal variables.
load_dotenv()
API_KEY = os.getenv("API_KEY")
NETWORK_ID = os.getenv("NETWORK_ID")
CLIENT_MAC = os.getenv("CLIENT_MAC")
CLIENT_NICK = os.getenv("CLIENT_NICK")
#Passes the API key to the header.
HEADERS = {
"X-Cisco-Meraki-API-Key": API_KEY
}
#Function to get the clients from the specified network.
def get_clients():
#Queries the Meraki API using the network ID, and runs a get command to get a response in .JSON format.
url = f"https://api.meraki.com/api/v1/networks/{NETWORK_ID}/clients"
response = requests.get(url, headers=HEADERS)
#Debugging print outs.
print("Status:", response.status_code)
print("Response:", response.text)
#Return the resopnse in .JSON form.
return response.json()
#Function to send email using SMTP.
def send_email(subject, body, to_email):
#SMTP credentials.
from_email = os.getenv("SMTP_EMAIL")
password = os.getenv("SMTP_PASS")
smtp_server = os.getenv("SMTP_SERVER")
smtp_port = os.getenv("SMTP_PORT")
#Create email object.
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = from_email
msg["To"] = to_email
msg.set_content(body)
# Connect to specified SMTP server, and then send the email.
with smtplib.SMTP_SSL(smtp_server, smtp_port) as smtp:
smtp.login(from_email, password)
smtp.send_message(msg)
while True:
#Constantly update the clients, and get the newest data.
clients = get_clients()
#Search thruogh the client list for the specified MAC address.
for client in clients:
#When it finds the specified MAC address, determine when it was last seen, and also set a variable for the current time.
if client["mac"] == CLIENT_MAC:
print("Status: " + client["status"])
print("IP Address: " + client["ip"])
last_seen = datetime.fromisoformat(client["lastSeen"].replace("Z", "+00:00"))
now = datetime.now(timezone.utc)
#If the client has not been seen for 3 minutes, send an alert email.
if (now - last_seen).seconds > 180:
print("Sending email alert...")
send_email(
subject="Meraki Alert",
body="Client " + CLIENT_NICK + "(" + CLIENT_MAC + ") is offline!",
to_email=os.getenv("SMTP_RECEIVER")
)
#Wait a minute before checking again.
time.sleep(60)