expect脚本在自动化部署中的具体应用案例

#expect脚本在自动化部署中的具体应用
expect脚本是一个非常好的交互式应用脚本,在自动化部署中,可以使用这个脚本来实现全自动的自动化部署。下面是一些具体的应用案例。

场景一:自动安装mysql

可以使用expect脚本来实现mysql自动安装,提取初始化密码,并使用初始化密码登录系统,然后修改密码,再执行数据库初始化操作。

send "unzip mysql.zip\n"
expect "# "
send "rpm -ivh libaio-0.3.109-13.el7.x86_64.rpm\n"
sleep 10
expect "]# "
send "rpm -ivh numactl-2.0.7-8.el6.x86_64.rpm\n"
sleep 10
expect "]# "
send "tar -zxvf  mysql-5.7.42-linux-glibc2.12-x86_64.tar.gz -C /usr/local\n"
sleep 60
expect "]# "
send "mv /usr/local/mysql-5.7.42-linux-glibc2.12-x86_64 /usr/local/mysql\n"
sleep 3
expect "# "
send "groupadd mysql\n"
expect "# "
send "useradd -g mysql -s /bin/false mysql\n"
expect "# "
send "mkdir -p /data/mysql\n"
expect "# "
send "chown -fR mysql:mysql /data/mysql\n"
expect "# "
send "cd /usr/local/mysql/bin/\n"
expect "# "
send "./mysqld --defaults-file=/etc/my.cnf --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/data/mysql\n"
expect "# "
send "ln -s /usr/local/mysql/bin/mysql /usr/sbin/mysql\n"
expect "# "
send "/bin/cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysql\n"
expect "# "
send "chmod +x /etc/init.d/mysql\n"
expect "# "
send "cd /etc/rc.d/init.d\n"
expect "# "
send "chkconfig --add mysql\n"
expect "# "
send "chkconfig mysql on\n"
expect "# "
send "/etc/init.d/mysql start\n"
expect "# "
send "cd /data/mysql\n"
expect "# "
send "cat error.log | grep password| awk \"{ print \\\$NF}\"\n"
expect {
    -re {password is generated for root@localhost: (.+)} {
        set myPassword \$expect_out(1,string)
    }
    timeout {
        puts "未找到匹配的密码字符串"
    }
}
expect "# "
puts "MySQL初始密码为:\$myPassword"
send "mysql -uroot -p\n"
expect "password: "
send "\$myPassword\n"
expect "mysql> "
send "set password =password('wahaha@m#T98kjhss');\n"
expect "mysql> "
send "grant all privileges on *.* to 'root'@'%' identified by 'wahaha@m#T98kjhss';\n"
expect "mysql> "
send "flush privileges;\n"
expect "mysql> "
send "create database wahaha;\n"
expect "mysql> "
send "use wahaha;\n"
expect "mysql> "
send "set names utf8;\n"
expect "mysql> "
send "source /opt/mysql/wahaha_mysql.sql;\n"
expect "mysql> "
send "exit\n"
expect "# "

场景2 安装JDK

解压安装JDK,并将JAVA_HOME相关变量写入/etc/profile中。

send "cd /usr/java; tar -zxvf jdk1.8.0_191.tar.gz\n"
expect "# "
send "echo 'JAVA_HOME=\/usr\/java\/jdk1.8.0_191' >> /etc/profile\n"
expect "# "
send "echo 'JRE_HOME=\\\${JAVA_HOME}\/jre' >> /etc/profile\n"
expect "# "
send "echo 'CLASSPATH=.:\\\${JAVA_HOME}\/lib:\\\${JRE_HOME}\/lib' >> /etc/profile\n"
expect "# "
send "echo 'PATH=\\\${JAVA_HOME}\/bin:\\\$PATH' >> /etc/profile\n"
expect "# "
send "echo 'export JAVA_HOME JRE_HOME CLASSPATH PATH' >> /etc/profile\n"
expect "# "
send "source /etc/profile\n"
expect "# "
send "java -version\n"
expect "# "

结论

使用同样的方法,我们可以实现任意安装过程,包括tomcat、redis,kafaka, 甚至Kubernetes。通过expect脚本,一切命令化,皆可自动化。expect与jenkins结合,我们可以实现绝大部分系统的自动化安装部署,这将给系统运维带来极大的便利。

你可能感兴趣的:(自动化,expect,运维)