从输出中获取特定消息并将信息存储到日志文件

Get specific message from output and store info to a log file

我有一个 telnet 期望脚本,仅用于检查服务器是否正常。

#!/usr/bin/expect
set IP 192.168.5.100
catch {spawn -noecho telnet $IP}
set timeout 3
expect {
  timeout
    { send_user "Telnet timed out waiting for $IP\n" ; exit }
  "onnection refused"
    { send_user "Connection was refused to $IP\n" ; exit }
  "No route"
    { send_user "System $IP is unknown\n" ; exit}
  "login:"
}
send_user "Success\n" ; exit

它工作完美,我从另一个 bash 脚本调用它以将消息存储到日志文件中。问题是输出信息太多,例如如果无法访问服务器:

# ./checkconn.expect                 
Trying 192.168.5.101...
telnet: connect to address 192.168.5.101: No route to host
System 192.168.5.101 is unknown

如果服务器可以访问:

Trying 192.168.5.100...
Connected to 192.168.5.100.
Escape character is '^]'.
--- Unauthorised access prohibited ---
This is a closed-access system. If you do not have permission
to access this system, then log off now. If you remain logged on
you consent to monitoring of your actions.
z1 login: Success

所以我只想将 expect 脚本发送的消息存储到日志中,如上例 "System 192.168.5.101 is unknown"

我该怎么做? 谢谢 卢卡斯

如果你的脚本是通过输入

执行的
./yourscript

然后你可以使用类似下面的管道:

./yourscript | sed -n '/^System.*is unknown$/p' > logfile

expect 实用程序具有名为 log_file 的过程来记录日志。

man expect中:

log_file [args] [[-a] file]
             If  a filename is provided, log_file will record a transcript of the session (beginning at that point) in the file.  log_file will stop recording if no argument is given.  Any previous log file is
             closed.

         Instead of a filename, a Tcl file identifier may be provided by using the -open or -leaveopen flags.  This is similar to the spawn command.  (See spawn for more info.)

         The -a flag forces output to be logged that was suppressed by the log_user command.

         By default, the log_file command appends to old files rather than truncating them, for the convenience of being able to turn logging off and on multiple times in one session.  To  truncate  files,
         use the -noappend flag.

         The -info flag causes log_file to return a description of the most recent non-info arguments given.`

你可以这样使用:

#!/usr/bin/expect
set IP 192.168.5.100
catch {spawn -noecho telnet $IP}
set timeout 3
log_file your_log_file.log
---
---
---