Linux-expect脚本编程
目录
一,expect运用
1,spawn命令
2,expect命令
3,send命令
4,exp_continue命令
5,send_user命令
6,expect变量
8,expect之内常用关键字
一,expect运用
工作流程:首先expect内部命令spawn打开指定进程-expect得到关键字-内部命令send向指定进程发送响应-进程执行完成之后,退出expect程序
1,spawn命令
spawn作用:新的产生交互的进程
spawn【选项】 【需要执行的shell命令或程序等】
(1),
expect
spawn passwd lu
expect "*密码:"
send "123456\r"
expect "*密码:"
send "123456\r"
expect eof
exit
#怎样用expect实现交互式更改密码
2,expect命令
expect作用:得到从spawn命令执行的命令和程序后产生的交互信息。看看是否匹配,匹配则开始执行expect进程接收字符串
expect语法:expect 【选项】 表达式【动作】
(2),
expect "hi" {send "say hi\n"}
hi
say hi
#expect语句的单分支结构
(3),
expect "hi" {send "say hi\n"} "bye" {send "byebye\n"}
bye
byebye
#expect语句的多分支结构
3,send命令
send命令的主要作用是:expect命令匹配完指定字符后,发送指定的字符串给程序系统
4,exp_continue命令
exp_continue命令的主要作用是,需要匹配多个字符串,那么多次匹配字符串并执行的不同动作之内,可以帮助expect实现继续匹配
(4),
#!/usr/bin/expect
spawn passwd jenkins
expect {
"新的密码:" { send "q1w2e3@123!!!!!\r"; exp_continue }
"新的密码:" { send "q1w2e3@123!!!!!\r" }
eof
}
#运用expect_continue实现非交互式更改用户jenkins的密码
5,send_user命令
send_user命令的作用是,用来打印expect脚本信息
(5),
#!/bin/bash
a=$1
b=$2
c=$3
/usr/bin/expect <<EOF
send_user "$a\n"
send_user "$b\t"
send_user "$c\n"
EOF
$1
$2 #3
#用send_user实现打印命令行的作用
6,expect变量
(6),
#!/usr/bin/expect
set a "123"
set b "abc"
puts "$a\t $b\n"
123 abc#用puts命令在expect之内调用变量
set <变量名称> [lindex $argv <param index>}
(8),
#!/usr/bin/expect
set a [ lindex $argv 0 ]
set b [ lindex $argv 1 ]
SET C [ lindex $argv 2 ]
puts "abc: $a $b $c"
$a $b $c
#用expect之内的[lindex $argv]实现位置参数的传递
8,expect之内常用关键字
(9),
#!/usr/bin/expect
if {test1} {
command1;
}if {test2} {
command2;
} else {
command3;
}
#expect之内if语句的语法结构
(10),
#!/usr/bin/expect
for { set i 1 } { i<=10 } { incr i 1 } {
puts "$i"
}
1
2
3
4
5
6
7
8
9
10
#在expect之内实现for语句的结构
(11),
#!/usr/bin/expect
set i 1
{ while i<=10 } {
puts "$i"
sleep 1
incr i 1
}
1
2
3
4
5
6
7
8
9
10
#在expect之内实现while语句的结构
打赏链接: