expect知识梳理

1 expect

  expect软件用于实现非交互式操作,实际应用中常用于批量部署,可以帮助运维人员管理成千上万台服务器.

  expect实现非交互式操作主要是在程序发出交互式询问时,按条件传递程序所需的字符串,如询问yes/no时自动传递yes或no,或询问密码时传递已定义好的密码,这样实现了非交互操作.

1.1 expect安装

  推荐使用yum安装,方便快捷,自动解决依赖问题;如果手动编译,需同时安装expect和tcl软件.

  安装省略,直接yum安装expect即可.

1.2 expect脚本中经常使用的命令及说明

命令 说明
set timeout NUM 设置超时时间,NUM是数字,单位是秒.
expect 进入expect环境下
spawn

expect软件中的监控程序,监控后面程序/命令发出的交互式询问,

spawn是expect环境下的内部命令.

send 发送已定义的字符串或数字密码给程序,完成交互式操作
"string "

表示发送string字符串后执行回车操作,程序之间的交互一般使用

" "

"string "

使用"string "表示发送指定的字符串后,并输出内容到终端,

方便用户查看结果.

exp_continue

若问题不存在则继续下一步,回答下面的问题.

注意此项不能加在expect发送自动应答中的最后一项,否则报错.

expect eof

当发送自动应答完毕后,退出expect环境

interact

当发送自动应答完毕后,停留在程序交互界面

set NAME [lindex $argv 0]

定义expect环境下的变量,类似shell中传参$1,$2,...

0代表发送自动应答传递的第一个参数,

1.3 expect结合shell脚本实现主机批量互信 

  ssh-copy-id非交互式传递公钥到其他主机,实现互信:

[root@test ~]# ssh-keygen	#<==回车创建rsa
[root@test ~]# mkdir /server/scripts -p
[root@test ~]# cd /server/scripts/
[root@test scripts]# cat auto_ssh-copy-id.exp   #<==expect脚本需以.exp后缀结尾并添加x权限执行
#!/usr/bin/expect

set timeout 10
set host [lindex $argv 0]
set passwd [lindex $argv 1]
spawn ssh-copy-id $host
    expect {
        "(yes/no)?"
        {
            send "yes
"
            expect "*assword:" { send "$passwd
"}
        }
        "*assword:"
        {
            send "$passwd
"
        }
    }
expect eof
######用法: ./auto_ssh-copy-id.exp user@host password
[root@test scripts]# chmod +x auto_ssh-copy-id.exp
[root@test scripts]# ./auto_ssh-copy-id.exp root@10.0.0.11 123456
[root@test scripts]# ssh root@10.0.0.11
Last login: Mon Nov 25 20:55:46 2019 from 10.0.0.253

  expect结合shell脚本实现批量互信:

[root@test scripts]# pwd
/server/scripts
[root@test scripts]# vi autossh.sh
[root@test scripts]# cat autossh.sh 
#!/bin/sh

passwd=123456
user_host=`awk '{print $3}' ~/.ssh/id_rsa.pub`
 
for i in $@  
do
        /server/scripts/auto_ssh-copy-id.exp $i $passwd >&/dev/null
        ssh $i "grep "$user_host" ~/.ssh/authorized_keys" >&/dev/null
        if [ $? -eq 0 ];then
                echo "$i is successful"
        else
                echo "$i is failed"
        fi
done
[root@test scripts]# chmod +x ./autossh.sh
[root@test scripts]# ls
auto_ssh-copy-id.exp  autossh.sh
######用法: /server/scripts/autossh.sh user@host
[root@test scripts]# ./autossh.sh root@10.0.0.70
root@10.0.0.70 is successful
[root@test scripts]# ssh root@10.0.0.70
Last login: Mon Nov 25 21:07:32 2019 from 10.0.0.11

  

  

原文地址:https://www.cnblogs.com/blog-tim/p/11934220.html