采用脚本自动填写具有交互式命令的方法

  采用脚本自动填写具有交互式命令的方法

  在我们安装完数据库mariadb之后,启动数据库,然后需要手动执行mysql_secure_installation进行安全设置,比如设置数据库的密码等等,设置完成之后我们才可以使用数据库。然而在我们采用脚本执行数据安装过程中,如何在数据库安全设置的命令执行后,自动输入我们要设置的数据库密码。这里可以提供一个可以对交互式命令自动填写的方法,那就是expect。

1、安装mariadb

  yum install mariadb mariadb-server python2-PyMySQL -y

2、数据库配置

  按如下方法配置数据的配置文件:

  vim /etc/my.cnf.d/openstack.cnf

[mysqld]
bind-address = $CONTROLLER_IP
default-storage-engine = innodb
innodb_file_per_table = on
max_connections = 4096
collation-server = utf8_general_ci
character-set-server = utf8

  启动数据库服务

  systemctl restart mariadb.service

  systemctl status mariadb.service

3、利用脚本执行数据库安全设置

  首先安装expect软件:yum install expect -y

  编写执行脚本,如/root/install/mysqlinstall.sh,脚本内容如下:

#!/usr/bin/expect
spawn 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 "root\r"
expect "Re-enter new password: "
send "root\r"
expect "Remove anonymous users?"
send "Y\r"
expect "Disallow root login remotely?"
send "n\r"
expect "Remove test database and access to it?"
send "Y\r"
expect "Reload privilege tables now?"
send "Y\r"
interact

  备注:

  Spawn后边填写我们需要执行的命令

  expect "xxx "其中xxx表示提示我们输入字符的关键字

  \r表示不输入任何内容直接回车

  Y\r表示输入Y然后回车

  root\r表示输入root然后回车,这里我设置密码为root

  注意:执行脚本不能用bash执行,用./root/install/mysqlinstall.sh执行脚本

 

posted @ 2019-03-15 20:32  陈LI  阅读(1638)  评论(0编辑  收藏  举报