用grep远程日志文件尾

x13*_*x13 6 ruby logging grep tail

我有这个代码来尾随远程日志文件:

def do_tail( session, file )
  session.open_channel do |channel|
  channel.on_data do |ch, data|
    puts "[#{file}] -> #{data}"
  end
  channel.exec "tail -f #{file}" 
end

Net::SSH.start("host", "user", :password => "passwd") do |session|
  do_tail session, "/path_to_log/file.log"
  session.loop
Run Code Online (Sandbox Code Playgroud)

我想只检索带有ERROR字符串的行file.log,我试图调用tail -f #{file} | grep ERROR但没有成功.

Dan*_*G2k 0

我不确定你想tail -f #{file} | grep ERROR.loop. 该-f标志告诉您tail继续流式传输数据,并且您永远不会使用 Ctrl+C 退出该流。

您可能只想使用一个简单的 Bash 命令来实现此目的,而您甚至不需要该.exec方法。尝试如下操作:

def do_tail session, file
  @keyword = 'ERROR'
  session.open_channel do |channel|
    channel.on_data {|ch, data| puts "[#{file}] -> #{data}"}
    `grep #{keyword} #{file}`
  end 
end
Run Code Online (Sandbox Code Playgroud)