Linux 实用小脚本系列(2)----mysql安全初始化脚本的免交互执行--mysql_secure_installation

    Linux 实用小脚本系列(2)----mysql安全初始化脚本的免交互执行--     mysql_secure_installation

            通常mysql安装完毕后,都会带有一个增强mysql安全的脚本,并且初始化密码也可以通过该脚本快速实现,但如果是采用自己编写脚本安装mysql(不管是二进制还是编译还是yum安装的方式),安装完毕后,都需要手动执行该脚本--mysql_secure_installation,这未免不太仁杏化了,这样的问题怎么解决呢? expect脚本可以帮助你实现免交互执行该脚本,十分的仁杏化,快速。

         现在就假设安装完毕了mysql。现在开始编写expect脚本快速的执行安全脚本。

yum install -y expect  #安装的是expect脚本解释器

vim mysql_secure.sh  内容如下:(需要什么密码自行在  set passwd 这一行后写入)

#!/usr/bin/expect
set passwd 要设定的密码
spawn  mysql_secure_installation
expect {
             "Enter current password" { send "\r"; exp_continue }
             "Y/n" { send "Y\r"; exp_continue }
             "New password" { send "$passwd\r"; exp_continue }
             "Re-enter new password" { send "$passwd\r"; exp_continue }
             "Remove anonymous users" { send "Y\r"; exp_continue }
             "Disallow root login remotely" { send "Y\r"; exp_continue }
             "Remove test database and access to it" { send "Y\r"; exp_continue }
             "Reload privilege tables now" { send "Y

 执行脚本:expect 脚本名称,或者 ./脚本名称。多说一句,通常shell脚本 执行的一种方式为  bash 脚本名称,现在需要将bash 换成expect ,即可。./脚本名称的方式 同shell脚本,需要给予执行权限,chmod +x 脚本名称。

上面的这个脚本,密码是写死在脚本内的,如果想更灵活,比如通过参数,从而提升安全,可以以带参数方式执行该脚本,仅仅需要一点小小的改动。

#!/usr/bin/expect
set passwd [lindex $argv 0]
spawn  mysql_secure_installation
expect {
             "Enter current password" { send "\r"; exp_continue }
             "Y/n" { send "Y\r"; exp_continue }
             "New password" { send "$passwd\r"; exp_continue }
             "Re-enter new password" { send "$passwd\r"; exp_continue }
             "Remove anonymous users" { send "Y\r"; exp_continue }
             "Disallow root login remotely" { send "Y\r"; exp_continue }
             "Remove test database and access to it" { send "Y\r"; exp_continue }
             "Reload privilege tables now" { send "Y\r" }
}

执行该脚本时带一个参数即可,该参数即为密码。

例如,expect 脚本名称 参数1, 那么,参数1的值就是密码,可通过登录mysql验证哦。

猜你喜欢

转载自blog.csdn.net/alwaysbefine/article/details/108679423
今日推荐