expect 保存日志文件
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步