expect 是一个自动交互的工具。
场景:检查远程主机是否存在某个文件
CheckRemote.sh
#!/usr/bin/expect
set RemoteHost "..."
set User "..."
set Pwd "..."
set RemotePath "..."
set FileName "..."
set CMD "find $RemotePath -name $FileName | wc -l"
spawn ssh $User@$RemoteHost $CMD
expect
{
"password" { send "$Pwd\n" }
}
spawn false
expect eof
catch wait retValue
exit [lindex retValue 3]
# lindex 索引访问
CheckRemoteRet.sh
#!/bin/bash
ret=`./CheckRemote.sh`
echo "$ret" | sed -n '2p'