うちのメインマシン(WindowsXP SP3)では、毎朝タスクでマシンを休止状態から自動復帰し、"eventquery.vbs"を組み込んだバッチファイルによりイベントログをバックアップ(日付毎に「application」「security」「system」のCSVファイルを作成)しています。
※"eventquery.vbs" とはWindowsXPに標準で準備されているイベントログ操作用のVBスクリプトで “%systemroot%\system32” にあります。
Ruby でも Windows イベントログが取れることを耳にしたので、試してみました。
以下にイベントログを取得して表示してみる手順を記録しておきます。
作業手順
前提条件
・作業OSは、WindowsXP SP3 です。
・使用したRubyは、Ruby-1.9.2-p290 です。
・試したイベントログは「system」です。
1.Gemsパッケージ「win32/eventlog」のインストール
コマンドプロンプトで以下のようにしてGemsパッケージ「win32/eventlog」をインストールします。
1
>gem install win32-eventlog
※win32-api, windows-api, windows-pr もインストールされます。
2.Gemsパッケージ「win32/eventlog」の一部修正
「win32/eventlog」をインストールしたデフォルトの状態では、"eventlog.rb"の14行目で
1
invalid byte sequence in US-ASCII (ArgumentError)
とエラーとなってしまいます。
そこで"eventlog.rb"の14行目の直前に以下のような記述を追加します。
1
2
3
4
5
6
7
8
9
10
class String
# Return the portion of the string up to the first NULL character. This
# was added for both speed and convenience.
def nstrip
if ! self . ascii_only?
self . force_encoding ( 'BINARY' )
end
self [ /^[^\0]*/ ] # <===以前の14行目
end
end
※参照サイト → RubyForge: Win32 Utils: トラッカー詳細: 28904 Gem win32-eventlog v0.5.2 on Ruby 1.9.1 and 1.9.2
3.テストコーディング
試しにイベントログを取得して表示するだけのスクリプトを作成してみます。
●ファイル名「get_event_log.rb」
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
require "win32/eventlog"
include Win32
handle = EventLog . open ( "system" )
total_rec = handle . total_records
oldest_rec_no = handle . oldest_record_number
puts "Total : #{ total_rec } , Oldest Record No. : #{ oldest_rec_no } "
puts "-" * 40
# 全件ループ
handle . read do | log |
puts "[ Record No. ] #{ log . record_number } "
puts "[ Type ] #{ log . event_type } "
puts "[ Event ] #{ log . event_id } "
puts "[ Date Time ] #{ log . time_written } "
puts "[ Source ] #{ log . source } "
puts "[ ComputerName ] #{ log . computer } "
puts "[ Category ] #{ log . category } "
puts "[ User ] #{ log . user } "
puts "[ Description ] #{ log . description } "
end
handle . close
4.実行
コマンドプロンプト等で作成したRubyスクリプトを実行してみます。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>ruby get_event_log.rb
Total : 5265, Oldest Record No. : 37224
----------------------------------------
[ Record No. ] 37224
[ Type ] warning
[ Event ] 4226
[ Date Time ] 2011-07-15 08:47:03 +0900
[ Source ] Tcpip
[ ComputerName ] P183
[ Category ] 0
[ User ]
[ Description ] TCP/IP で、同時 TCP 接続試行回数のセキュリティ制限値に達しました。
[ Record No. ] 37225
[ Type ] information
[ Event ] 7035
[ Date Time ] 2011-07-15 09:35:22 +0900
[ Source ] Service Control Manager
[ ComputerName ] P183
[ Category ] 0
[ User ] masaru
[ Description ] MySQL サービスは、正常に 開始 コントロールを送信しました。
----< 以下省略 >----
ちなみに、イベントビューアでの「ログファイルの名前を付けて保存」とか「すべてのイベントを消去」とかも可能です。
いずれは、現在当方が “eventquery.vbs” でCSV保存している処理を Ruby による処理に移行してみようかとも考えています。
以上。