Skip to content

Instantly share code, notes, and snippets.

@mikedamoiseau
Last active March 30, 2017 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikedamoiseau/4ed7d30b17e1d65abde898352452799f to your computer and use it in GitHub Desktop.
Save mikedamoiseau/4ed7d30b17e1d65abde898352452799f to your computer and use it in GitHub Desktop.
Script to automatically relaunch Nginx and MySQL servers
#!/bin/bash
#settings
EMAIL="me@example.com"
SUBJECT="THE EMAIL SUBJECT"
# date
DATETIME=$(date +%F_%T)
DATE=$(date +"%Y-%m-%d")
# test nginx
function check_for_nginx() {
if [[ ! "$(/usr/sbin/service nginx status)" =~ "is running" ]]
then
echo "$DATETIME : restarting nginx..."
/usr/sbin/service nginx start
echo "Nginx server has been restarted: $DATETIME." | mail -s "$SUBJECT NGINX RESTARTED" "$EMAIL"
else
echo "$DATETIME : nginx is running"
fi
}
# test apache
function check_for_apache() {
if [[ ! "$(/usr/sbin/service apache2 status)" =~ "is running" ]]
then
echo "$DATETIME : restarting apache..."
/usr/sbin/service apache2 start
echo "Apache server has been restarted: $DATETIME." | mail -s "$SUBJECT APACHE RESTARTED" "$EMAIL"
else
echo "$DATETIME : apache is running"
fi
}
# test mysql
function check_for_mysql_old() {
if [[ ! "$(/usr/sbin/service mysql status)" =~ "start/running" ]]
then
echo "$DATETIME : restarting mysql..."
/usr/sbin/service mysql start
echo "MySQL server has been restarted: $DATETIME." | mail -s "$SUBJECT MYSQL RESTARTED" "$EMAIL"
else
echo "$DATETIME : mysql is running"
fi
}
# test mysql
function check_for_mysql() {
UP=$(pgrep mysql | wc -l);
if [ "$UP" -eq 0 ];
then
echo "$DATETIME : restarting mysql..."
/usr/sbin/service mysql start
echo "MySQL server has been restarted: $DATETIME." | mail -s "$SUBJECT MYSQL RESTARTED" "$EMAIL"
else
echo "$DATETIME : mysql is running"
fi
}
function lets_do_it_now() {
# check_for_nginx
check_for_apache
check_for_mysql
}
# We have everything, let's do it.
lets_do_it_now
@mikedamoiseau
Copy link
Author

Add the script to the cronjob with the command crontab -e:

*/10 * * * * /root/relaunch-services.sh >> /root/relaunch-services.log 2>&1

This will execute the script every 10 minutes and redirect the output to the log file (stdout and stderr)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment