资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Expect自动化交互应用实例解析-创新互联

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

创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都做网站、成都网站制作、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的铜仁网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

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操作简单 用途明了 易学易用  不过,现在工作中用的不是很多,日常也多是用来辅助其他程序脚本执行的

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


新闻标题:Expect自动化交互应用实例解析-创新互联
浏览地址:http://cdkjz.cn/article/cshepp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220