应用于自动化交互式操作的场景,借助expect处理交互的
命令,可以将交互过程写在一个脚本上使之自动化完成,
适用于多台服务器执行相同操作的环境。
expect语法:
expect [选项] [-c cmds] [ [ - [ f | b] ] cmdfile ] [ args ]
选项
-c:从命令行执行expect脚本,默认expect是交互地执行的
示例:expect -c ‘expect "\n" {send "pressed enter\n"}‘
-d: 可以输出调试信息
eg:expect -d ssh.exp
expect 中相关命令
spawn:启动新的进程;监控交互式,并且激活。
send:用于向进程发送字符串、
expect:从进程接收字符串
interact:允许用户交互
exp_continue 匹配多个字符串在执行动作后加此命令
expect eof:表示退出
#!/bin/bash
spawn scp /etc/fatab wang@192.168.0.12:/data
expect {
"yes/no" {send "yes\n";exp_continue}
"password" {send "magedu\n"}
}
expect eof
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
spawn ssh $user@$ip
expect{
"yse/no" { send "yes\n";exp_continue }
"password" { send "redhat }
}
interact
执行多个命令:
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 10
spawn ssh $user@$ip
expect {
"yes/no" { send "yse\n;exp_continue" }
"password" { send "$password\n"}
}
expect "]#" { send "useradd haha\n"}
expect "]#" {send "echo magedu |passwd --stdin haha\n"}
send "exit\n"
expect eof
#!/bin/bash
ip=$1
user=$2
password=$3
expect << EOF
set timeout 10
spawn ssh $user@$ip
expect {
"yes/no" { send "yes\n; exp_continue" }
"password" { send "passwor\n" }
}
expect "]#" { send "useradd haha\n" }
expect "]#" { send "echo redhat |passwd --stdin haha\n" }
expect eof
EOF
注意:expect 中 {}内,不必担心与{是否有空格,这个没有影响的。
原文:https://blog.51cto.com/14907072/2536701