コマンドラインからアクセスログに Woothee を適用して分析


Woothee は User-Agent のパース・分類を行うライブラリです。
JavaScript, Java, Ruby, Perl, Python, PHP, Golang と、複数の実装が用意されており、共通のテストデータを使うことで同一の判定結果が保証されているのが特徴です。

Web エンジニアならコマンド上でちょっとしたアクセスログの分析を行うこともあると思いますが、バラバラな User-Agent に Woothee を適用して下処理ができれば捗るでしょう。

テスト用データの用意

こんな感じの LTSV ファイルを用意してみました。
自サイトから引っ張りだしたリアルなログです。
クローラーっぽいのだけに絞り込んで、一応ホストは除外しています。

まずは Woothee のインストール

今回は woothee-ruby を使いますが、他の言語でもだいたい似たようなことはできるでしょう。

$ gem i woothee --no-ri --no-rdoc

LTSV から User-Agent だけ抽出

LTSV なので awkcut の合わせ技だけで十分です。

$ awk -F "\t" '{ print $11 }' crawler.txt | cut -b4-
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)
Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)
Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)
Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Fastladder FeedFetcher/0.0.3 (http://fastladder.org/)
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

Woothee を適用

ruby-r オプションで woothee を読み込みつつワンライナーを実行します。
ここではクローラ名だけを抽出してみました。

$ awk -F "\t" '{ print $11 }' crawler.txt | cut -b4- | ruby -r woothee -ne 'puts Woothee.parse($_.chop)[:name]'
Googlebot
bingbot
Baiduspider
bingbot
bingbot
Googlebot
Googlebot
livedoor FeedFetcher
Googlebot
Googlebot

集計

sortuniq でランキング化してみましょう。

$ awk -F "\t" '{ print $11 }' crawler.txt | cut -b4- | ruby -r woothee -ne 'puts Woothee.parse($_.chop)[:name]' | sort | uniq -c | sort -nr
  95 Googlebot
  75 livedoor FeedFetcher
  45 Baiduspider
  44 bingbot
  21 Yahoo! Slurp
  18 Google Feedfetcher
  13 ahref AhrefsBot
  10 salesforce radian6
   7 Hatena
   5 Googlebot Mobile
   1 Google AppEngine

Google が多いですね。

それ jr でできるよ

拙作の、jq 風の JSON フィルタリングを Ruby で書けるツール、jr ならもっと簡単にできます。
--require オプションによるライブラリの読み込みに対応したので、Woothee など様々な Gem と組み合わせて使えるようになりました。
これまた拙作の ltsv2json と組み合わせて使います。
(ltsv2json と jr の組み合わせについては LTSV のログを jq でフィルタする もお読みください)

それでは jr をインストールしてみましょう。

$ gem i jr-cli --no-ri --no-rdoc

jr なら以下のようにできます。

$ ltsv2json crawler.txt | jr --require woothee 'map{|j| Woothee.parse(j[:ua])[:name] }' | sort | uniq -c | sort -nr
  95 "Googlebot"
  75 "livedoor FeedFetcher"
  45 "Baiduspider"
  44 "bingbot"
  21 "Yahoo! Slurp"
  18 "Google Feedfetcher"
  13 "ahref AhrefsBot"
  10 "salesforce radian6"
   7 "Hatena"
   5 "Googlebot Mobile"
   1 "Google AppEngine"

簡単ですね。