Linux expect基础

作者: seamus 分类: shell 发布时间: 2018-05-06 21:00

远程连接对方机器 执行命令,将结果保存到文件 远程传送过来,本机读取数据判断
#!/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”
#!/bin/bash
/usr/bin/expect >/dev/null 2>&1 <<EOF
spawn ssh root@192.168.2.129
expect “*password:”
send “123456\r”
expect “*#”
send ” mysql -e \”start slave;\” \r”
expect “*#”
send “exit\r”
expect eof
EOF
~

、使用脚本文件的例子–实现自动输密码
#!/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

3、在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 ;;

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 {…} –里面的多行记录,从上向下扫描匹配,谁先匹配谁先处理。
4、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}
}