Shell一键修改MySQL用户密码

Shell一键修改MySQL用户密码

摘要

Shell一键修改MySQL用户密码,参考lnmp

shell修改mysql密码

新建 changeMysqlPwd.sh ,内容如下


#!/bin/bash


MySQL_Bin="/usr/local/mysql/bin/mysql"
database_username=$1;
database_username_passwd=$2;

DB_Root_Password='root'

Do_Query()
{
    echo "$1" >/tmp/.mysql.tmp
    ${MySQL_Bin} --defaults-file=~/.my.cnf </tmp/.mysql.tmp
    return $?
}

# common ut method without args
Make_TempMycnf()
{
    cat >~/.my.cnf<<EOF
[client]
user=root
password='${DB_Root_Password}'
EOF

}

# common ut method without args
TempMycnf_Clean()
{
    if [ -s ~/.my.cnf ]; then
        rm -f ~/.my.cnf
    fi  
    if [ -s /tmp/.mysql.tmp ]; then
        rm -f /tmp/.mysql.tmp
    fi  
}

Make_TempMycnf

if [ "${database_username}" = "" ]; then
        echo "Database Username can't be empty!"
        exit 1
fi

if [ "${database_username_passwd}" = "" ]; then
        echo "Database Password can't be empty!"
        exit 1
fi

Do_Query "UPDATE mysql.user SET Password=PASSWORD('${database_username_passwd}') WHERE User='${database_username}' AND Host IN ('localhost', '127.0.0.1', '::1');"
if [ $? = "0" ] ;then
{
    echo "update $database_username pwd: $database_username_passwd , OK";
}
else
{
    echo "update $database_username pwd: $database_username_passwd , ERROR";
}
fi


Do_Query "FLUSH PRIVILEGES;"
if [ $? = "0" ] ;then
{
    echo "FLUSH update $database_username pwd: $database_username_passwd , OK";
}
else
{
    echo "FLUSH update $database_username pwd: $database_username_passwd , ERROR";
}
fi

TempMycnf_Clean

执行

chmod +x changeMysqlPwd.sh
./changeMysqlPwd.sh username newpwd