#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結合,我們可以實現絕大部分系統的自動化安裝部署,這將給系統運維帶來極大的便利。