首页 > 解决方案 > 通过 Shell 脚本为 auth socket 插件执行 MySQL 命令

问题描述

我正在尝试创建一个 shell 脚本来自动化安装 PHP、MySQL 和 Nginx 的过程。

到目前为止,一切正常。但是,我无法将其身份验证方法从 切换auth_socketmysql_native_password

MYSQLPASS=$(openssl rand -base64 32)

sudo apt-get install -y expect

sudo apt-get install -y mysql-server

SECURE_MYSQL=$(expect -c "
set timeout 10
spawn mysql_secure_installation

expect \"Press y|Y for Yes, any other key for No: \"
send \"n\r\"

expect \"New password: \"
send \"$MYSQLPASS\r\"

expect \"Re-enter new password: \"
send \"$MYSQLPASS\r\"

expect \"Remove anonymous users? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Disallow root login remotely? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Remove test database and access to it? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Reload privilege tables now? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect eof
")

我必须在终端上手动完成。

sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<password>';
FLUSH PRIVILEGES;
exit

标签: mysqlbashshell

解决方案


你能试试这个吗?

MYSQLPASS=$(openssl rand -base64 32)

sudo apt-get install -y expect

sudo apt-get install -y mysql-server

SECURE_MYSQL=$(expect -c "
set timeout 10
spawn mysql_secure_installation

expect \"Press y|Y for Yes, any other key for No: \"
send \"n\r\"


expect \"Enter current password for root (enter for none):\"
send \"$MYSQLPASS\r\"
expect \"Change the root password?\"
send \"n\r\"


expect \"Remove anonymous users? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Disallow root login remotely? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Remove test database and access to it? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Reload privilege tables now? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect eof
")

echo "$SECURE_MYSQL"

相应地改变这部分

对于 MariaDb/MySQL 5.5:

expect "Enter current password for root (enter for none):"
  send -- "\r"
  expect "Set root password?"
  send -- "y\r"
  expect "New password:"
  send -- "${$MYSQLPASS}\r"
  expect "Re-enter new password:"
  send -- "${$MYSQLPASS}\r"

对于 MySQL 8

    expect "Enter password for user root:"
    send "$MYSQLPASS\r"
    
    expect "Change the password for root ? ((Press y|Y for Yes, any other key for No) :"
    send "y\r"
    
    expect "New password:"
    send "$MYSQLPASS\r"
    
    expect "Re-enter new password:"
    send "$MYSQLPASS\r"
    expect "Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) :"
send "y\r"

至于 MariaDB 10.x

       expect \"Enter current password for root (enter for none): \"
send \"n\r\"
expect \"Switch to unix_socket authentication \[Y/n\] \"
send \"n\r\"
expect \"Change the root password? \[Y/n\] \"
send \"y\r\"
expect \"New password: \"
send \"$MYSQLPASS\r\"
expect \"Re-enter new password: \"
send \"$MYSQLPASS\r\"

推荐阅读