如何在Ubuntu上编写安装MySQL服务器的脚本?

Sudo apt-get install mysql将安装,但它也会要求在控制台中输入密码。

我如何以非交互的方式做到这一点?也就是说,写一个脚本,可以提供密码吗?

#!/bin/bash
sudo apt-get install mysql  # To install MySQL server

# How to write script for assigning password to MySQL root user
# End

这应该能奏效

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

当然,它会给您留下一个空白的根密码——所以您会想要运行类似于

mysqladmin -u root password mysecretpasswordgoeshere

之后,为帐户添加密码。


sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

对于特定的版本,比如mysql-server-5.6,你需要像这样指定版本:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

对于mysql-community-server,键略有不同:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

将your_password替换为所需的根密码。(似乎your_password也可以留空作为空白根密码。)

如果你的shell不支持here-strings (zsh, ksh93和bash支持),使用:

echo ... | sudo debconf-set-selections 

另一种可行的方法:

echo "mysql-server-5.5 mysql-server/root_password password root" | debconf-set-selections
echo "mysql-server-5.5 mysql-server/root_password_again password root" | debconf-set-selections
apt-get -y install mysql-server-5.5

注意,这只是将密码设置为“root”。我不能让它使用简单的引号设置一个空白密码”,但这个解决方案对我来说已经足够了。

基于这里的一个解决方案。


Use:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"