Sending different data types and different ways to graylog server(part. 2)

 

5. 使用Graylog Collector sidecar收集 graylog server上的 log file資料 至 graylog GELF UDP input

Collector sidecar主要架構圖:

Graylog_Collector_Sidecar_—_Graylog_2_0_0_documentation

跟著http://docs.graylog.org/en/2.0/pages/collector_sidecar.html走 (windows 和 linux都有)

1) 安裝nxlog => 記得安裝完nxlog後,要先把nxlog service停下來,再改由graylog去控制nxlog

2) 安裝collector sidecar

3) 設定!!!(最麻煩的部分)

A. collector_sidecar.yml:

server_url: http://140.116.221.54:12900
node_id: graylog-collector-sidecar
collector_id: file:/etc/graylog/collector-sidecar/collector-id
tags:
    - linux
    - graylog
    - server
log_path: /var/log/graylog/collector-sidecar
update_interval: 10
log_rotation_time: 10
log_max_age: 10
backends:
    - name: nxlog
      enabled: true
      binary_path: /usr/bin/nxlog
      configuration_path: /etc/graylog/collector-sidecar/generated/nxlog.conf

– server_url要對到graylog server的port 12900,在System-> node-> REST API可看到該設多少

– node_id可隨意取,之後在graylog web抓到會顯示你這邊設定的node_id

– collector_id這個在安裝的時候,就會順便給,不需要動(除非安裝graylog collector的路徑有變更)

– tags 在graylog web會找你本地端這邊設定的tags 去對應到 web端設定的configurations的tags

– backends這邊我只試過nxlog來蒐集,在蒐集windows的log時,如果yml設定檔內有其他backend,就先都砍掉,只留nxlog

 

B. 上面設定完後,連接到graylog web介面-> System-> Collectors -> Manage configurations-> Create configuration->隨意取

– tag就填入剛剛在yml檔內設定的tags

– Configure Collector Outputs: 這邊所設定的Output,指的是 資料被蒐集的本地端所安裝的collector 要output到哪裡
當然是要output到graylog server的input囉,所以這邊設定完的output,別忘記也要到graylog web-> System-> Inputs去新增一個對應的input

– Configure Collector Inputs:
type有四種:
1| [NXLog] file input: 指的是 想被蒐集資料有安裝collector sidecar本地端的file
2| [NXLog] Windows Event log: Windows下的event log
3| [NXLog] UDP Syslog Listener: 還不是很懂QQ
4| [NXLog] TCP Syslog Listener: 還不是很懂QQ

Input的Forward to就是到上面所設定的Collector Outputs,也就是forward到graylog的input裡,
在collector這邊所設定的都會即時更新到 有安裝collector sidecar那端上,可以把web介面的collector設定想像成在本地端做設定的感覺,會比較好懂collector input和output

– Define Snippets

1| Backend目前好像只能選擇NXLog (?
2| Snippet就是寫上附加的資訊(外掛之類的訊息),會即時更新到 有安裝collector sidecar那端上
所以可以試試看在snippet加上 #hello 的字眼,然後到 有安裝collector sidecar那端上 查看collector_sidecar.yml檔有沒有被更改

 

設定完,”理論上”就會有資料上傳到graylog的input裡了

 

 

疑點解決:

如果設定完後,還是沒有資料進來怎麼辦?

1. 先檢查collector是否有成功安裝、連線:
Graylog_Web_Interface
這邊有出現,並且對應到正確的OS、collector id(可在collector-sidecar/collector-id內查看),就是有成功連線

在web collector頁面,按show message後沒有資料,就是configuration有出問題

 

2. 檢查兩端(web、有安裝sidecar那端)configuration的tags是否有相同對應:

兩端的tags一定要相同,有安裝sidecar那端的collector才抓得到configuration哦,
否則只是一個空的collector而沒有設定input和output,自然就不會有資料流動囉

*再真的沒有資料的話,可試試看把tags換掉

 

3. 檢查collector output是否有對應到graylog input的ip和port(重要)

graylog input的bind_address 和 collector output的server ip是要一樣的哦!!
port也要開同一個port,例如12210

 

4. 以上幾點都檢查完後,要檢查collector input是否有讀到,有一個最簡單的方法
在collecotor input設定一個[NXLog] file input,
path to logfile就設定隨便一個空的文件檔(e.g. hello.txt,自己創在桌面之類的)
設定完後,試著修改hello.txt,改完存檔後,再到collector按show message看是否有修改資料上傳

 

這邊有測試到一個情況是一個軟體把logfile都lock住,導致input讀不到,目前無解…

比較爛的方式就是複製出一份沒lock的,再上傳

對了! 在collector input的path to logfile的檔名可以設定用 XXX/*.log,就可以把XXX資料夾裡面的所有副檔名為log的都抓進去

How to set up graylog server on Ubuntu 14.04?

 

1. OpenSource 資料蒐集&分析平台比較:

https://www.evernote.com/l/AfBaqPuTRHBINLW7Fcafv2jffYx4WnTqau8

 

2. graylog簡介:
https://www.graylog.org/overview

 

3. 從零到架設

1) Java SE 8:
http://rongson.twbbs.org/wordpress/how-to-install-java-se-8-in-ubuntu-14-04/

2) MongoDB:
sudo apt-get update

sudo apt-get install mongod

* 檢查是否有執行: ps aux | grep mongod

3) ElasticSearch:
Ubuntu_installation_—_Graylog_2_0_0_documentation

* 檢查是否有執行: ps aux | grep elasticsearch

若沒有,就重開機:sudo reboot

4) Graylog:

檢查完前兩項mongodb, elasticsearch都有設定好且啟動後,再進行graylog安裝

Ubuntu_installation_—_Graylog_2_0_0_documentation

設定password_secret:`pwgen -N 1 -s 96` => 產生的亂碼複製到/etc/graylog/server/server.conf內的password_secret欄位

和root_password_sha2:echo -n yourpassword | shasum -a 256 =>  產生的亂碼複製到/etc/graylog/server/server.conf內的root_password_sha2欄位

 

*成功後,如何開啟graylog服務?

=> `sudo rm -f /etc/init/graylog-server.override`

=> `sudo start graylog-server`

*確認graylog server有否開啟服務?

=> ps aux | grep graylog

若沒有開啟,就是Java版本有問題,請更新到java se 8

Desktop_—_sinpao_graylog-server___etc_graylog_server_—_ssh_sinpao_140_116_221_54_-p_22_—_113×36

不能openjdk哦!

 

5) 設定graylog web interface:

看:http://docs.graylog.org/en/2.0/pages/configuration/web_interface.html#configuring-webif-nginx

一樣到/etc/graylog/server/server.conf裡修改參數即可(跟剛剛設定密碼一樣檔案)


1. web_enable =true

2. rest_listen_uri = http://YourServerIp:12900/  (不是127.0.0.1:12900)

3. web_listen_uri = http://YourServerIp:9000/   (不是127.0.0.1:9000)

4. web_enable_cors = false

5. web_enable_gzip = true

 

=> 設定完,即可用瀏覽器輸入 YourServerIp:9000 就進去囉

預設帳密是admin / admin

參考:

1. graylog doc – OS packages: http://docs.graylog.org/en/2.0/pages/installation/operating_system_packages.html

2. graylog doc – Ubuntu steps by steps: http://docs.graylog.org/en/2.0/pages/installation/os/ubuntu.html

 

Sending different data types and different ways to graylog server(part. 1)

1. 在terminal以curl指令傳送json格式單次封包 至GELP HTTP input

=> (port 設為 12202)

ex. curl -XPOST http://140.116.163.151:12202/gelf -d ‘{“short_message”:”trytryRS”}’

ex. curl -XPOST http://140.116.163.151:12202/gelf -d ‘{“short_message”:”trytryRS”, “host”:”rongson”, “facility”:”rongsons mac”, “_test”:”hello”}’

1Graylog_Web_Interface

 

2. 以tcp client傳送單次plaintext封包

=> (port 12203)

import java.io.*;
import java.net.*;

class TcpClient
{
    public static void main(String argv[]) throws Exception
    {
          String sentence;
          String modifiedSentence;
          BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
          Socket clientSocket = new Socket("140.116.163.151", 12203);
          DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
          BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
          System.out.print("Input: ");
          sentence = inFromUser.readLine();
          outToServer.writeBytes(sentence + '\n');
          System.out.println("OVER");
          //modifiedSentence = inFromServer.readLine();
          //System.out.println("FROM SERVER: " + modifiedSentence);
          clientSocket.close();
    }
}

tcp

Graylog_Web_Interface

 

3. udp client傳送單次plaintext封包

=> (port 12204)

import java.io.*;
import java.net.*;
 
// 1. 本程式必須與 UdpServer.java 程式搭配執行,先執行 UdpServer 再執行本程式。
// 2. 本程式必須有一個參數,指定伺服器的 IP。
// 用法範例: java UdpClient 127.0.0.1
 
public class udpClient extends Thread {
    int port;            // port : 連接埠
    InetAddress server; // InetAddress 是 IP, 此處的 server 指的是伺服器 IP
    String msg;            // 欲傳送的訊息,每個 UdpClient 只能傳送一個訊息。
 
    public static void main(String args[]) throws Exception {
        for (int i=0; i<100; i++) {
            // 建立 UdpClient,設定傳送對象與傳送訊息。
            udpClient client = new udpClient(args[0], 12204, "UdpClient : "+i+"th message");
            client.run(); // 啟動 UdpClient 開始傳送。
        }
    }
 
    public udpClient(String pServer, int pPort, String pMsg) throws Exception {
        port = pPort;                             // 設定連接埠
        server = InetAddress.getByName(pServer); // 將伺服器網址轉換為 IP。
        msg = pMsg;                                 // 設定傳送訊息。
    }
    public void run() {
      try {
        byte buffer[] = msg.getBytes();                 // 將訊息字串 msg 轉換為位元串。
        // 封裝該位元串成為封包 DatagramPacket,同時指定傳送對象。
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, server, port); 
        DatagramSocket socket = new DatagramSocket();    // 建立傳送的 UDP Socket。
        socket.send(packet);                             // 傳送
        socket.close();                                 // 關閉 UDP socket.
      } catch (Exception e) { e.printStackTrace(); }    // 若有錯誤產生,列印函數呼叫堆疊。
    }
}

Graylog_Web_Interface

 

4. 以Java TCPClient 寫入Json格式 傳送到 graylog GELF TCP input

import java.io.*;
import java.net.*;
import org.json.*;

class TcpClientJson
{
    private String host;
    private int port;
    private Socket socket;
    private final String DEFAULT_HOST = "localhost";


    public void connect(String host, int port) throws IOException {
        this.host = host;
        this.port = port;
        socket = new Socket(host, port);
        System.out.println("Client has been connected..");
    }

    public JSONObject receiveJSON() throws IOException {
        InputStream in = socket.getInputStream();
        ObjectInputStream i = new ObjectInputStream(in);
        JSONObject line = null;
        try {
            line = (JSONObject) i.readObject();

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
             e.printStackTrace();

        }
        return line;
    }
    public void sendJSON() throws IOException {
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("RS", "Hello Java Json");
        jsonObject2.put("host", "RS");
        jsonObject2.put("facility", "test");
        jsonObject2.put("_foo","bar");
        jsonObject2.put("short_message","hello");

        OutputStream out = socket.getOutputStream();
        DataOutputStream o = new DataOutputStream(out);        
        System.out.println("Hello sendJson");

        o.writeBytes(jsonObject2.toString()+'\0');
        System.out.println(jsonObject2.toString());

        out.flush();
        //System.out.println("Sent to server: " + " " + jsonObject2.get("key").toString());
    }

    public static void main(String argv[]) throws Exception
    {
      TcpClientJson client = new TcpClientJson();
        try{

            client.connect("140.116.221.54", 12299);
            // For JSON call sendJSON(JSON json) & receiveJSON();

            client.sendJSON();
            //client.receiveJSON();
        }
        catch (ConnectException e) {
            System.err.println(client.host + " connect refused");
            return;
        }

        catch(UnknownHostException e){
            System.err.println(client.host + " Unknown host");
            client.host = client.DEFAULT_HOST;
            return;
        }

        catch (NoRouteToHostException e) {
            System.err.println(client.host + " Unreachable");
            return;

        }

        catch (IllegalArgumentException e){
            System.err.println(client.host + " wrong port");
            return;
        }

        catch(IOException e){
            System.err.println(client.host + ' ' + e.getMessage());
            System.err.println(e);
        }
        finally {
            try {
                client.socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getUserString(){
        BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
        System.out.print("Input: ");
        String sentence="hello";
        try{
            sentence = inFromUser.readLine();
        }catch(IOException e){
            System.out.println(e);
        }
        return sentence;
    }
}

Graylog_Web_Interface

* 記得在java tcpclient端傳送前,要在結尾加入+’\0’,否則graylog gelf tcp input會收到流量,但不會顯示資料

參考:https://github.com/Graylog2/graylog2-server/issues/643

 

 

還有part.2
http://rongson.twbbs.org/wordpress/sending-differen…g-server(part-2)/

Using differant platforms and wordpress plugins to display codes

1. 試貼java: pastie
———–

2. 產生html原始碼:https://tohtml.com/java/


import java.util.Scanner;
import java.io.BufferedReader;

class Hello{
	private static String message;

	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.print("你素隨?: ");
		message = input.nextLine();
		String name= message;
		System.out.println("安捏! " + message + " 哩賀~~~~~");
		System.out.print(message +" 來跟大家說一句祝福的話吧: ");
		message = input.nextLine();
		System.out.println("yoyoyo, " + name + " 要跟大家說這些話,大家要認真聽哦!");
		System.out.println(": "+ message);
	}	
	
	public static void dosomething(){

	}
}

3. 換個, pastebin

4 . 再用個ideone

 

5. try內建外掛:Shortcodes Ultimate

 

6. try內建外掛:simple code highlighter

import java.util.Scanner;
import java.io.BufferedReader;

class Hello{
	private static String message;

	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.print("你素隨?: ");
		message = input.nextLine();
		String name= message;
		System.out.println("安捏! " + message + " 哩賀~~~~~");
		System.out.print(message +" 來跟大家說一句祝福的話吧: ");
		message = input.nextLine();
		System.out.println("yoyoyo, " + name + " 要跟大家說這些話,大家要認真聽哦!");
		System.out.println(": "+ message);
	}	
	
	public static void dosomething(){

	}
}

Learn about bash? shell? (二)

8. 環境變數?自訂變數?
– 自訂變數只能在當個process使用
ex. 我在終端機裡面設定
=> variable=”hello”
=> echo $variable
會跑出 hello
但是開了別的終端機時,echo $variable,就沒東西囉
ps. 即使在同一個終端機下,終端機的child process也讀取不到$variable
=> 利用export variable
能夠使同一個終端機下的child process也能使用$variable
但開啟別的終端機,還是無法使用$variable

有關環境變數問題集:
1. 到底有哪些變數是環境變數?
2. 自訂變數export後就是環境變數了嗎?
3. 如何讓自訂變數能夠永久存在?
4. PS1是環境變數嗎?

9.

Learn about bash? shell? (一)

1. 什麼是shell?
=> 

在system call之外的應用程式,都是shell(廣義)

2. 什麼是bash?
常聽到的 Bourne SHell (sh) 、在 Sun 裡頭預設的 C SHell、 商業上常用的 K SHell、, 還有 TCSH 等等,每一種 Shell 都各有其特點
-> Bourne Again SHell (簡稱 bash)

3. 為什麼要用bash?
優點:
1) 能查詢history(之前在資工系用的工作站就不支援查詢,每次指令都要重打,超煩XD)
=> less ~/.bash_history
裡面有之前輸入過的指令(被駭客取得root權限後,查看裡面就可能得知某某伺服器帳密)

2) tab補足指令或檔案名稱(完全是福音,使用沒有tab補足功能的shell會死掉哈哈)
tab按一下:補足指令或檔名
tab按兩下:顯示接下來有哪些選項是符合的

3) alias指令別名(可以把常使用的指令設成更簡單好懂好打的方式)
=> alias lm = ‘ls -al’

4) job control, background, foreground

5) shell script 程式化腳本(批次檔的感覺,把一連串的連續指令寫成script,之後只要執行script就不用一行一行keyin)

6) wildcard 萬用字元

4. 查詢某指令是否為bash shell內建命令
-> type [-tpa] command
ex. type -t ls

herongsendeMacBook-Air:~ RongSonHo$ type -t ls
file

顯示file -> 外部命令
顯示alias -> 別名
顯示builtin -> 內建命令
-p: 若command為外部命令時,會顯示完整檔案路徑

herongsendeMacBook-Air:~ RongSonHo$ type -p ls
/bin/ls

-a: 把$PATH中,含有command的指令都列出來
ex. type -a pwd

herongsendeMacBook-Air:~ RongSonHo$ type -a pwd
pwd is a shell builtin

pwd is /bin/pwd

ps. which指令,也有類似的功能哦

5. $PATH 環境變數在幹麻的?
=> 當我們在終端機輸入指令後,shell會到$PATH中的資料夾中尋找相對應的指令,若找不到指令就執行不了。

herongsendeMacBook-Air:~ RongSonHo$ echo $PATH
/Users/RongSonHo/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

6. 如何改變命令提示字元的預設顯示呢?
herongsendeMacBook-Air:~ RongSonHo$ 
改變PS1這個環境變數
我的PS1長這樣:

herongsendeMacBook-Air:~ RongSonHo$ echo $PS1
h:W u$



但直接修改PS1只會在當個tty改變

7. 如何永久改變PS1?
=> cd ~
=> ls -a
=> vim .bash_profile
=>

if which rbenv > /dev/null; then eval “$(rbenv init -)”; fi
export PS1='[就決定是你了,帥榮森! t: W ]$ ‘

參考:
1. 鳥哥:
http://linux.vbird.org/linux_basic/0320bash.php#ps2