expect - programmed dialogue with interactive programs
Expect is a program that “talks” to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue.
yum install expect -y
[root@141 mnt]# cat ssh.exp
#!/usr/bin/expect
set timeout 30 #设置超时时间,永不超时则设为-1
spawn ssh root@172.25.254.79
expect "*password:" #若出现password字符则立即返回,否则等待30s
send "westos\r" #输入密码并回车
interact #执行完成后保持交互状态,把控制权交给控制台
spawn是进入expect环境后的内部命令。
The spawn daemon provides the Postfix equivalent of inetd. It listens on a port as specified in the Postfix master.cf file and spawns an external command whenever a connection is established. The connection can be made over local IPC (such as UNIX-domain sockets) or over non-local IPC (such as TCP sockets). The command´s standard input, output and error streams are connected directly to the communication endpoint.
结果:运行后直接登录
[root@141 mnt]# expect ssh.exp
spawn ssh root@172.25.254.79
root@172.25.254.79's password:
Last login: Wed Jun 27 13:56:50 2018
Expect嵌套Shell
[root@141 mnt]# cat expect.exp
#!/usr/bin/expect
set timeout 2
spawn /mnt/sh_expect.sh
expect "*feel:"
send "sharp\r"
expect eof ##结束标示
shell脚本
[root@141 mnt]# cat sh_expect.sh
#!/bin/bash
read -p "How does the air feel:" FEELING
echo "The air feels $FEELING"
[root@141 mnt]# expect expect.exp
spawn /mnt/sh_expect.sh
How does the air feel:sharp
The air feels sharp
执行shell命令
exec sh -c {rht-vmctl start desktop}
shell嵌套expect
[root@141 mnt]# cat expect_in_shell.sh
#!/bin/bash
passwd=$2
/usr/bin/expect <<EOF
spawn ssh root@$1
expect {
"(yes/no)" ##这里expect可以选择符合条件的命令执行
{
send "yes\r"
expect "*password:" {send "$2\r"}
}
"*password:"
{
send "$2\r"
}
}
expect eof
EOF
自动登录
[root@141 mnt]# sh expect_in_shell.sh 172.25.254.79 westos
spawn ssh root@172.25.254.79
root@172.25.254.79's password:
Last login: Wed Jun 27 20:05:24 2018 from xupt.sports.com