shell script 分析ssh log並輸出為json檔

簡介

這個工具是透過,last和lastb這兩個指令,輸出並將其json化

  1. last:指令能輸出,成功登陸ssh的log檔
  2. lastb:指令能輸出,登陸ssh失敗的檔

流程

設定輸出目錄 => 利用cut和awk等工具整理輸出資料 => for迴圈建立array儲存資料 => 利用EFO和printf來輸出json

核心說明

cut -c 01-58 --complement 剪裁輸出的片段

awk '{if(length !=0) print $0}' 去除空白行

uniq -c 去除重覆行,並計算重覆次數

mktemp 創建亂數文件

完整程式碼

#!/bin/bash
######init setting
Local_Path=$(pwd)
Fasle_json_Path="${Local_Path}"'/output_Fasle.json'
Success_json_Path="${Local_Path}"'/output_Success.json'
success_log() {
    last -ad | cut -c 01-58 --complement | sort | awk '{if(length !=0) print $0}' | uniq -c | sort -n -r
}
false_log() {
    lastb -a | cut -c 01-60 --complement | sort | awk '{if(length !=0) print $0}' | uniq -c | sort -n -r
}
TMPFile=$(mktemp)
######output data to temp file
init() {
    unset VARS
    unset index
    unset IPV4
    unset Count
}
Log() {
    init

    $1 >${TMPFile}

    while read line; do
        VARS[$index]="$line"
        index=$(expr $index + 1)
    done <${TMPFile}

    for ((index = 0; index < ${#VARS[*]}; index++)); do
        Count[$index]=$(echo ${VARS[$index]} | cut -d " " -f 1)
        IPV4[$index]=$(echo ${VARS[$index]} | cut -d " " -f 2)
    done

    printf "{"
    printf "\""$2"\":["
    for ((i = 0; i < ${#IPV4[*]}; i++)); do
        cat <<EFO
        {
            "IP_Address" : "${IPV4[i]}",
            "times" : ${Count[i]},
            "status" : "$2"
        }
EFO
    if [ $i -lt $((${#IPV4[*]}-1)) ] ; then
        printf ","
    fi
    done
    printf "    ]"
    printf "}"

}

Log false_log false >${Fasle_json_Path}
Log success_log true >${Success_json_Path}

json輸出結果

{
"false":
    [       
        {
            "IP_Address" : "218.92.0.144",
            "times" : 3864,
            "status" : "false"
        },        
        {
            "IP_Address" : "59.36.144.188",
            "times" : 1092,
            "status" : "false"
        }
    ]
}

原始碼下載

點我下載

Last modification:December 8, 2019
If you think my article is useful to you, please feel free to appreciate