sean for sure, of course you're right. I'm bad (aka lazy) at shell scripting, so I asked ChatGPT to write it for me. Seems legit!
Me: Can you write a shell script that checks a redis server to see if it is online and send an email notification if it's down?
ChatGPT: Yes, here's a shell script that checks if a Redis server is online and sends an email notification if it's down:
#!/bin/bash
REDIS_HOST="localhost"
REDIS_PORT="6379"
EMAIL_ADDRESS="your-email@example.com"
EMAIL_SUBJECT="Redis server is down"
EMAIL_BODY="Redis server is not responding at ${REDIS_HOST}:${REDIS_PORT}."
redis-cli -h $REDIS_HOST -p $REDIS_PORT ping > /dev/null 2>&1
if [ $? -ne 0 ]
then
echo $EMAIL_BODY | mail -s "$EMAIL_SUBJECT" $EMAIL_ADDRESS
fi
In this script, you can replace localhost and 6379 with your Redis server's host and port. The script uses redis-cli to ping the Redis server and checks the exit code to see if the server is online. If the server is not responding, the script sends an email to the specified email address with the subject and body specified.
You will need to have the mail command installed on your system for the email notification to work.
Me: Can you have it not send repeat messages?
ChatGPT: Yes, you can modify the script to avoid sending repeat messages. One way to do this is to keep track of the previous state of the Redis server and only send an email if the state has changed. Here's an updated version of the script that implements this approach:
REDIS_HOST="localhost"
REDIS_PORT="6379"
EMAIL_ADDRESS="your-email@example.com"
EMAIL_SUBJECT="Redis server is down"
EMAIL_BODY="Redis server is not responding at ${REDIS_HOST}:${REDIS_PORT}."
STATE_FILE="/tmp/redis_state"
redis-cli -h $REDIS_HOST -p $REDIS_PORT ping > /dev/null 2>&1
if [ $? -ne 0 ]
then
if [ ! -f $STATE_FILE ] || grep -q "UP" $STATE_FILE
then
echo $EMAIL_BODY | mail -s "$EMAIL_SUBJECT" $EMAIL_ADDRESS
echo "DOWN" > $STATE_FILE
fi
else
if [ ! -f $STATE_FILE ] || grep -q "DOWN" $STATE_FILE
then
echo "UP" > $STATE_FILE
fi
fi
In this version of the script, the state of the Redis server is stored in a file specified by the STATE_FILE variable. If the Redis server is down and the previous state was "UP" (or the state file does not exist), the script sends an email and updates the state file to "DOWN". If the Redis server is up and the previous state was "DOWN" (or the state file does not exist), the script updates the state file to "UP".
With this modification, the script will only send an email if the Redis server's state has changed from the last time the script was run.