expect的使用

1. expect概述

1.1 expect的功能

腳本執行時,有時會需要人工進行交互輸入,這時可以通過expect工具來實現自動交互。

expect是一種shell解釋器,但是expect可以在命令交互時捕捉指定的內容,然後再輸出指定的內容。

1.2 安裝expect

yum install -y expect 

1.3 一些基本的expect關鍵字

# 設置expect捕捉的超時時間,單位為秒
set timeout 10

# 使用expect,一般與重定向結合使用,以達到在bash解釋器下也能執行捕捉
/usr/bin/expect

# 啟動新進程,用於執行shell命令
spawn

# 與spawn結合使用,使用exp_continue進行多次捕捉
expect {「等待捕捉的內容」 {send "需要輸入的內容"}}

# 發送輸入的內容
send

# 繼續捕捉,不斷開會話
exp_continue

# 允許用戶交互,即此命令之後,交互將不會由expect進行,而是交回給用戶
interact

2. expect使用示例

2.1 mysql初始化

#!/bin/bash
# Description: Initialize MySQL Server
# Root password
user='root'
password='woshiniba'

set timeout 10

function initMysql() {
    /usr/bin/expect << EOF                              # 表示以下內容將傳遞給 /usr/bin/expect 程式來執行
    spawn /usr/bin/mysql_secure_installation            # 表示用spawn來執行這個命令,spawn只能在expect環境中才能執行
    expect {
        "Enter current password for root (enter for none):" {send "\r";exp_continue} # 這裡\r表示回車,也可以使用\n
        "Set root password?" {send "Y\r";exp_continue}  # exp_continue表示還要繼續保持捕捉動作(會話)
        "New password" {send "$password\r";exp_continue}
        "Re-enter new password" {send "$password\r";exp_continue}       
        "Remove anonymous users?" {send "Y\r";exp_continue}
        "Disallow root login remotely?" {send "n\r";exp_continue}
        "Remove test database and access to it?" {send "Y\r";exp_continue}
        "Reload privilege tables now?" {send "Y\r";exp_continue}
        }
    expect eof  # 表示結束expect
EOF
}

initMysql

2.2 批量做免密登錄

#!/bin/bash
# Description: Ansible SSH password free login configuration
# Author: Praywu
# Blog: //cnblogs.com/hgzero

server=('172.18.0.150' '172.18.0.202')
passwd='woshiniba'
key='/root/.ssh/id_rsa'

function genKey(){
    [ -e "$key" ] || ssh-keygen -t rsa -P "" -f $key 
}

function connServer(){
    /usr/bin/expect << EOF
    spawn /usr/bin/ssh-copy-id -i ${key}.pub root@$1
    expect {
        "want to continue connecting (yes/no)?" {send "yes\r";exp_continue}
        "s password" {send "${passwd}\r";exp_continue}
    }
EOF
}

function exec(){    
    genKey && echo -e "\033[32m[INFO]\033[0m Generate key OK!" || echo -e "\033[31m[ERROR]\033[0m Generate key Failed!" 
    set timeout 15
    for i in $(seq 0 $((${#server[*]}-1)));do
        connServer "${server[$i]}" &> /dev/null
        [[ $? -eq 0 ]] && echo -e "\033[32m[INFO]\033[0m Get ${server[$i]} Success!" || echo -e "\033[32m[INFO]\033[0m Get ${server[$i]} Failed!"
    done
}

function clear(){
    for i in $(seq 0 $((${#server[*]}-1)));do
        sed -i "/${server[$i]}/d" /root/.ssh/known_hosts
    done
}

function help(){
    echo "Usage: $0 [ exec | clear ]"
    echo -e "Ansible SSH password free login configuration \n"
}

function main(){
    case $1 in 
        exec)
            exec;;
        clear)
            clear;;
        *)
            help;;    
    esac
}

main $1

2.3 其他更詳細內容