LoginSignup
1
0

Windowsのバッチファイル・Powershellの結果をSplunkに取り込む

Last updated at Posted at 2023-12-11

この記事はSplunk Advent Calendar 2023 11日目です。

SplunkのUniversal ForwarderはWindowsの場合、任意のバッチファイル(.bat)やPowershell(.ps1)の実行結果も取り込めます!という機能があって、実はこれすごいんじゃない?と最近個人的にブームだったのでメモです。

※この機能自体は大昔からあります

何ができるの?

要はWindowsのバッチファイル・Powershellで見られるものなら何でも取れるんですが、例えば:

  • Wifi接続状況の確認(netsh)
  • 接続監視、Web/APIコンテンツ取得(curl)
  • ドライブ利用状況(Powershell)
  • その他コマンドプロンプト経由で標準出力できる.exeの結果

その他にも色々あります。
そして、ChatGPTに聞いたらスクリプトの内容まで作ってくれるので、Windowsで取りたいものは何でも簡単に取ってSplunkで分析できると言っても過言ではありません。
便利な世の中になりました。

バッチファイル用inputs.conf

フォルダ構造

$SPLUNK_HOME\etc\app\配下に以下のように作成。

フォルダ構造
- <任意のadd-on名>
  - bin
    - <任意の名前>.bat
  - default
    - inputs.conf
  - local
    - inputs.conf

.batファイル

好きな.batファイルを作成します。

.batファイル例
@echo off
chcp 65001 >nul
echo name=%1, result="Hello %1!"

@echo off: コマンドの一行結果のみ出力する。
chcp 65001 >nul: utf8(英語)で出力する。>nulがなければ実行結果として「Active code page: 65001」と出力されてしまう。
※日本語がよければ不要だが、sourcetype側の文字コードはSJISにしておく。
echo name=%1, result="Hello %1!": 標準出力。%1は引数でinputs.confから渡す。Splunkで取り込んだ後のフィールド抽出はname=valueで自動抽出にお任せ。もっと複雑だったりしたらJSONにしても。(雑に取り込んでrexとかで抽出してもいいけど)

inputs.confファイル

こんな感じで作ります。

inputs.conf例
[script://.\bin\hello.bat Splunker]
interval = 60 
sourcetype = hello:bat
index = sandbox
disabled = 0

[script://.\bin\hello.bat Splunker]: 同一Add-onフォルダのbin内の「hello.bat」に引数「Splunker」を渡している。
interval = 60: 60秒おきに実行。cron式でも良い。
その他はいつもの。

実行結果

image.png

Powershell用inputs.conf

フォルダ構造

$SPLUNK_HOME\etc\app\配下に以下のように作成。バッチファイルの時と同じです。

フォルダ構造
- <任意のadd-on名>
  - bin
    - <任意の名前>.ps1
  - default
    - inputs.conf
  - local
    - inputs.conf

.ps1ファイル

好きなPowershell(.ps1)ファイルを作成します。

.ps1ファイル例
Param( [string]$Name )
Write-Output "name=$Name, result=`"Hello $Name!`""

Param( [string]$Name ): 「Name」というパラメーター名で文字列型の値を受け取る。
Write-Output "name=$Name, result="Hello $Name!"": Write-Hostで標準出力。

inputs.confファイル

こんな感じで作ります。

inputs.conf例
[powershell://hello_powershell]
script = ."$SplunkHome\etc\apps\hello_ps\bin\hello.ps1" -Name "Splunker"
schedule = 60
sourcetype = hello:ps1
index = sandbox
disabled = 0

[powershell://hello_powershell]: 任意のタイトル。バッチファイルと違い、ファイルパスではないので注意。
script = ."$SplunkHome\etc\apps\hello_ps\bin\hello.ps1" -Name "Splunker": script = [.(ピリオド)] [$SplunkHomeから始まるファイルパス]という独特な書式。ファイルパスではなく、直接Powershellスクリプトを書いても良い。
schedule = 60: 60秒おきに実行。cron式でも良い。バッチファイルの「interval」とは違うので注意。
その他はいつもの。

実行結果

image.png

備考

  • 詳しくはこちら

  • Powershellに関するログは特別にここにも出る。$SplunkHome\var\log\splunk\splunk-powershell.ps1.log

おまけ(ChatGPTがあればなんでもできる)

image.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0