bash / expect脚本中的错误处理

时间:2011-07-25 05:54:26

标签: bash error-handling expect

下面粘贴的是一个bash脚本,结合了expect代码,其中包含:

  • 通过ssh连接到远程主机,收集文件并准备tgz文件;
  • 将tgz文件从远程主机复制到本地计算机;
  • 再次通过ssh连接到远程主机并删除以前创建的tgz文件;
  • 最后,在本地计算机上提取tgz文件。

如果传递的参数有效(即$host$user$pass),则一切正常。如果其中一个不正确,脚本将挂起。我想知道如果用户名(或密码)不正确,如何包含一些错误处理(例如,在$ cmd1中)来终止脚本和消息?

提前感谢任何指示。

#!/bin/bash
prog=$(basename $0)
NO_ARGS=0 
E_OPTERROR=85

# Script invoked with no command-line args?
if [ $# -eq "$NO_ARGS" ]; then
  echo "Usage: $prog [-h host] [-u username] [-p password]"
  echo "       $prog -help for help."
  exit $E_OPTERROR
fi

showhelp() {
  echo "Usage: $prog [-h host] [-u username] [-p password]"
  echo " -h: host"
  echo " -u: username"
  echo " -p: password"
  echo " -help: this help message"
  exit 2
}

user=""
host=""
pass=""
now=$(date +"%m-%d-%Y")
dir="data_$now"
file="data.tgz"

while getopts "h:u:p:help" name; do
  case $name in
    h)
      host=$OPTARG
    ;;
    u)
      user=$OPTARG
    ;;
    p)
      pass=$OPTARG
    ;;
    help)
      showhelp $0
    ;;
  esac
done

if [ -d "$dir" ]; then
  rm -R $dir
  mkdir $dir
else
  mkdir $dir
fi

cmd1=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect "$ "
send "cd /tmp\n"
expect "$ "
send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
expect "$ "
send "logout"
EOF)

cmd2=$(expect << EOF
spawn scp $user@$host:/tmp/$file $dir
expect "password: "
send "$pass\n"
expect "$ "
EOF)

CMD3=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect "$ "
send "cd /tmp\n"
expect "$ "
send "rm $file\n"
expect "$ "
send "logout"
EOF)

echo "$cmd1"
echo "$cmd2"
echo "$cmd3"
cd $dir
tar -xzf $file
rm $file
count=$(ls -1 | wc -l | awk '{gsub(/^ +| +$/, "")}1')
cd ..
#clear
echo "All done. Extracted $count *.net files."

2 个答案:

答案 0 :(得分:2)

expect命令可以根据不同的答案执行不同的操作。

例如,您可以像这样定义$ cmd1:

cmd1=$(expect << EOF
spawn ssh $user@$host
expect "password: "
send "$pass\n"
expect {
{
  "Permission denied, please try again." {
       send_user "Wrong password"
       exit
   }
  "$ " {
       send "cd /tmp\n"
       expect "$ "
       send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
       expect "$ "
       send "logout"
   }
}
EOF)

如果提供的密码不起作用,此脚本将退出并打印“密码错误”消息。

有关更高级的用法,请查看手册页。这里有一些例子和许多其他选择。

答案 1 :(得分:1)

expect {
{
  "Permission denied, please try again." {
       send_user "Wrong password"
       }
  "$ " {
       send "cd /tmp\n"
       expect "$ "
       send "tar -czf $file \`find . -maxdepth 1 -name 'f2p_*' -print\`\n"
       expect "$ "
       send "logout"
   }

这里当我们删除命令exit时,期望应该打印“密码错误”而不是通过发送“cd / tmp \ n”来执行下一部分....... 这是正确的吗?