自动化需要用户交互的流程的最佳策略

时间:2016-01-29 14:03:24

标签: linux bash shell docker

我在Dockerfile中工作,但有一个" secure" MariaDB服务器脚本我需要运行哪个是交互式的,我不知道如何处理这个。

基本上,这是我在测试环境中遵循脚本的流程,并且我想在Dockerfile中实现相同的目标,而不需要用户交互,只需回答如下所示:

# /usr/bin/mysql_secure_installation

Enter current password for root (enter for none): [ENTER] // because there is no password
OK, successfully used password, moving on...

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

Remove anonymous users? [Y/n] Y
 ... Success!

Disallow root login remotely? [Y/n] n
 ... skipping.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!

Cleaning up...

所以我需要编写一个bash脚本或其他可以自动处理这个但又不知道的东西,你会怎么处理这个?

2 个答案:

答案 0 :(得分:3)

我认为您可以尝试两种不同的方法:

  1. 最终使用expect脚本"评估"来自bash。手册页here
  2. 或者:

    1. 使用" here document"来自bash脚本的语法(不期望)
    2. **编辑 - 选项2 **

      的示例
      #!/bin/bash
      ...
      /usr/bin/mysql_secure_installation <<EOF
      
      n
      Y
      n
      Y
      Y
      EOF
      ...
      

      基本上你将所有答案传递给mysql_secure_installation的标准输入。

      使用expect只是有点复杂。您可以从here

      开始

答案 1 :(得分:1)

另一个选择,mysql_secure_installation是一个简单的bash脚本,它执行几个mysql命令,只需使用sql命令。

DELETE FROM mysql.user WHERE User='';
DROP DATABASE test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;

将此命令保存在文件中并将其传递给mysql

mysql < my_file.sql