当前位置: 代码迷 >> 综合 >> expect--交互命令
  详细解决方案

expect--交互命令

热度:73   发布时间:2023-12-28 12:05:10.0

expect–交互命令

expect是一个免费的编程工具,用来实现自动的交互式任务,而无需人为干预。说白了,expect就是一套用来实现自动交互功能的软件。

ubuntu:

sudo apt-get install expect -y

expect常用命令总结:
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时间

案例1:

#!/usr/bin/expect 
set name [lindex $argv 0]
set passwd [lindex $argv 1]
spawn mysql -u $name -p$passwd
expect "*>*"
send "use mysql;\r"
expect "*>*"
send "CREATE USER 'ims'@'localhost' IDENTIFIED BY 'IMEinno0802';\r"
expect "*>*"
send "grant all privileges on ims.* to 'ims'@'localhost' with grant option;\r"
expect "*>*"
send "FLUSH PRIVILEGES;\r"
expect "*>*"
send "CREATE DATABASE ims;\r"
expect "*>*"
send "use ims;\r"
expect "*>*"
send "source /inno/ims/cms/sql/db.sql;\r"
expect "*>*"
send "source /inno/ims/cms/sql/init.sql;\r"
expect "*>*"
send "quit;\r"

案例2:

#!/bin/bash
passwd='123456'
/usr/bin/expect <<-EOF
set time 30
spawn ssh saneri@192.168.56.103 df -Th
expect {
    
"*yes/no" {
     send "yes\r"; exp_continue }
"*password:" {
     send "$passwd\r" }
}
expect eof
EOF

expect当前目录

proc getScriptDirectory {
    } {
    set dispScriptFile [file normalize [info script]]set scriptFolder [file dirname $dispScriptFile]return $scriptFolder
}#Example usage
set scriptDir [getScriptDirectory]
puts $scriptDir