TCP和UDP的Syslog日志接收与解析

接收UDPSyslog日志(直接使用Socket编程监听端口,得到原始字符串)

  1   2 
  3 import java.io.IOException;
  4 import java.net.DatagramPacket;
  5 import java.net.DatagramSocket;
  6 import java.net.InetAddress;
  7 import java.net.InetSocketAddress;
  8 import java.net.SocketException;
  9 
 10 import com.icssla.platform.common.AppLogger;
 11 
 12 /**
 13  * UDP服务类.  采集syslog
 14  */
 15 public class UdpServerSocket {//implements IUdpServerSocket
 16     private byte[] buffer = new byte[1024];
 17 
 18     private DatagramSocket ds = null;
 19 
 20     private DatagramPacket packet = null;
 21 
 22     private InetSocketAddress socketAddress = null;
 23 
 24     private String orgIp;
 25 
 26     private String curIp = "192.168.1.128";
 27 
 28     /**
 29      * 构造函数,绑定主机和端口
 30      * 
 31      * @param host 主机
 32      * @param port 端口号
 33      * @throws SocketException 
 34      * @throws Exception
 35      */
 36     
 37     public UdpServerSocket(int port) throws SocketException {
 38         socketAddress = new InetSocketAddress(port);
 39         ds = new DatagramSocket(socketAddress);
 40 //        System.out.println("--------------udp service start----------------");
 41     }
 42 
 43     public final String getOrgIp() {
 44         return orgIp;
 45     }
 46 
 47     public final String getCurIp() {
 48         return curIp;
 49     }
 50 
 51     /**
 52      * 设置超时时间,该方法必须在bind方法之后使用
 53      * @param timeout 超时时间
 54      * @throws Exception
 55      */
 56     public final void setSoTimeout(int timeout) throws Exception {
 57         ds.setSoTimeout(timeout);
 58     }
 59 
 60     /**
 61      * 获得超时时间
 62      * 
 63      * @return 返回超时时间
 64      * @throws Exception
 65      */
 66     public final int getSoTimeout() throws Exception {
 67         return ds.getSoTimeout();
 68     }
 69 
 70     /**
 71      * 绑定监听地址和端口
 72      * @param host 主机IP
 73      * @param port 端口
 74      * @throws SocketException
 75      */
 76     public final void bind(String host, int port) throws SocketException {
 77         socketAddress = new InetSocketAddress(host, port);
 78         ds = new DatagramSocket(socketAddress);
 79     }
 80 
 81     /**
 82      * 接收数据包,该方法会造成线程阻塞
 83      * 
 84      * @return 返回接收的数据串信息
 85      * @throws IOException
 86      */
 87     public final String receive() throws Exception {
 88         packet = new DatagramPacket(buffer, buffer.length);
 89         ds.receive(packet);
 90         orgIp = packet.getAddress().getHostAddress();
 91         String info = new String(packet.getData(), 0, packet.getLength());
 92 //        System.out.println("UdpServerSocket receive "+info);
 93         return info;
 94     }
 95 
 96     /**
 97      * 接收日志并返回字符串
 98      * 
 99      * @return
100      * @throws Exception
101      */
102     public final String receiveReturnStr() throws Exception {
103         packet = new DatagramPacket(buffer, buffer.length);
104         ds.receive(packet);
105         orgIp = packet.getAddress().getHostAddress();
106         String info = new String(packet.getData(), 0, packet.getLength());
107 //        System.out.println("UdpServerSocket Receive "+info);
108 
109         return info;
110     }
111 
112     /**
113      * 将响应包发送给请求端 
114      * @param info 回应报文
115      * @throws IOException
116      */
117     public final void response(String info) throws IOException {
118 //        System.out.println("Client IP" + packet.getAddress().getHostAddress()
119 //                + ",Port:" + packet.getPort());
120         DatagramPacket dp = new DatagramPacket(buffer, buffer.length, packet
121                 .getAddress(), packet.getPort());
122         dp.setData(info.getBytes());
123         ds.send(dp);
124     }
125 
126     /**
127      * 设置报文的缓冲长度
128      * @param bufsize 缓冲长度
129      */
130     public final void setLength(int bufsize) {
131         packet.setLength(bufsize);
132     }
133 
134     /**
135      * 获得发送回应的IP地址
136      * @return 返回回应的IP地址
137      */
138     public final String getResponseAddress() {
139 //        System.out.println("IP receive "+packet.getAddress().toString().substring(1));
140         return packet.getAddress().toString().substring(1);
141     }
142 
143     /**
144      * 获得回应的主机的端口
145      * @return 返回回应的主机的端口
146      */
147     public final int getResponsePort() {
148         return packet.getPort();
149     }
150 
151     /**
152      * 关闭udp监听口
153      */
154     public final void close() {
155         try {
156             ds.close();
157         } catch (Exception ex) {
158             ex.printStackTrace();
159         }
160     }
161     
162     /**
163      * 测试方法.
164      * @param args
165      * @throws Exception
166      */
167     public static void main(String[] args) throws Exception {
168         //这里的IP是你本机的IP也就是syslog服务器的IP
169         String serverHost = "192.168.1.134";
170         int serverPort = 514;
171         UdpServerSocket udpServerSocket = new UdpServerSocket(serverPort);
172         while (true) {          
173             udpServerSocket.receive();
174             udpServerSocket.getResponseAddress();
175         }
176     }
177 }

接收TCP Syslog日志(直接使用Socket编程监听端口,得到原始字符串)

  1 import java.io.BufferedReader;
  2 import java.io.IOException;
  3 import java.io.InputStreamReader;
  4 import java.io.PrintWriter;
  5 import java.net.InetAddress;
  6 import java.net.InetSocketAddress;
  7 import java.net.ServerSocket;
  8 import java.net.Socket;
  9 import java.net.SocketAddress;
 10 import java.net.SocketException;
 11 
 12 public class TcpServerSocket {
 13     private byte[] buffer = new byte[1024];
 14     
 15     private ServerSocket serverSocket = new ServerSocket();
 16     
 17     private InetSocketAddress socketAddress = null;
 18     
 19     private Socket client;
 20     
 21     private PrintWriter socketOut;
 22         
 23     private String orgIp;
 24         
 25     /**
 26      * 构造函数,绑定主机和端口
 27      * @param host 主机
 28      * @param port 端口号
 29      * @throws SocketException 
 30      * @throws Exception
 31      */
 32     public TcpServerSocket(int port) throws IOException {
 33         socketAddress = new InetSocketAddress(port);
 34         serverSocket.bind(socketAddress);
 35 //        System.out.println("--------------tcp service start----------------");
 36     }
 37      
 38     
 39     public final String getOrgIp() {
 40         orgIp = client.getRemoteSocketAddress().toString();
 41         return orgIp.substring(1, orgIp.indexOf(":"));
 42     }
 43 
 44 
 45     /**
 46      * 接收数据包
 47      * @return 返回接收的数据串信息
 48      * @throws IOException
 49      */
 50     public final String receive() throws Exception {
 51         String info = new String();
 52         client = serverSocket.accept();
 53         socketOut = new PrintWriter(client.getOutputStream());
 54         if ( client.getInputStream().read(buffer) > 0 ) {
 55             int length = 0;
 56             for(;length < buffer.length; length++) {
 57                  if (buffer[length] == '\0')
 58                      break;
 59             }
 60             info = new String(buffer, 0 , length);
 61         }
 62         client.close();
 63         return info;
 64     }
 65 
 66 
 67     /**
 68      * 将响应包发送给请求端
 69      * @param info 回应报文
 70      * @throws IOException
 71      */
 72     public final void response(String info) throws IOException {
 73         socketOut.write(info);
 74     }
 75 
 76     /**
 77      * 关闭udp监听口
 78      */
 79     public final void close() {
 80         try {
 81             socketOut.flush();
 82             socketOut.close();
 83             serverSocket.close();
 84         } catch (Exception e) {
 85         }
 86     }
 87     
 88     /**
 89      * 测试方法.
 90      * @param args
 91      * @throws Exception
 92      */
 93     public static void main(String[] args) throws Exception {
 94         //TCP发包测试
 95         int num = 0;
 96         while (true) {
 97             final Socket socket = new Socket();
 98             SocketAddress address = new InetSocketAddress("192.168.1.132", 1468);
 99             socket.connect(address);
100             
101             PrintWriter socketOut = new PrintWriter(socket.getOutputStream());
102             BufferedReader socketIn = new BufferedReader( new InputStreamReader(socket.getInputStream()) );
103             
104             String sendStr = "This is message - " + num;
105             socketOut.write(sendStr);
106             socketOut.flush();
107             String receiveStr = socketIn.readLine();
108             System.out.println("Receive Message: " + receiveStr);
109             
110             socketOut.close();
111             socketIn.close();
112             socket.close();    
113             num++;
114             Thread.sleep(1000L);
115         }
116     }
117 }

利用正则表达式对Syslog日志进行解析

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 public class Test {
 7     
 8     public static void main(String[] args) {
 9         Map<Integer, String> Facility = new HashMap<Integer, String>(){
10             {
11                 put(0, "kernel messages");
12                 put(1, "user-level messages");
13                 put(2, "mail system");
14                 put(3, "system daemons");
15                 put(4, "security/authorization messages (note 1)");
16                 put(5, "messages generated internally by syslogd");
17                 put(6, "line printer subsystem");
18                 put(7, "network news subsystem");
19                 put(8, "UUCP subsystem");
20                 put(9, "clock daemon (note 2)");
21                 put(10, "security/authorization messages (note 1)");
22                 put(11, "FTP daemon");
23                 put(12, "NTP subsystem");
24                 put(13, "log audit (note 1)");
25                 put(14, "log alert (note 1)");
26                 put(15, "clock daemon (note 2)");
27                 put(16, "local use 0  (local0)");
28                 put(17, "local use 1  (local1)");
29                 put(18, "local use 2  (local2)");
30                 put(19, "local use 3  (local3)");
31                 put(20, "local use 4  (local4)");
32                 put(21, "local use 5  (local5)");
33                 put(22, "local use 6  (local6)");
34                 put(23, "local use 7  (local7)");            
35             }
36         };
37         
38         Map<Integer, String> Severity = new HashMap<Integer, String>(){
39             {
40                 put(0, "Emergency: system is unusable");
41                 put(1, "Alert: action must be taken immediately");
42                 put(2,"Critical: critical conditions");
43                 put(3, "Error: error conditions");
44                 put(4, "Warning: warning conditions"); 
45                 put(5, "Notice: normal but significant condition");
46                 put(6, "Informational: informational messages");
47                 put(7, "Debug: debug-level messages");
48             }     
49         };
50         
51         Map<String, String> syslogMap = new HashMap<String, String>();
52         String log = "<27>Sep 27 21:41:29 ka ntpd[2248]: bind(23) AF_INET6 fe80::216:31ff:fee7:f4a4%4#123 flags 0x11 failed: Cannot assign requested address\r\n" + 
53                 " ka rc.local[1698]: send noflow data:192.168.101.111;192.168.101.26;modbus;1;2020-09-27 21:40:42\r\n" + 
54                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.111;192.168.101.26;s7;1;2020-09-27 21:40:46\r\n" + 
55                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.26;192.168.101.111;s7;1;2020-09-27 21:40:46\r\n" + 
56                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.26;192.168.101.111;hj212;1;2020-09-27 21:40:46\r\n" + 
57                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.111;192.168.101.26;hj212;1;2020-09-27 21:40:46\r\n" + 
58                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.26;192.168.101.111;modbus;1;2020-09-27 21:40:46\r\n" + 
59                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.111;192.168.101.26;modbus;1;2020-09-27 21:40:46\r\n" + 
60                 "<30>Sep 27 21:41:12 ka rc.local[1698]: send noflow data:192.168.101.26;192.168.101.111;hj212;1;2020-09-27 ";
61         String[] logArray = log.split("<");
62         for(int i = 1; i < logArray.length; i++) {
63             String logString = "<" + logArray[i];
64             String pattern = "<(\\d+)>(\\w{3}\\s+\\d{1,2}\\s\\d\\d:\\d\\d:\\d\\d)\\s+([\\w-]+)\\s+([\\w-\\.\\]\\[]+):\\s(.*)";
65             Pattern r = Pattern.compile(pattern);
66             Matcher matcher = r.matcher(logString); 
67             if(matcher.find()) {
68                 Integer FS = Integer.parseInt(matcher.group(1));
69                 syslogMap.put("Facility", Facility.get(FS >> 8));
70                 syslogMap.put("Severity", Severity.get(FS & 7));
71                 syslogMap.put("Timestamp", matcher.group(2));
72                 syslogMap.put("Orgin",matcher.group(3));
73                 syslogMap.put("Tag", matcher.group(4));
74                 syslogMap.put("Message", matcher.group(5));
75             }
76             System.out.println(syslogMap);            
77         }
78     }
79 }

 

posted @ 2020-11-19 10:40  木子丘  Views(4077)  Comments(0Edit  收藏  举报