hgzero

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: https://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 其他更详细内容

 

 

相关文章: