Mysql
通過expect實現mysql自動化
我需要自動化
mysql_secure_installation
流程,我已經編寫了這個腳本,但它失敗得很慘,我不想為數據庫設置任何密碼#!/usr/bin/expect set timeout 10 spawn mysql_secure_installation expect "Enter current password for root (enter for none):" send -- "\r" expect "Set root password? [Y/n]" send "n\r" expect "Remove anonymous users? [Y/n]" send "Y\r" expect "Disallow root login remotely? [Y/n]" send "n\r" expect "Remove test database and access to it? [Y/n]" send "Y\r" expect "Reload privilege tables now? [Y/n]" send "Y\r" interact
錯誤:
[root@localhost ansible]# ./mysql.sh spawn mysql_secure_installation NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY! In order to log into MariaDB to secure it, we'll need the current password for the root user. If you've just installed MariaDB, and you haven't set the root password yet, the password will be blank, so you should just press enter here. Enter current password for root (enter for none): invalid command name "Y/n" while executing "Y/n" invoked from within "expect "Set root password? [Y/n]"" (file "./mysql.sh" line 8)
[
在 TCL 中是特殊的,並且是"..."
插值的,所以"blah [foo]"
導致 TCL 嘗試呼叫
foo
過程(proc
或其他語言可能稱為 asub
或function
)。一個人可以反擊[
expect "blah \[foo]"
或者改為引用
{}
禁用插值expect {blah [foo]}
這些是明智的選擇。不要使用超過這一點的任何程式碼!
愚蠢的程序部
我們還可以創建一個
proc
導致呼叫Y/n
返回的[Y/n]
;$ expect expect1.1> proc Y/n {} { return "\[Y/n]" } expect1.2> puts "abort [Y/n]" abort [Y/n] expect1.3>
這允許
[Y/n]
在插值字元串內操作。更麻煩的是 viaunknown(n)
,因為這允許我們proc
為大多數隨機[...]
字元串創建一個插值在任何地方…當然,除非proc
給定的過程名稱已經存在;就像我之前說的,這是一個壞主意,不應該使用。expect1.1> proc unknown args { return "\[$args]" } expect1.2> puts "abort [Y/n]" abort [Y/n] expect1.3> puts "already exists [puts -nonewline puts\ ]" puts already exists expect1.4>