expect

expect功能

linux下运行命令、脚本或程序时,经常需要从终端输入某些命令继续运行的指令,这些输入都需要人为的手工干预
expect可以根据程序的提示,模拟标准输入提供给程序,从而实现自动化交互执行。一般位于 /usr/bin/ecpect 
expect脚本必须以interact或expect eof结束 interact 表示执行完成后保持交互状态,把控制权交给控制台,此时可以进行手工操作 expect eof与spawn对应,表示捕获终端输出信息终止 在shell脚本中嵌入expect脚本,必须以 expect <<EOF 开头,以 EOF 结尾,结尾的 EOF 必须单独成行且前面不能有任何字符

expect 的四个命令:

       send : 用于向进程发送字符串

       expect : 从进程接收字符串

       spawn : 启动一个新的进程

       interact : 退出自动化,进入人工交互

ssh登录脚本示例:

#!/usr/bin/expect

# 设置超时时间,单位为秒,默认情况下是10秒;-1不会超时
set timeout 30

# 设置主机IP、用户名及密码
set host "101.200.241.109"
set username "root"
set password "123456"

# spawn是进入expect环境后才可以执行的expect内部命令,直接在shell下执行是找不到spawn命令的;它主要的功能是给ssh运行进程加个壳,用来传递交互指令
spawn ssh $username@$host

# expect也是expect的一个内部命令,这个命令的意思是判断上次输出结果里是否包含“password”的字符串,如果有则立即返回;否则就等待一段时间后返回,这里等待时长就是前面设置的30秒
expect "*password*" {send "$password
"}

# 执行完成后保持交互状态,把控制权交给控制台,进行人工交互;如果没有这一句登录完成后会退出,而不是留在远程终端上
interact

ssh批量登录主机并执行命令:

#!/bin/bash

# To read the file, the last line must be blank
# The format of the file content is: host usename password, separated by spaces
# for example:
#   10.246.3.87 root root
#   10.246.3.88 root root

file=$1

if [ x"${file}" == x"" ];then
    echo "usage: ./ansible.sh <hosts_file>"
    exit 0
fi

# Repeat to read line
while read line
do
    if [ x"${line}" != x"" ];then
        host=$(echo ${line} | awk '{print $1}')
        username=$(echo ${line} | awk '{print $2}')
        password=$(echo ${line} | awk '{print $3}')

        echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>> start to login ${host}"

        /usr/bin/expect <<EOF
        set timeout 3
        spawn ssh ${username}@${host}
        expect {
            "*(yes/no)*" { send "yes "; exp_continue }
            "*password*" { send "${password} " }
        }

        expect "*#" { send "cd /home/ " }
        expect "*#" { send "touch tongyishu.log " }
        expect "*#" { send "exit " }

        expect eof
EOF
    fi
done < ${file}

ecpect安装:

A. Tcl 安装

下载地址: http://www.tcl.tk/software/tcltk/downloadnow84.tml

1.下载源码包

wget http://nchc.dl.sourceforge.net/sourceforge/tcl/tcl8.4.11-src.tar.gz

2.解压缩源码包

tar xfvz tcl8.4.11-src.tar.gz

3.安装配置

cd tcl8.4.11/unix

./configure --prefix=/usr/tcl --enable-shared

make & make install

 

B. expect 安装 (需Tcl的库)

1.下载源码包

wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz/download

2.解压缩源码包

tar xzvf expect5.45.tar.gz

3.安装配置

cd expect5.45

./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.4.11/generic ##注意路径中要用到tcl中的 库

make & make install

原文地址:https://www.cnblogs.com/tongyishu/p/11775765.html