set ip 192.168,。110.2 定义变量
spawn ssh root@192.157.1111 启动追踪指令
expect connetcting (yes/no) 捕捉 会话 一定要匹配
send yes 自动发送指令
send:向进程发送字符串,用于模拟用户的输入
**interact:**执行完成后保存交互状态,把控制权交给控制台
Timeout:指定超时时间,过期则继续执行后续指令
exp_continue
send_user
流程:
spawn 启动追踪 —> expect 匹配捕捉关键字 ——> 捕捉到将触发send 代替人为输入指令—> interact /expect eof
$argv参数数组
Expect脚本必须以interact或expect eof 结束,执行自动化任务通常expect eof就够了
send命令不具备回车换行功能,一般要加 \r 或 \n
单一分支语法 expect “password:” {send “mypassword\r”;}
多分支模式语法 方式一:
expect “aaa” {send “AAA\r”}
expect “bbb” {send “BBB\r”}
expect “ccc” {send “CCC\r”}
方式二:只要匹配了aaa或bbb或ccc中的任何一个,执行了了相应的send语句后将会退出该expect语句
exoect {
“aaa” {send “AAA\r“}
“bbb” {send “BBB\r”}
“ccc” {send “CCC\r”}
}
方法三:exp_continue表示继续后面的匹配,如果匹配了aaa,执行完send语句后还要继续向下匹配bbb
exoect {
“aaa” {send “AAA\r“;exp_continue}
“bbb” {send “BBB\r”;exp_continue}
“ccc” {send “CCC\r”}
}
-re参数表示匹配正则表达式
案例:ssh远程免交互登录
[root@localhost ~]#vim a.sh
#!/usr/bin/expect //expect文件路径
set timeout 60
set hostname [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh root@$hostname
expect {
"(yes/no)"
{send "yes\r";exp_continue}
"*password"
{send "$password\r"}
}
interact
[root@localhost ~]#chmod +x a.sh
[root@localhost ~]#./a.sh 192.168.100.100 123abc
[root@localhost ~]#vim a.sh
#!/bin/bash
hostname=$1
password=$2
set timeout 60
/usr/bin/expect<<-EOF //加载expect文件路径
spawn ssh root@${hostname}
expect {
"(yes/no)"
{send "yes\r";exp_continue}
"*password"
{send "$password\r"}
}
expect "*]#" //匹配进入后的页面
send "exit\r" //触发退出
expect eof //等待结束
EOF //expect结束标志,EOF前后不能有空格
[root@localhost ~]#chmod +x a.sh
[root@localhost ~]#./a.sh 192.168.100.100 123abc
[root@localhost ~]#vim b.sh
#!/bin/bash
user=$1
password=$2
useradd $user
expect<<-EOF //加载expect文件路径
spawn passwd $user //开启进程跟踪passwd
expect {
"New password:" {send "$password\r";exp_continue} //匹配关键字并自动输入密码
"*password" {send "$password\r"} //匹配关键字并自动输入密码
}
expect eof //等待结束
EOF
[root@localhost ~]#chmod +x b.sh
[root@localhost ~]#./b.sh tom tom123
- [root@localhost ~]#vim c.sh
#!/usr/bin/expect //expect文件路径
set timeout 20
set hostname [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh root@$hostname
expect {
"Connection refused" exit
"Name or service not know" exit
"(yes/no)" {send "yes\r";exp_continue}
"*password:" {send "$password\r"}
}
interact
exit
[root@localhost ~]#chmod +x a.sh
[root@localhost ~]#./c.sh 192.168.100.100 123abc
[root@localhost ~]#vim d.sh
#!/bin/bash
hostname=$1
expect<<-EOF
spawn ftp $hostname
expect {
"Name" {send "ftp\r";exp_continue}
"Password" {send "\r"}
}
expect eof
EOF
[root@localhost ~]#chmod +x d.sh
[root@localhost ~]#./d.sh 192.168.100.100 //本机要开启ftp,对方也要开启