简体   繁体   中英

MySQL root user password change automation

folks,

I am trying to automate MySQL root user user temporary password change.

Details:

OS Centos7, mysql Ver 8.0.19-10 for Linux on x86_64 (Percona Server (GPL), Release 10, Revision f446c04)

My script:

#!/bin/sh
PSW=$1
MYPASS = `grep 'temporary password' /var/log/mysqld.log|awk '{print $13}'`
echo $MYPASS
sleep 3
echo "ALTER USER 'root'@'localhost' IDENTIFIED WITH   mysql_native_password BY '$PSW';" >> /root/my.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> /root/my.sql
sleep 3
mysql --connect-expired-password -u root --password='$MYPASS' mysql < /root/my.sql
sleep 5                    

Script's logic

I execute a script which is called prepare_db.sh from shell with a command and pass PSW variable (want to change temp psw to this one)

sh prepare_db.sh Pass123

it grabs temp mysql root psw assigns it to a variable MYPASS creates my.sql file which looks like that:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Pass123';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;

when sql file is created script automatically tries to execute it with a command:

mysql --connect-expired-password -u root --password='$MYPASS' mysql < /root/my.sql

Problem

Everytime I get an error saying that access is dennied:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Strange thing

If I try to run same command from a shell, I get no error and password changes..

mysql --connect-expired-password -u root --password='e=F4D4N7<-gp' mysql < /root/my.sql

Please help me to find a mistake, or a solution how could I achieve my goal - automate roots temp password reset

Thank you in advance!

The issue is that you are using single quotes in your command. With single quotes, variables are not expanded.

So, you are literally sending $MYPASS as password, instead of the contents of the MYPASS variable!

Change it to double quotes:

mysql --connect-expired-password -u root --password="$MYPASS" mysql < /root/my.sql

A tip for the future: If you (temporarily) add set -x at the start of your script, you'll see each line printed before it gets executed, after evaluation. This way you'd also have spotted that there is a literal $MYPASS .


EDIT: As Cyrus mentioned in a comment , there is another issue to fix before this can work: Change /bin/sh to /bin/bash at the shebang of your script, and if you manually run it, use bash instead of sh .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM