仅将命令输出记录到文件中

时间:2015-04-17 08:23:34

标签: ssh expect

我想记录我在期望的SSH生成脚本中运行的一些命令的输出,但我希望输出非常干净。我已经在互联网上找到了一些关于日志记录的信息,但除了将命令发送到日志文件外它不起作用。

---从剧本中间开始,这是我的步骤---

expect -re ">" 

log_file "settings.txt";

send_user "show device\n"

expect -re ">"

log_file "rules.txt";

send "show access-rules\n"

expect -re ">"

log_file "interfaces.txt";

send "show interface all\n"

expect -re ">"

log_file "cfs.txt";

send "show tsr content-filtering\n"

expect -re ">"

log_file "routes.txt";

send "show routes\n"

expect -re ">"

log_file "nat.txt";

send "show nat\n"

expect -re ">"

send "exit\n"

send_user命令仅将命令发送到日志文件,send_log命令也是如此。我只希望将该命令的输出发送到日志文件,该命令本身也允许在日志中。

1 个答案:

答案 0 :(得分:0)

您实际需要的是抑制基本上解释为heresend命令的输出。 (我猜这是你的要求。只写命令的输出,而不是命令。)

由于log_userlog_file在登录文件时非常紧密,我们必须使用send_log进行调整。

基本思想可以概括为

# We escaped the `$` symbol with backslash to match literal '$'
# The second dollar sign is meant to match the end of a line
set prompt "#|>|\\\$$"  
log_file output.log
send "show command here\r"
log_user 0
expect -re "\r\n(.*)$prompt"; # match actual command output
log_user 1
send_log "$expect_out(1,string)"; # Sending it to the log file

现在,根据您的要求,您希望将其发送到每个命令的单独文件。您可以在单独的列表中定义这些命令输出的命令和文件名。

spawn ssh <host> <port>
# Further your logic to handle the login

proc getCmdOutput {cmd} {
 global cmdsList logFileList
 set prompt "#|>|\\\$$"; 
 # Finding the log file name based on the 'cmd' passed
 log_file -noappend [lindex $logFileList [lsearch $cmdsList $cmd]]
 send "$cmd\r"
 log_user 0
 expect -re "\r\n(.*)$prompt"
 log_user 1
 send_log "$expect_out(1,string)"; # Sending command output to file
 log_file; # Removing logging of file.
}


set cmdsList {
        "show version"
        "show interfaces"
        "show services"
        "show vlan"
}

set logFileList {
        version.log
        interfaces.log
        services.log
        vlan.log
}


foreach cmd $cmdsList {
        getCmdOutput $cmd
}

请注意,cmdsListlogFileList列表在命令和相应的日志文件名方面应该是相同的。