一、下载工具
- Expect工具是依赖tcl的,所以需要先检查是否安装tcl
[root@localhost ~]# whereis tcl
tcl: /usr/lib64/tcl8.5 /usr/share/tcl8.5
- 如果没有安装运行下面命令安装
[root@localhost ~]# yum install -y tcl
[root@localhost ~]# yum install -y expect
- 查看expect的安装路径
[root@localhost ~]# command -v expect
/usr/bin/expect
二、选项介绍
spawn
启动新的交互进程, 后面跟命令或者指定程序expect
从进程中接收信息, 如果匹配成功, 就执行expe原文链接:https://www.dqzboy.com ct后的动作send
向进程发送字符串send exp_send
用于发送指定的字符串信息exp_continue
在expect中多次匹配就需要用到send_user
用来打印输出 相当于shell中的echointeract
允许用户交互exit
&nbs文章来源(Source):浅时光博客 p; 退出expect原文链接:https://www.dqzboy.com 脚本eof
expect执行结束, 退出set
定义变量puts
输出变量set timeout
设置超时时间
三、使用实践
1、免交互拷贝公钥
1.1:编辑脚本
[root@localhost ~]# vim autocopy.exp
#!/usr/bin/expect
set timeout 10
set user_hostname [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh-copy-id $user_hostname
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword:" { send "$password\n"}
}
"*assword:"
{
send "$password\n"
}
}
expect eof
[root@localhost ~]# chmod +x autocopy.exp
1.2:测试使用
[root@localhost ~]# ./autocopy.exp root@192.168.66.100 密码

2、SCP自动应答脚本
2.1:编辑脚本
[root@localhost ~]# vim autocopy.exp
#!/usr/bin/expect
set timeout 10
set user_hostname [lindex $argv 0]
set src_file [lindex $argv 1]
set dest_file [lindex $argv 2]
set password [lindex $argv 3]
spawn scp $src_file $user_hostname:$dest_file
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword:" { send "$password\n"}
}
"*assword:"
{
send "$password\n"
}
}
expect "100%"
expect eof
[root@localhost ~]# chmod +x autocopy.exp
2.2:测试使用
- 用法:
autoscp.exp [user@]hos
文章来源(Source):浅时光博客 tname文章来源(Source):https://www.dqzboy.com 源文件 目标目录 [password] - 说明:该自动回答脚本可以自动完成主机验证和密码认证,即使已经是实现公钥认证的机器也没问题,因为公钥认证机制默认优先于密码认证,且此脚本的password项是可选的,当然,在没有实现公钥认证的情况下,password是必须项,否则expect实现非交互的目的就失去意义了。
必须 注册 为本站用户, 登录 后才可以发表评论!