Expect 用法

inux shell脚本嵌套expect 实现远程ssh登入,传送文件

原创 deelaaay 2014-03-06 16:53:19 评论(0) 1505人阅读linux

目的:linux shell脚本嵌套expect 实现远程ssh登入,登入后执行一个命令,将命令保存到一个文件,利用scp传送文件到本地指定目录下面。shell

另外,附加几个网上的例子。bash

我的以为将下面的几个shell看懂。基本上就掌握了初步的expect 用法服务器

 

远程链接对方机器 执行命令,将结果保存到文件 远程传送过来,本机读取数据判断
#!/bin/bash
/usr/bin/expect >/dev/null 2>&1 <<EOF 
set timeout 30
spawn ssh root@192.168.2.128
expect "*password:"
send "123456\r"
expect "*#"
send "service heartbeat status >/tmp/status \r"
spawn scp  root@192.168.2.128:/tmp/status /root/ceshi-heartbeat/
expect "*password:"
send "123456\r"
expect "*#"
exit
expect eof
EOF
cat status|grep "heartbeat OK" >/dev/null 2>&1
[ $? = 0 ]&& echo "OK"
[ $? != 0 ]&& echo "not OK"ssh

 


、使用脚本文件的例子--实现自动输密码
#!/usr/bin/expect -f
set password 123456
#download
spawn scp root@192.168.1.218:/root/a.wmv /home/yangyz/
set timeout 300 
expect "root@192.168.1.218's password:"
set timeout 300 
send "$password\r"
set timeout 300 
send "exit\r"
expect eof   www.2cto.com

三、在sh脚本中嵌入expect的例子--经过连上一个公网的服务器再转跳到一个内网的服务器上,用脚本实现不用输密码,直接使用./goto.sh servername
#!/bin/bash
passmsmallq10="a"
passzhsh="a"
passfcwr="b"
passwapfx="c"
passadfx="d"

ip1="200.100.10.10"
ip2="10.100.100.70"
ip3="10.100.100.60"
ip4="10.100.100.10"
ip5="10.100.100.20"

case $1 in 
"zhsh") passstr=$passzhsh ipstr=$ip2 ;;
"fcwr") passstr=$passfcwr ipstr=$ip3 ;;
"wapfx") passstr=$passwapfx ipstr=$ip4 ;;
"adfx") passstr=$passadfx ipstr=$ip5 ;;
*) echo "The parameter $1 isn't exist"
exit 0 ;;  www.2cto.com
esac

command1="ssh -l m_smallq -p 36000 $ip1"
command2="ssh -l mqq -p 36000 $ipstr"

expect -c "
        set timeout 60;
        spawn $command1;
        expect {
                \"221.130.15.10's password:\" {send \"$passmsmallq10\r\"; exp_continue}
                \"m_smallq\" {send \"$command2\r\"; exp_continue}
                \"mqq's password:\" {send \"$passstr\r\";interact}
                }
        "

对上面例子的expect的解说
expect -c "..."  --里面输入命令
expect {...}     --里面的多行记录,从上向下扫描匹配,谁先匹配谁先处理。
www.2cto.com

四、ssh到另外一台机子执行df -h后退出,要点是send后面能够跟多个命令,经过\r来分行成多个命令
#!/bin/bash
ip1="183.62.178.191"
command1="ssh -l root -p 14322 $ip1"

expect -c "
        spawn $command1;
        expect {
                \"183.62.178.191's password:\" {send \"aa\r\"; exp_continue}
                \"root@\" {send \"df -h\r exit\r\"; exp_continue}
                }
        "spa

相关文章
相关标签/搜索