Monday, May 7, 2012

Script to check if mysql is alive and restart if its not.

The script below is done in Bash, which can be used across all Linux platforms. The function of the script is to check if mysql is currently running properly else it will restart the service.


1. Navigate to /root.
$ cd /root

2. Create a new file
$ vim mysql.sh
or
$ vi mysql.sh
Also give the command below to check the logs
$ touch /root/mysql.log

3. Insert the following lines to the file
-----------------------------------
#!/bin/bash
/usr/bin/mysqladmin ping| grep 'mysqld is alive' > /dev/null 2>&1
if [ $? != 0 ]
then
        /etc/init.d/mysqld stop
        /etc/init.d/mysqld start
        echo Starting at `date`
fi
-----------------------------------

4.  Give execute permission.
$ chmod 755  mysql.sh

5. Set a cron to check it at regular intervals.
$ crontab -e
*/5 * * * * sh -x mysql.sh
(This will check every 5 minutes)

2 comments:

Anonymous said...

Thanks!
It is exactly what I was looking for

Tim Petersson said...

Im on debian 7 and using plesk
My mysql service is first of all start and stop using:
/etc/init.d/mysql stop
/etc/init.d/mysql start
without the "d"

Then when i run it i get this email:
+ grep mysql is alive
+ /usr/bin/mysqladmin ping
/usr/bin/mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost' (using password: NO)'
+ [ 1 != 0 ]
+ /etc/init.d/mysql stop
Stopping MySQL database server: mysqld.
+ /etc/init.d/mysql start
Starting MySQL database server: mysqld ..
Checking for tables which need an upgrade, are corrupt or were
not closed cleanly..
+ date
+ echo Starting at Mon May 26 09:48:05 CEST 2014
Starting at Mon May 26 09:48:05 CEST 2014

it starts and stops the server over and over again.

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews