Shell 用于检查 mysql 是启动还是关闭的脚本

Shell script to check if mysql is up or down

我想要一个 bash shell 脚本,我可以 运行 使用 cron 作业检查远程服务器上的 mysql 是否 运行ning .如果是,则什么都不做,其他启动服务器。

cronjob 将每分钟检查远程服务器是否处于活动状态(或不活动)mysql。我可以自己编写 cron 作业,但我需要有关 shell 脚本的帮助,该脚本检查远程 mysql 是启动还是关闭。检查后的响应是向上还是向下并不重要。但是检查很重要。

您可以使用下面的脚本

#!/bin/bash

USER=root
PASS=root123

mysqladmin -h remote_server_ip -u$USER -p$PASS processlist ###user should have mysql permission on remote server. Ideally you should use different user than root.

 if [ $? -eq 0 ]
        then
                echo "do nothing"
        else
                ssh remote_server_ip  ###remote server linux root server password should be shared with this server.
                service mysqld start
 fi

所选答案中的脚本效果很好,但需要您在本地主机上安装 MySQL 客户端。我需要类似的东西用于 Docker 容器并且不想安装 MySQL 客户端。这是我想出的:

# check for a connection to the database server
#
check=$(wget -O - -T 2 "http://$MYSQL_HOST:$MYSQL_PORT" 2>&1 | grep -o mariadb)

while [ -z "$check" ]; do
    # wait a moment
    #
    sleep 5s

    # check again
    #
    check=$(wget -O - -T 2 "http://$MYSQL_HOST:$MYSQL_PORT" 2>&1 | grep -o mariadb)
done

这有点不同,因为它将循环直到可以建立数据库连接。我还使用 MariaDB 而不是股票 MySQL 数据库。您可以通过将 grep -o mariadb 更改为其他内容来更改它 - 我不确定成功连接时 MySQL returns 是什么,因此您必须稍微尝试一下。