我用文件中的解析字符串填充Ruby Hash。 (我解析了一个freeradius日志。) 现在我想为这个脚本添加过滤器,但是hash.has_key等无法识别键,这些键明显位于哈希内。
脚本:radreport
#!/usr/bin/env ruby
require 'optparse'
require 'yaml'
class AccountingEntry
attr_accessor :attributes
def initialize
@attributes = Hash.new
end
def print
puts self.to_yaml
end
end
# ------------ Get Options ------------
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: radreport [options] file"
opts.on( '-a', '--filter-attribute ATTRIBUTE', "Only show results where ATTRIBUTE is VALUE (Use with -fv)") do |attribute|
options[:filter] = 1
options[:filter_attr] = attribute
end
opts.on( '-v', '--filter-value VALUE', "Only show results where ATTRIBUTE is VALUE (Use with -fa)" ) do |value|
options[:filter] = 1
options[:filter_val] = value
end
end
optparse.parse!
if (options[:filter] && !options[:filter_attr])
puts "ERROR: Trying to filter results, but one option (-fa) is missing."
exit
elsif (options[:filter] && options[:filter_val] == nil)
puts "ERROR: Trying to filter results, but one option (-fv) is missing."
exit
end
puts options.inspect
tmp = AccountingEntry.new
# ----------- Get File ----------------
ARGV.each do|f|
if File.readable?(f)
File.open(f).each do |line|
if /(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Sep|Oct|Nov|Dec)\s\d+\s\d{2}:\d{2}:\d{2}\s\d{4}/ =~ line
if (options[:filter])
puts tmp.attributes.inspect
puts tmp.attributes.has_key?(options[:filter_attr])
if (tmp.attributes.key(options[:filter_attr]) == options[:filter_val])
tmp.print
puts "-------------------------------------------------- \n"
end
elsif
tmp.print
puts "-------------------------------------------------- \n"
end
tmp = AccountingEntry.new
end
if /\A\s*.*\s=\s".*"/ =~ line
tmp.attributes.store(line.scan(/\A\s*(.*)\s=\s".*"/)[0], line.scan(/\A\s*.*\s=\s"(.*)"/)[0])
elsif /\A\s*.*\s=\s.*/ =~ line
tmp.attributes.store(line.scan(/\A\s*(.*)\s=\s.*/)[0], line.scan(/\A\s*.*\s=\s(.*)/)[0])
end
end
end
end
输入文件:detail-test
Mon Jun 16 13:26:19 2014
User-Name = "testuser"
Timestamp = 1402917979
Mon Jun 16 13:26:24 2014
User-Name = "testuser"
Timestamp = 1402917984
输出:
$ ./radreport -a User-Name -v testuser detail-test
{:filter=>1, :filter_attr=>"User-Name", :filter_val=>"testuser"}
{}
false
{["User-Name"]=>["testuser"], ["Timestamp"]=>["1402917979"]}
false
{["User-Name"]=>["testuser"], ["Timestamp"]=>["1402917984"]}
false
通常,对于最后两个条目,输出应该为true,之后应该打印条目。 我不知道自己做错了什么..也许是问题所在,价值也在括号内?
答案 0 :(得分:0)
根据额外代码的数量来确定它有点困难,但是当它们作为字符串存储时,您似乎试图通过符号(即:filter
)来访问密钥(即{{{ 1}})。
此功能将转换它们。
"filter"