Mysql

如何使用 bash 將輸入從一個腳本傳遞到另一個腳本

  • January 11, 2019

我正在編寫一個腳本,我想在其中啟動 mysql_secure_installation腳本並在每個提示處提供適當的答案。我嘗試使用這樣的迴聲:

echo -e "\n\n$db_pass\n$db_pass\n\n\n\n\n" | /usr/bin/mysql_secure_installation

它不完全工作。它似乎正確回答了最後 5 個問題,但沒有正確回答前 3 個問題(這是在一個CentOS 6.5盒子上)。這是輸出:

In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

stty: standard input: Invalid argument
Enter current password for root (enter for none):
stty: standard input: Invalid argument
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n]  ... skipping.

當被要求輸入 root 密碼時,它應該送出一個返回。然後,當被要求設置 root 密碼時,它應該送出另一個返回。但是,正如您從沒有發生的輸出中看到的那樣。

我需要做什麼才能使其按預期工作?

MySQL 開發站點上的這個錯誤報告解決了mysql_secure_installation需要互動式使用者會話的問題。

那裡有一些很好的討論,其中有一些技巧和範例可以expect用作解決方法。似乎解決您希望以非互動方式執行腳本的最佳建議(即:沒有直接的使用者互動)是 Daniël van Eeden 的回答,它提供了以下expect腳本:

#!/usr/bin/expect --
spawn /usr/local/mysql/bin/mysql_secure_installation

expect "Enter current password for root (enter for none):"
send "\r"

expect "Set root password?"
send "y\r"

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

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

expect "Remove anonymous users?"
send "y\r"

expect "Disallow root login remotely?"
send "y\r"

expect "Remove test database and access to it?"
send "y\r"

expect "Reload privilege tables now?"
send "y\r"

puts "Ended expect script."

此外,似乎在 MySQL 5.6.8 中解決了基本 MySQL 安裝存在非安全內容的總體問題,但僅適用於通過 RPM 進行的新安裝或使用以下--random-password選項進行的原始碼安裝:

新的 RPM 安裝操作(不是升級) 使用 –random-passwords 選項呼叫**mysql_install_db 。**因此,從此版本開始安裝的 RPM 將保護其 root 帳戶,並且沒有匿名使用者帳戶。(使用 RPM for Unbreakable Linux Network 的安裝操作不受影響,因為它們不使用 mysql_install_db。)

對於使用二進制 .tar.gz 分發或原始碼分發的安裝操作,您可以使用 –random-passwords 選項手動呼叫mysql_install_db以使您的 MySQL 安裝更安全。建議這樣做,特別是對於具有敏感數據的站點。

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