/** * 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.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SnortParser { private String logData = new String(); private BufferedReader fi ; private BufferedWriter fw ; public SnortParser(String in, String ou) throws IOException { fi = new BufferedReader(new FileReader(new File(in))); fw = new BufferedWriter(new FileWriter(new File(ou))); } public static boolean isIpAddress(String inputString) { StringTokenizer tokenizer = new StringTokenizer(inputString, "."); if (tokenizer.countTokens() != 4) { return false; } try { for (int i = 0; i < 4; i++) { String t = tokenizer.nextToken(); int chunk = Integer.parseInt(t); if ((chunk & 255) != chunk) { return false; } } } catch (NumberFormatException e) { return false; } if (inputString.indexOf("..") >= 0) { return false; } return true; } 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 { String line = null; int count = 0; do { String tmp = this.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){ this.fw.write(this.logData.toString() + "\n"); this.logData = "" ; count = 0; } else { System.err.print(" Error ! "); return ; } } while (true); this.fw.flush(); this.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(); } }