标签:
expect是交互性很强的脚本语言,可以帮助运维人员实现批量管理成千上百台服务器操作,很实用!
expect依赖于tcl,而linux系统里一般不自带安装tcl,所以需要手动安装
下载:expect-5.43.0.tar和tcl8.4.11-src.tar
下载地址:https://pan.baidu.com/s/1kVyeLt9
提取密码:af9p
将expect和tcl的软件包下载放到/usr/local/src目录下
(1)解压tcl,进入tcl解压目录,然后进入unix目录进行编译安装
[root@localhost src]# tar -zvxf tcl8.4.11-src.tar.gz
[root@localhost src]# cd tcl8.4.11/unix
[root@localhost unix]# ./configure
[root@localhost unix]# make && make
(2)安装expect
[root@localhost src]# tar -zvxf expect-5.43.0.tar.gz
[root@localhost src]# cd expect-5.43.0
[root@localhost expect-5.43.0]# ./configure --with-tclinclude=/usr/local/src/tcl8.4.11/generic --with-tclconfig=/usr/local/lib/
[root@localhost expect-5.43.0]# make && make install
(3)安装完成后进行测试
[root@localhost ~]# expect
expect1.1>
expect1.1>
----------------------------------------------------------------------------------------------------
下面结合shell脚本做简单测试:
从本机自动登录到远程机器192.168.1.200(端口是22,密码是:PASSWORD)
登录到远程机器后做以下几个操作:
1)useradd wangshibo
2)mkdir /opt/test
3) exit自动退出
[root@xw4 tmp]# cat test-ssh.sh
#!/bin/bash
passwd=‘PASSWORD‘
/usr/local/bin/expect <<-EOF
set time 30
spawn ssh -p22 root@192.168.1.201
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect "*#"
send "useradd wangshibo\r"
expect "*#"
send "mkdir /opt/test\r"
expect "*#"
send "exit\r"
interact
expect eof
EOF
[root@xw4 tmp]# sh test.sh
spawn ssh -p22 root@192.168.1.201
root@192.168.1.201‘s password:
Last login: Fri Sep 23 16:21:20 2016 from 192.168.1.23
[root@vm-002 ~]# useradd wangshibo
[root@vm-002 ~]# mkdir /opt/test
[root@vm-002 ~]# [root@xw4 tmp]#
标签:
原文地址:http://www.cnblogs.com/kevingrace/p/5900303.html