最新要闻

广告

手机

美联储会议痛击黄金多头 黄金TD开启窄幅下行

美联储会议痛击黄金多头 黄金TD开启窄幅下行

致敬高温下的“劳动剪影”

致敬高温下的“劳动剪影”

家电

Linux之expect

来源:博客园


【资料图】

目录
  • Expect
[root@localhost ~]#cat < hello> hi> halo> EOFhellohihalo

Expect

  • 建立在tcl上的一个工具
  • 用于自动化控制和测试
  • 解决shell脚本中交互相关问题

/usr/bin/expect

[root@localhost ~]#rpm -q expectexpect-5.45-14.el7_1.x86_64[root@localhost ~]#which expect/usr/bin/expect[root@localhost ~]#vim test[root@localhost ~]#cat test#!/usr/bin/expectspawn ssh 192.168.174.102expect {   "yes/no"   {send "yes\r"; exp_continue}   "password" {send "123123\r" }}#expect eof  #交互结束会回到原先的用户interact  #交互结束保留在目标用户[root@localhost ~]#chmod +x test[root@localhost ~]#./testspawn ssh 192.168.174.102The authenticity of host "192.168.174.102 (192.168.174.102)" can"t be established.ECDSA key fingerprint is SHA256:8rTcpr5+eXm4qipF2jv/MRbC424mx9Fu/KjVOEIrgVk.ECDSA key fingerprint is MD5:e2:1d:87:30:df:a2:ca:b0:71:12:42:b3:40:03:77:8f.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added "192.168.174.102" (ECDSA) to the list of known hosts.root@192.168.174.102"s password: Last login: Tue Aug 15 18:58:10 2023 from 192.168.174.1
[root@localhost ~]#cat test#!/usr/bin/expectset hostname [ lindex $argv 0 ]spawn ssh $hostnameexpect {   "yes/no"   {send "yes\r"; exp_continue}   "password" {send "123123\r" }}expect eof#interact[root@localhost ~]#./test 192.168.174.102spawn ssh 192.168.174.102root@192.168.174.102"s password: Last login: Thu Aug 17 09:41:47 2023 from 192.168.174.100[root@localhost ~]#[root@localhost ~]#
  • 定义:是建立在tcl(tool command language)语言基础上的一个工具,常被用于进行自动化控制和测试,解决shell脚本中交互的相关问题

  • Expect概述(与ssh相互配合使用)

    • 建立在tcl之上的工具
    • 用于进行自动化控制和测试
    • 解决shell脚本中交互相关的问题
  • 基本命令

    • 判断上次输出结果中是否包含指定的字符串,如果有则立即返回,否则就等待超时时间后返回
    • 只能捕捉由spawn启动的进程的输出
    • 用于接收命令执行后的输出,然后和期望的字符串匹配
  • send

    • 向进程发送字符串,用于模拟用户的输入
    • 该命令不能自动回车换行,一般要加\r(回车)
  • set

    • 设置超时时间,过期则继续执行后续指令
    • 单位是秒
    • timeout -1表示永不超时
    • 默认情况下,timeout是10秒
  • exp_continue

    • 允许expect继续向下执行指令
  • send_user

    • 回显命令,相当于echo

基本命令:

#脚本解释器#!/usr/bin/expect(不用.sh结尾)#spawn 后面通常跟一个Linux执行命令,表示开启一个会话、进程,并跟踪后续交互信息例:spawn ssh 192.168.8.8#expect判断上次输出结果中是否包含指定的字符串,如果有则立即返回,否则就等待超时时间后返回;只能捕捉有swpan启动的进程输出用于接受命令执行后的输出,然后和期望的字符串匹配#send向进程发送字符串,用于模拟用户的输入:该命令不能自动回车换行,一般要加 \r (回车) 或者\n ```bash#!/usr/bin/expect#设置超时时间set timeout 5#参数传入set hostname  [lindex $argv 0]  #hostname=$1set password  [lindex $argv 1] #password=$2
[root@localhost ~]#rpm -q expect   #先查看是否安装expect,没有安装需要先安装(yum install expect -y)expect-5.45-14.el7_1.x86_64[root@localhost ~]#rpm -q tcltcl-8.5.13-8.el7.x86_64[root@localhost ~]#vim test#!/usr/bin/expectspawn ssh 192.168.8.106    #启动命令expect {       #捕捉spawn启动的进程的输出    "yes/no" { send "yes\r"; exp_continue }  #捕捉yes或no,exp continue代表继续捕捉    "password" { send "123123\r" }    #继续捕捉}#expect eof    #代表结束,结束返回之前终端interact       #代表结束,留在远程终端[root@localhost ~]#chmod +x test

关键词: