fbpx

Python Script to Monitor MongoDB

Here is a Python script that checks the status of MongoDB and sends an email using the smtplib library:

				
					import smtplib
from pymongo import MongoClient

# Replace these with your own email and MongoDB connection details
sender_email = "myemail@example.com"
receiver_email = "otheremail@example.com"
mongodb_uri = "mongodb://localhost:27017"

# Connect to MongoDB
client = MongoClient(mongodb_uri)

# Check the status of the server
server_status = client.server_info()

# Set the subject and body of the email based on the server status
if "ok" in server_status and server_status["ok"] == 1.0:
    subject = "MongoDB status: OK"
    body = "The MongoDB server is running and responding to requests."
else:
    subject = "MongoDB status: ERROR"
    body = "There was a problem connecting to the MongoDB server."

# Send the email using SMTP
with smtplib.SMTP("localhost") as server:
    server.sendmail(sender_email, receiver_email, f"Subject: {subject}\n\n{body}")

				
			

This script uses the pymongo library to connect to MongoDB and check the status of the server. If the server is running and responding to requests, it sends an email with the subject “MongoDB status: OK”. If there is a problem connecting to the server, it sends an email with the subject “MongoDB status: ERROR”.

You will need to modify the script to use your own email address and MongoDB connection details. You will also need to have a local SMTP server running on your machine in order for the script to be able to send the email.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories