我需要自动化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)
答案1
[
TCL 比较特殊,并且"..."
是插值,所以
"blah [foo]"
导致 TCL 尝试调用该foo
过程(proc
,或其他语言可能称为sub
或 的内容function
)。人们可以反击[
expect "blah \[foo]"
或者用引号来{}
禁用插值
expect {blah [foo]}
这些都是明智的选择。请勿使用超过此点的任何代码!
愚蠢的程序部
我们还可以创建一个导致调用 return 的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]
在插值字符串内进行操作。甚至可能会遇到更多麻烦,因为这允许我们为大多数插入到任何地方的随机字符串unknown(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>