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

问题描述 投票:0回答:2

我有一个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

此程序运行完美,我从anothe 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

因此,我只希望将期望脚本发送的消息存储到日志中,例如上面的示例“系统192.168.5.101未知”

我该怎么做?谢谢卢卡斯

bash logging expect
2个回答
1
投票

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
---
---
---

0
投票

如果通过输入来执行脚本

./yourscript

然后您可以使用类似以下管道的内容:

./yourscript | sed -n '/^System.*is unknown$/p' > logfile
© www.soinside.com 2019 - 2024. All rights reserved.