Skip to content

Instantly share code, notes, and snippets.

@nbfritz
Last active August 29, 2015 13:57
Show Gist options
  • Save nbfritz/9810393 to your computer and use it in GitHub Desktop.
Save nbfritz/9810393 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "thor"
require "yaml"
require "open3"
class App < Thor
MAILLOG_REGEX = /^.+:(?<timestamp>\w+\s+\d+ \d\d+:\d\d:\d\d) (?<server>[^\s]+) .+ to=<(?<to>[^>]+)>.+ relay=(?<relay>[^,]+),.+status=(?<status>.+)$/
# other mail analysis-type stuff...
desc "maillog_all", "fetch all recent maillog results from app7 and app8"
def maillog_all
logs = retrieve_maillogs("cat /var/log/maillog")
keys = logs.first.keys
puts keys.join("\t")
logs.each {|l| puts keys.map {|k| l[k] }.join("\t") }
end
desc "maillog_search", "search recent maillog results from app7 and app8 for a given pattern"
def maillog_search(filter)
logs = retrieve_maillogs("grep '#{filter}' /var/log/maillog*")
keys = %w(timestamp server relay to status)
puts keys.join("\t")
logs.each {|l| puts keys.map {|k| l[k] }.join("\t") }
end
private
def retrieve_maillogs(command)
logs = %w(server1 server2).each_with_object([]) do |server, ret|
Open3.popen3("ssh #{server}.daveramsey.com #{command}") do |stdin, stdout, stderr, thread|
ret.concat parse_maillog(stdout)
end
end.sort_by {|e| e["timestamp"]}
end
def parse_maillog(stream)
stream.each_line.with_object([]) do |l, ret|
if m = l.match(MAILLOG_REGEX)
ret << m.names.each_with_object({}) {|n, log| log[n] = m[n] }
ret.last["timestamp"] = DateTime.parse(ret.last["timestamp"])
end
end
end
end
App.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment