我们通过Shell可以实现简单的控制流功能,如:循环、判断等。但是对于需要交互的场合则必须通过人工来干预,有时候我们可能会需要实现和交互程序如telnet服务器等进行交互的功能。而Expect就使用来实现这种功能的工具。
实现登录到服务器192.168.0.100然后运行ls -l >cwmmmm.txt这条命令
==============================================
#!/usr/bin/expect -f
set timeout 30
set passwd PHILIPS
spawn ssh -lroot -p22 192.168.0.100
set timeout 1
expect "password:"
send "$passwd\r"
expect "#"
send "ls -l >cwmmmm.txt\r"
expect eof
更改远程服务器密码(先用root登录后然后更改用户cwm密码并退出
================================================
#!/usr/bin/expect -f
set timeout 30
set passwd PHILIPS
spawn ssh -lroot -p22 192.168.0.100
set timeout 1
expect "password:"
send "$passwd\r"
expect "#"
send "passwd cwm\r"
expect "New UNIX password:"
send "111111\r"
expect "Retype new UNIX password:"
send "111111\r"
expect eof #执行完后退出
interact #另外一种是执行完后不退出
{
#timeout 2 { send "ls\r" }
#{ send "ls -l\r" }
#}
批量更改密码 ./cwm1.sh 192.168.0.100 root philips PHILIPS
============================================================
#!/usr/bin/expect -f
set ipaddress [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set newpassword [lindex $argv 3]
set timeout 30
spawn ssh -l$username $ipaddress
expect "password:"
send "$password\r"
expect "#"
send "passwd\r"
expect "*password:"
send "$newpassword\r"
expect "*password:"
send "$newpassword\r"
interact
#timeout 2 { send "ls\r" }
#{ send "ls -l\r" }
#}
再运行脚本
./cwm1.sh 192.168.0.100 root philips PHILIPS
----------------------------------------------------------------------------
用expect实现自动登录SSH服务器,并在远端执行命令
脚本内容如下:
#!/usr/bin/expect -f
if {$argc<2} {
puts stderr "Usage: $argv0 host user passwaord timeout"
exit 1
}
set HOST [lindex $argv 0]
set USER [lindex $argv 1]
set PASSWD [lindex $argv 2]
set TIMEOUT [lindex $argv 3]
set timeout $TIMEOUT
spawn ssh -l $USER $HOST
# 判断是否是第一次登录
expect_before "no)?" {
send "yes\r" }
sleep 1
# 输入密码
expect "password:"
send "$PASSWD\r"
#如果想直接进入交互模式,可以直接用下面这句
#interact
#自动在远端服务器执行命令
#判断提示符
sleep 2
expect "*#"
send "mkdir /blog.zhangjianfeng.com/tmp/abcd -p\r"
send "ls -l\r"
expect "*#"
exit
## END ##
如果需要调用多台主机,可以写一个shell脚本来调用上面的脚本expect.sh
#cat callexpect.sh
#!/bin/bash
TIMEOUT=2
for i in `cat list`
do
HOST=${i%% *}
USER=`echo $i | awk -F [\ :] ‘{print $2}’`
PASS=${i##*:}
./expect.sh $HOST $USER $PASS $TIMEOUT
done
#list文件格式是 ip:user:passwd
expect -c "
18 set timeout 3600;
19 spawn scp ${path}${product}-1.0.0-${num}.i386.rpm ${path}${product}-1.0.0-${num}.i386.tmp
20 expect {
21 \"*yes/no*\" {send \"yes\r\";exp_continue}
22 \"*password*\" {send \"密码\r\";}
23 }
24 expect eof;"
阅读(2227) | 评论(0) | 转发(0) |