重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

Expect自动化交互应用实例解析

expect是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。

成都创新互联技术团队10年来致力于为客户提供成都做网站、网站建设、外贸营销网站建设成都品牌网站建设成都营销网站建设、搜索引擎SEO优化等服务。经过多年发展,公司拥有经验丰富的技术团队,先后服务、推广了上千网站,包括各类中小企业、企事单位、高校等机构单位。

expect自动交互流程:

spawn启动指定进程---expect获取指定关键字---send向指定程序发送指定字符---执行完成退出

简单实例1:

vim test.exp        ##exp是expect脚本的扩展名

#!/usr/bin/expect        ##使用expect解析程序

spawn ssh root@192.168.1.5  free   ##用spawn执行ssh命令 登录后执行free命令

expect “*password”   ##匹配获取的字符串

send “123456\n”        ##匹配后发送密码给系统,\n是换行

expect  eof   ##处理结束expect

实例2:

#!/usr/bin/expect

spawn  ssh root@192.168.1.5 free

expect {

    "yes/no"    {exp_send "yes\r";exp_continue}

     "*password"    {exp_send "123456\r"}

}

expect eof

实例3:

#!/usr/bin/expect

spawn test.sh

expect {

    "username"  {exp_send "test\r";exp_continue}

    "*password" {exp_send "123456\r";exp_continue}

     "*mail*"   {exp_send "lidao@163.com\r"}

}

expect eof

expect 常用 命令总结

spawn    交互程序开始   后面跟命令或者指定程序

expect    获取匹配信息  匹配成功则执行expect后面的程序动作

send       exp_send   用于发送指定的字符串信息

exp_continue        在expect中多次匹配就需要用到

send_user        用来打印输出 相当于shell中的echo

exit            退出expect脚本

eof              expect执行结束 退出

set                定义变量

puts               输出变量

set timeout    设置超时时间

实例4:

#!/usr/bin/expect

if {$argc !=2 } {

    puts "expect $argv0 ip command"

    exit

}

set ip [lindex $argv 0]

set cmd [lindex $argv 1]

set password "123456"

spawn ssh root@$ip $cmd

expect {

    "yes/no" {send "yes/r";exp_continue}

    "*password" {send "$password\r"}

}

expect eof

expect test.exp 192.168.1.5  "free -m"

实例5:ssh秘钥认证

生成秘钥

ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa >/dev/null 2>&1

vim test.exp

#!/usr/bin/expect

if [ $argc != 2 ] { 

    send_user "usage: expect test.exp file host\n"

    exit

}

set file [lindex $argv 0]

set host [lindex $argv 1]

set password "123456"

spawn ssh-copy-id -i $file "-p 22 root@$host"

expect {

    "yes/no"    {send "yes\r";exp_continue}

    "*password" {send "$password\r"}

}

expect eof

vim kk.sh 循环expect脚本

#!/bin/bash

for n in 2 3 4 5 6 7

do 

    expect test.exp ~/.ssh/id_dsa.pub 192.168.1.$n

done

expect操作简单 用途明了 易学易用  不过,现在工作中用的不是很多,日常也多是用来辅助其他程序脚本执行的


当前文章:Expect自动化交互应用实例解析
网页网址:http://cqcxhl.com/article/pedhds.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP