2022
我们一起努力

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

赞(0)
文章名称:《Expect 自动化交互应用实例解析 - 建站服务器》
文章链接:https://www.fzvps.com/31216.html
本站文章来源于互联网,如有侵权,请联系管理删除,本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
图片版权归属各自创作者所有,图片水印出于防止被无耻之徒盗取劳动成果的目的。

评论 抢沙发

评论前必须登录!