On Fri, Dec 4, 2009 at 3:09 PM, Panagiotis Atmatzidis
<atma / convalesco.org> wrote:
> Hello,
>
> I'm a total newbe. I'm trying to figure out how to grab a specific Xth character from a .log and put it into an array.
>
> The output though parses lines the following:
>
> 2009-11-19 00:31:29,928 fail2ban.actions: WARNING [ssh-ipfw] Ban 203.169.139.171
>
> Now, I'd like to isolate the IP and put it into an Array.
>
> I would like to use the output from the cli: "$ grep Ban fail2ban.log|awkF "Ban" '{print $2}'"
>
> 0.12.200.xx
> 93.193.221.xx
> 5.72.xx.xx
> 24.207.xx.xx

$ echo '2009-11-19 00:31:29,928 fail2ban.actions: WARNING [ssh-ipfw]
Ban 203.169.139.171' | awk -F "Ban" '{print $2}'
 203.169.139.171

$ echo '2009-11-19 00:31:29,928 fail2ban.actions: WARNING [ssh-ipfw]
Ban 203.169.139.171' | ruby -ne 'print split("Ban")[1]'
 203.169.139.171

;)

>   def get_ips(filename)
>     ips = [] # make a list of ip addressses
>     File.foreach(filename) do |line|
>       puts "#{line}" if line =~ /Ban/
>     end
>   end

Incorporating that into your program snippet:

def get_ips(filename)
  ips = []
  File.foreach(filename) do |line|
    next unless line =~ /Ban/
    ips << line.split("Ban")[1]
  end
  ips
end

(Though in a real program, rather than split like above, I would
probably use a capturing regex to grab the IP address.)

Unless the file is huge, I would probably use scan:

def banned_ips_from(filename)
  File.read(filename).scan(/Ban (.*)/).flatten
end