1. $expect_out(buffer) 這種方式需要注意不能在shell嵌套expect的情況下使用,因爲在這種情況下expect腳本中的$xx變量會被解析成shell部分傳入的參數,無法起到原本在expect腳本下的作用。 其次,$expect_out(buffer)需要和send內容在兩個不同的expect循環中出現。 #!/bin/expect set user "root" set host "10.25.103.2" set loginpass "eve" spawn ssh -p 23 $user@$host set timeout 30 set ofile "info_$host" # 在本地創建日誌 set output [open $ofile "w"] # 打開日誌,準備寫入 expect { -re "Are you sure you want to continue connecting (yes/no)?"{ send "yes\r" } -re "password:" { send "${loginpass}\r" } -re "Permission denied, please try again." { exit } } expect { "#" { send {cat /proc/net/dev} send "\r" } } expect { "#" { set outcome $expect_out(buffer) # 獲取回顯 send "\r" puts $output $outcome # 將回顯寫入日誌 unset expect_out(buffer) # 清空回顯緩存 } } close $output # 關閉日誌文件 expect { -re $cmd_prompt { send "exit \r" } } interact
在/usr/bin/expect<<-EOF中創建日誌文件(終端有回顯)
主要寫法,就是在/usr/bin/expect<<-EOF下面添加一行:
/usr/bin/expect<<-EOF
log_file ssh.log
......
EOF
日誌將保存到ssh.log文件中
在/usr/bin/expect <<EOF中創建日誌文件(終端無回顯)
這種方式就是直接把回顯寫入日誌文件,這樣本地終端就不會有回顯了,乾淨了許多,方法就是利用輸出重定向:
/usr/bin/expect <<EOF > ${log_file}
....
EOF
同時在expect腳本之後我們可以對回顯結果進行一個判斷,查看是否有報錯:
/usr/bin/expect <<EOF > ${log_file}
set timeout -1
spawn ssh -p 23 ${user_name}@${host_ip}
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword:" { send "${user_password}\n"}
}
"*assword:"
{
send "${user_password}\n"
}
}
sleep 1
send "${cmd}\n"
send "exit\n"
expect eof
EOF
cat ${log_file} | grep -iE "Permission denied|failed" >/dev/null
if [ $? -eq 0 ];then
echo "Script execute failed!"
return 1
fi