粘貼下面是一個bash腳本,結合期望代碼,其中:錯誤在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 [email protected]$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 [email protected]$host:/tmp/$file $dir
expect "password: "
send "$pass\n"
expect "$ "
EOF)
CMD3=$(expect << EOF
spawn ssh [email protected]$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."
除外?期望? –
@Ignacio拼寫更正。感謝您的評論。 – Andrej