Linux命令系列 - expect

mervyn 2018年7月23日12:48:36LinuxLinux命令系列 - expect已关闭评论171

目录

Expect是一个用来处理交互的命令。借助 expect,我们可以将交互过程写在一个脚本上,使之自动化完成。形象的说,ssh登录,ftp登录等都符合交互的定义。下文我们首先提出一个问题,然后介绍基础知四个命令,最后提出解决方法。文章源自编程技术分享-https://mervyn.life/9dc586ba.html

shell脚本实现ssh自动登录远程服务器示例:文章源自编程技术分享-https://mervyn.life/9dc586ba.html

#!/usr/bin/expect
spawn ssh root@192.168.22.194
expect "*password:"
send "123\r"
expect "*#"
interact

四个命令

Expect中最关键的四个命令是 send , expect, spawn, interact文章源自编程技术分享-https://mervyn.life/9dc586ba.html

send命令

send命令用于向进程发送字符串, 接收一个字符串参数,并将该参数发送到进程。文章源自编程技术分享-https://mervyn.life/9dc586ba.html

expect1.1> send "hello world\n"
hello world

expect命令

expect 命令从进程接收字符串。 expect 可以接收一个字符串参数,也可以接收正则表达式参数。文章源自编程技术分享-https://mervyn.life/9dc586ba.html

单一分支模式语法

expect "hi" {send "You said hi"}

匹配到 hi 后,会输出 "you said hi"文章源自编程技术分享-https://mervyn.life/9dc586ba.html

多分支模式语法

expect "say" { send "said\n" } \
"hello" { send "Hello world\n" } \

等价于如下写法:文章源自编程技术分享-https://mervyn.life/9dc586ba.html

expect {
"say" { send "said\n"}
"hello" { send "Hello world\n"}
}

spawn命令

spawn命令用于启动新的进程。spawn 后的 send 和 expect 命令都是和 spawn 打开的进程进行交互的。文章源自编程技术分享-https://mervyn.life/9dc586ba.html

interact

interact 允许用户交互。文章源自编程技术分享-https://mervyn.life/9dc586ba.html

实际应用

ssh 自动登录

shell 文件名: ssh_login.sh文章源自编程技术分享-https://mervyn.life/9dc586ba.html

#!/usr/bin/expect  -f

#接收第一个参数,并设置IP
set ip [lindex $argv 0 ]

#接收第二个参数,并设置密码
set password [lindex $argv 1 ]
set port [lindex $argv 2 ]

#设置超时间
set timeout 10
#发送ssh请滶
spawn ssh root@$ip -p $port
expect {
        "*yes/no" { send "yes\r"; exp_continue}
        "*password:*" { send "$password\r" }
}
interact

通过执行以下命令即可文章源自编程技术分享-https://mervyn.life/9dc586ba.html

ssh_login.sh 127.0.0.1 'xxx' 22

实际工作中,可以为上述命令设置一个 alias文章源自编程技术分享-https://mervyn.life/9dc586ba.html

weinxin
我的微信公众号
微信扫一扫
mervyn
Linux 文本三剑客 - sed Linux

Linux 文本三剑客 - sed

sed 是 stream editor 它是一种流编辑器,一次处理一行内容 。 基本用法如下: # sed --help sed ... {script-only-if-no-other-script...