expect是交互性很强的脚本语言,可以帮助运维人员实现批量管理成千上百台服务器操作,是一款很实用的批量部署工具!
expect依赖于tcl,而linux系统里一般不自带安装tcl,所以需要手动安装
下载:expect-5.43.0.tar和tcl8.4.11-src.tar
可以到Linux公社资源站下载:
------------------------------------------分割线------------------------------------------
具体下载目录在 /2017年资料/2月/20日/expect环境安装以及简单脚本测试/
------------------------------------------分割线------------------------------------------
将expect和tcl的软件包下载放到/usr/local/src目录下
----------------------------------------------------------------------------------------------------
下面结合shell脚本做简单测试:
例1:
从本机自动登录到远程机器192.168.1.200(端口是22,密码是:PASSWORD)
登录到远程机器后做以下几个操作:
1)useradd wangshibo
2)mkdir /opt/test
3) exit自动退出
*******************************************************************************************************
例2:
我们在部署无密码访问时,手工建立ssh互信需要好几个步骤,并且中途人工交互(输入密码等),如果机器数目多,则很繁琐!
下面方法用于自动化生成authorized_keys,免去了手工数据.
方法: 利用expect编写sshkey.exp在远程主机上生成id_rsa,并重定向到本地.在利用noscp.exp.把文件复制到远程主机
为了节省自己的时间,可以写个expect自动化脚本,分享如下:
#sshkey.exp
if {$argc<3} {
puts stderr "Usage: $argv0 host user passwd "
exit 1
}
set host [ lindex $argv 0 ]
set user [ lindex $argv 1 ]
set pwd [ lindex $argv 2 ]
set timeout 30
#spawn ssh ${user}@${host} "rm -rf ~/.ssh/id_rsa*"
#
#expect {
# "*yes/no" { send "yes\r"; exp_continue }
# "*password:" { send "$pwd\r"; exp_continue }
#}
spawn ssh ${user}@${host} "ssh-keygen -t rsa"
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r"; exp_continue }
"Enter file in which to save the key*" { send "\n\r"; exp_continue }
"Overwrite*" { send "y\n"; exp_continue }
"Enter passphrase (empty for no passphrase):" { send "\n\r"; exp_continue }
"Enter same passphrase again:" { send "\n\r" }
}
spawn ssh ${user}@${host} "cat ~/.ssh/id_rsa.pub"
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}
expect eof
#noscp.exp
if {$argc<4} {
puts stderr "Usage: $argv0 localfile remotefile user passwd "
exit 1
}
set localfile [ lindex $argv 0 ]
set remotefile [ lindex $argv 1 ]
set user [ lindex $argv 2 ]
set pwd [ lindex $argv 3 ]
set timeout 30
spawn scp ${localfile} ${user}@${remotefile}
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}
expect eof
------------------------------------------------------------------------
(4)
脚本说明
./sshkey.exp 主机名 用户名 密码 (在远程主机生成id_rsa)
./noscp.exp 本地文件 远程路径 远程用户密码 (无密码拷贝文件)
--------------------------------------------------------------------------
如果是多台机器的话,可以结合shell脚本进行批量执行