/** * Program: LogParser.java * Editor: Waue Chen * From : NCHC. Taiwn * Last Update Date: 07/17/2008 */ package tw.org.nchc.code; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SnortParser { private String logData = new String(); private String in; private String ou; public SnortParser(String in, String ou) { this.in = in; this.ou = ou; } public SnortParser() { this.in = "/var/log/snort/alert"; this.ou = "~/parseSnort.log"; } public void snortParser(String line, int i) throws ParseException, Exception { String[] data; Pattern patten_line; Matcher matcher; switch (i) { case 1: patten_line = Pattern .compile("^\\[\\**\\] \\[([1-9]*):([1-9]*):([1-9]*)\\] ([^\\[]*)\\[\\**\\]$"); break; case 2: patten_line = Pattern .compile("^\\[Classification: ([^\\]]*)\\] \\[Priority: ([1-9]*)\\].*$"); break; case 3: patten_line = Pattern .compile("(^[0-9]*)\\/([0-9]*)\\-([0-9]*)\\:([0-9]*)\\:([0-9]*)\\.[0-9]* ([^ ]*) -> ([^$]*)$"); break; case 4: patten_line = Pattern .compile("^([^ ]*) TTL:([^ ]*) TOS:([^ ]*) ID:([^ ]*) IpLen:([^ ]*) DgmLen:([^ ]*)$"); break; default: patten_line = null; break; } matcher = patten_line.matcher(line); if (matcher.matches()) { int number = matcher.groupCount(); data = new String[number]; for (int j = 0; j < number; j++) { data[j] = matcher.group(j + 1); this.logData += (data[j] + ";"); } } } void parseToLine() throws IOException, ParseException, Exception { BufferedReader fi = new BufferedReader(new FileReader(new File(in))); BufferedWriter fw = new BufferedWriter(new FileWriter(new File(ou))); String line = null; int count = 0; do { String tmp = fi.readLine(); if (tmp == null) { break; } else if (count < 4) { line = tmp; // System.out.println(line); snortParser(line, count + 1); count++; } else if (count == 4) { count++; } else if (count == 5) { fw.write(this.logData.toString() + "\n"); this.logData = ""; count = 0; } else { System.err.print(" Error ! "); return; } } while (true); fw.flush(); fw.close(); } public static void main(String[] args) throws ParseException, Exception { String in = new String("/home/waue/Desktop/alert"); String ou = new String("/home/waue/Desktop/bb"); SnortParser a = new SnortParser(in, ou); a.parseToLine(); } }