在 Ubuntu 16.04 LTS 上非交互式(静默)安装 MySQL 5.7

Mic*_*sen 5 mysql unattended ubuntu-16.04

MySQL 5.7(实际上是 5.6+)改变了mysql_secure_installation工作方式。这使得很难为 Ubuntu 16.04 LTS 找到一个有效的、静默的、脚本化的安装。您将如何以脚本化的非交互式方式安全地安装 MySQL?

Mic*_*sen 8

下面的完整脚本可以放入我们称为“install.sh”的文件中,并通过执行以下操作来执行:

touch install.sh      # Create empty file
chmod 700 install.sh  # Make executable
nano install.sh       # Copy contents into script here
./install.sh          # Run it
Run Code Online (Sandbox Code Playgroud)

关于下面的脚本:

  1. 请记住通过将第 4 行的问号替换为您的密码来设置 MYSQL_ROOT_PASSWORD
  2. 如果以 root 身份运行,请删除 sudo。
  3. 该脚本安装Expect。如果您取消注释第 50 行,它还可以在完成后清除(卸载)Expect。

脚本内容:

#!/bin/bash
export DEBIAN_FRONTEND=noninteractive

MYSQL_ROOT_PASSWORD='?' # SET THIS! Avoid quotes/apostrophes in the password, but do use lowercase + uppercase + numbers + special chars

# Install MySQL
# Suggestion from @dcarrith (http://serverfault.com/a/830352/344471):
echo debconf mysql-server/root_password password $MYSQL_ROOT_PASSWORD | sudo debconf-set-selections
echo debconf mysql-server/root_password_again password $MYSQL_ROOT_PASSWORD | sudo debconf-set-selections
#sudo debconf-set-selections <<< "mysql-server-5.7 mysql-server/root_password password $MYSQL_ROOT_PASSWORD"
#sudo debconf-set-selections <<< "mysql-server-5.7 mysql-server/root_password_again password $MYSQL_ROOT_PASSWORD"
sudo apt-get -qq install mysql-server > /dev/null # Install MySQL quietly

# Install Expect
sudo apt-get -qq install expect > /dev/null

# Build Expect script
tee ~/secure_our_mysql.sh > /dev/null << EOF
spawn $(which mysql_secure_installation)

expect "Enter password for user root:"
send "$MYSQL_ROOT_PASSWORD\r"

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

expect "Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:"
send "2\r"

expect "Change the password for root ? ((Press y|Y for Yes, any other key for No) :"
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"

EOF

# Run Expect script.
# This runs the "mysql_secure_installation" script which removes insecure defaults.
sudo expect ~/secure_our_mysql.sh

# Cleanup
rm -v ~/secure_our_mysql.sh # Remove the generated Expect script
#sudo apt-get -qq purge expect > /dev/null # Uninstall Expect, commented out in case you need Expect

echo "MySQL setup completed. Insecure defaults are gone. Please remove this script manually when you are done with it (or at least remove the MySQL root password that you put inside it."
Run Code Online (Sandbox Code Playgroud)