1.下载expcet相关文件
tcl 地址:https://sourceforge.net/projects/tcl/files/Tcl/ 选择一个版本
expect 地址:https://sourceforge.net/projects/expect/files/Expect/ 选择一个版本
国外的网站,下载会比较慢。(个人已经下载了expect5.45.tar.gz和tcl8.6.8-src.tar.gz,上传到了个人的百度云盘)
2.安装
先安装tcl
[root@localhost ~]$ tar -zxvf tcl8.6.8-src.tar.gz
[root@localhost ~]$ cd tcl8.6.8/unix
[root@localhost ~]$ ./configure --prefix=/usr/tcl --enable-shared
[root@localhost ~]$ make
[root@localhost ~]$ make install
[root@localhost ~]$ cp tclUnixPort.h ../generic
安装完毕以后,把unix目录下面的tclUnixPort.h copy到子目录generic中。
暂时不要删除tcl源代码,因为expect的安装过程还需要用。
安装expect
[root@localhost ~]$ tar -zxvf expect5.45.tar.gz
[root@localhost ~]$ cd expect5.45
[root@localhost ~]$ ./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.6.8/generic
[root@localhost ~]$ make
[root@localhost ~]$ make install
[root@localhost ~]$ ln -s /usr/tcl/bin/expect /usr/expect/bin/expect
3.编写expect脚本
[username@localhost ~]$ vi expectshell //添加以下内容
#!/usr/expect/bin/expect //expect脚本命令的位置
set remote_ip "192.168.1.103"
set pass_wd "some password"
spawn scp tcl8.6.8-src.tar.gz username@192.168.1.103:/home/username/tcl.tar.gz //spawn 后面跟一个命令,开启一个会话,这里是一个copy文件的命令
expect "*assword:"
send "${pass_wd}\r" //输入密码
spawn ssh username@192.168.1.103 //开启另一个,ssh登录
expect "*assword: "
send "${pass_wd}\r"
expect "Last login:*"
send "ifconfig\r" //查看ip信息
expect "*flags*"
send "su root\r" //切换root用户
expect "*assword:"
send "${pass_wd}\r"
send "cd /usr\r"
send "mkdir test\r"
send exit\r"
expect eof //结束
保存后赋予权限,执行检查结果
[username@localhost ~]$ chmod 755 expectshell
[username@localhost ~]$ ./expectshell
4. 使用expect输入参数
#!/usr/bin/expect -f
if {$argc < 3} {
#do something
send_user "usage: ./expectshell <remote_user> <remote_host> <remote_pwd>"
exit
}
set timeout -1
set remote_user[lindex $argv 0 ] //接收第一个参数,并登录用户名
set remote_host [lindex $argv 1 ] //接收第一个参数,并设置IP
set remote_pwd [lindex $argv 2 ] //接收第二个参数,并设置密码
set timeout -1 //设置超时时间
spawn ssh ${remote_user}@${remote_host} //发送ssh请滶
expect { //返回信息匹配
"*yes/no" { send "yes\r"; exp_continue} //第一次ssh连接会提示yes/no,继续
"*password:" { send "${remote_pwd}\r" } //出现密码提示,发送密码
}
interact //交互模式,用户会停留在远程服务器上面.