在我的 ubuntu 22.04 服务器中,我创建了一个 bash 脚本来设置我的服务器来为 laravel 应用程序提供服务,我执行的步骤之一是:
- 下载 mysql
- 创建非 root 用户,
- 授予非 root 用户所有权限。
我在我的 Bash 脚本中使用了这个代码:
#!/bin/bash
echo 'Downloading mysql, creating non-root database user with all grants and securing mysql'
sleep 3
sudo apt install mysql-server
# Prompt for database username
read -rp "Enter the database's owner username: " DB_USER
# Prompt for database password (first entry)
while true; do
read -rsp "Enter the database password: " DB_PASSWORD1
echo
read -rsp "Re-enter the database password: " DB_PASSWORD2
echo
if [ "$DB_PASSWORD1" = "$DB_PASSWORD2" ]; then
break
else
echo "Passwords did not match. Please try again."
fi
done
# Connect to MySQL
sudo mysql <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$DB_PASSWORD';
CREATE USER '$DB_USER'@'localhost' IDENTIFIED WITH mysql_native_password BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON *.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
EOF
# Run mysql_secure_installation
sudo mysql_secure_installation
sudo service mysql restart
问题:
现在,一切完成之后,我尝试像这样登录 mysql:
mysql -u user-p
我进入的地方确切地我被提示输入相同的用户名和密码
我收到以下错误:
ERROR 1045 (28000): Access denied for user 'Faber'@'localhost' (using password: YES)
现在,如果我执行此命令,其中用户和密码与我之前输入的完全相同
sudo mysql
ALTER USER 'DBuser'@'localhost' IDENTIFIED BY '161fd43c260030@&DB';
FLUSH PRIVILEGES;
我可以正确登录mysql,为什么我不能通过 bash 脚本正确设置密码,因为我使用 bash 脚本自动执行任务,所以我希望避免执行 ALTER 命令......
答案1
$DB_PASSWORD
似乎没有在您的脚本的任何地方设置,因此请确保像这样设置它:
while true; do
read -rsp "Enter the database password: " DB_PASSWORD1
echo
read -rsp "Re-enter the database password: " DB_PASSWORD2
echo
if [ "$DB_PASSWORD1" = "$DB_PASSWORD2" ]; then
DB_PASSWORD="$DB_PASSWORD1"
break
else
echo "Passwords did not match. Please try again."
fi
done
注意:全大写的变量名可能会覆盖 shell 内置变量,因此不要使用它们。