Linux expect 自动化交互工具

发布时间 2023-09-18 09:17:12作者: beautiful-life

1---expect常用命令介绍

1.1---spawn命令

spawn:通过spawn执行一个命令或者一个程序,之后所有的expect操作都会在这个执行过的命令或者程序进程中执行

spawn语法:spawn [选项] [需要自动化交互的命令或者程序]

-open: 表示启动文件进程

-ignore:表示忽略某些信号

#提示:使用spawn命令expect程序实现自动 交互工作流程的第一步,也是最关键的一步

1.2---expect命令

expect命令的作用就是获取spawn命令执行后的信息,看看是否和其事先指定的相匹配。一旦匹配上指定的内容就执行expect后面的动作,expect命令也有一些选项,相对用的较多的是-re,使用正则表达式的方式来匹配
#语法

expect 表达式 [动作]

#示例

ssh远程登录机器执行命令,首次登录需要输入yes/no和输入密码

[root@game scripts]# cat ssh.exp 
#!/usr/bin/expect
​
spawn ssh root@192.168.228.137 "free -m"
expect {
    "yes/no" {exp_send "yes\r";exp_continue}
    "*password" {exp_send "guoke123\r"}
}
expect eof
#参数说明
exp_send和send类似。\r(回车)
匹配多个字符串的时候,需要在每次匹配并执行动作后,加上exp_continue

1.3---send命令

即在expect命令匹配指定的字符串后,发送指定的字符串给系统,这些命令可以支持一些特殊转义符号,例如:\r表示回车、\n表示换行、\t表示制表符等

#参数

-i: 指定spawn_id,用来向不同的spawn_id进程发送命令,是进行多程序控制的参数

-s: s代表slowly,即控制发送的速度,使用的时候要与expect中的标量send slow相关联

1.4---exp_continue命令

作用是让expect程序继续匹配的意思 #如

expect {
    "yes/no" {exp_send "yes\r";exp_continue}
    "*password" {exp_send "guoke123\r"}
}

#因为后面还有匹配的字符,所以需要加上exp_continue,否则expect将不会自动输入指定的字符串,最后一个就不需要加上exp_continue了

1.5---send_user命令

send_user命令可用来打印expect脚本信息,类似shell里的echo命令

#用法

[root@game scripts]# cat send_user.exp 
#!/usr/bin/expect
​
send_user "guoke\n"
send_user "youtiao.\t" #tab键,没有换行
send_user "what hao\n"
​
#效果
[root@game scripts]# expect send_user.exp 
guoke
youtiao.    what hao

1.6---exit命令

exit命令的功能类似于shell中的exit,即直接退出expect脚本,除了最基本的退出脚本功能之外,还可以利用这个命令对脚本做一些关闭前的清理和提示等工作

2---expect实战

#!bin/bash

user="admin"
passwd="Zenap_123"
ip="10.220.131.184"
NS="SMF188"
SN="show nf"


/usr/bin/expect <<-EOF
spawn ssh ${user}@${ip} -p 7788
set timeout 50
expect {
        "password" {send "${passwd}\r";}
}

expect "zte:>"
        send "enter appmode:SMF188.CommonS_TMSP_0.sc-tmsp-rosng\r"
        send "con t\r"
        send "interface xgei-1/0/1/1\r"
        send "shutdown\r"

expect eof

EOF