Mysql

在 Ubuntu 16.04 LTS 上非互動式(靜默)安裝 MySQL 5.7

  • July 4, 2019

MySQL 5.7(實際上是 5.6+)改變了mysql_secure_installation工作方式。這使得很難找到適用於 Ubuntu 16.04 LTS 的工作、靜默、腳本安裝。您將如何以腳本化的非互動方式安全地安裝 MySQL?

下面的完整腳本可以放入我們將稱為“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

關於下面的腳本:

  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."

引用自:https://serverfault.com/questions/783527