温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-14 05:01:23 来源:网络 阅读:2066 作者:super李导 栏目:建站服务器


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




向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI