expect的用法

expect是处理交互式命令的命令,它可以将类似ssh登录,ftp登录等等需要交互式的场景自动输入登录账号密码。 使其完成自动化运行。

expect命令

  • spawn:启动新的进程
  • send:用于向进程发送字符串
  • expect:从进程接收字符串
  • interact:允许用户交互
  • exp_continue:匹配多个字符串在执行动作后加此命令

expect使用方法

expect在文本中是以/usr/bin/expect顶格写,同bash脚本不同,所以后缀不用sh来结尾

1)单一分支模式

示例:

expect1.1> expect "hi" {send "you said hi\n"}
hi
you said hi
expect1.2> 

2)多分支使用
示例:

expect1.2> expect "hi" {send "you said hi\n"}\
+> "hehe" {^C+> [root@ydong ~]# expect
expect1.1> expect "hi" {send "you said hi\n"}\
+> "hehe" {send "you said hehe"}
hi
you said hi

3)自定义脚本

[root@ydong ~]# cat test.exp 
#!/usr/bin/expect

[root@ydong ~]# cat test.exp 
#!/usr/bin/expect

spawn ssh ydong@11.2.2.228
expect {
	"yes/no" {send "yes\n";exp_continue}
        "password" {send "centos\n"}   
       }
expect eof

上述有个问题,eof表示在执行完脚本之后,退出。 这样就会导致在ssh连接上ydong的机器无法输入命令。 可以expect eof改成interact即可

[root@ydong ~]# cat test.exp 
#!/usr/bin/expect

spawn ssh ydong@11.2.2.228
expect {
	"yes/no" {send "yes\n";exp_continue}
        "password" {send "centos\n"}   
       }
#expect eof
interact

4)expect中的变量用法

[root@ydong ~]# cat test.exp 
#!/usr/bin/expect
set ip 11.2.2.228
set user ydong
set password centos


spawn ssh $user@$ip 
expect {
	"yes/no" {send "yes\n";exp_continue}
        "password" {send "$password\n"}   
       }
#expect eof
interact

5)expect中位置变量

[root@ydong ~]# cat test.exp 
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]



spawn ssh $user@$ip 
expect {
	"yes/no" {send "yes\n";exp_continue}
        "password" {send "$password\n"}   
       }
#expect eof
interact

expect test.exp  11.2.2.228 ydong centos

5)执行多个命令

[root@ydong ~]# cat test.exp 
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]



spawn ssh $user@$ip 
expect {
	"yes/no" {send "yes\n";exp_continue}
        "password" {send "$password\n"}   
       }

expect "]#" { send "useradd xixi\n" }

expect "]#" { send "echo centos | passwd --stdin haha\n"}

expect "exit\n"

expect eof
#interact

6)在shell脚本中调用expect

[root@ydong ~]# cat test1.sh 
#!/bin/bash
ip=$1
user=$2
password=$3

expect << EOF

set timeout 10
spawn ssh $user@$ip

expect {
 	"yes/no" { send "yes\n" }
        "password" {send "$password\n"}

}

expect "]#" {send "useradd heihei\n"}
expect "]#" {send "echo centos| passwd --stdin heihei\n"}
expect "]#" {send "exit\n"}
expect eof
EOF

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页