件名の通りです。対処方法をご教授いただけませんでしょうか?よろしくお願いいたします。
解決したい問題
%r(リクエストの最初の行)に「"」が含まれていても対応できる方法をご教授いただきたいです。
環境
- Windows10
- Spyder(Python 3.6)
サンプル
log
1 2hoge.fuga.com - - [04/Sep/2018:20:38:28 +0900] "GET /index.php?&q=type%3Apiyo" HTTP/1.1" 200 144155 "-" "-" 3
得たい結果
tsv
1 2hoge.fuga.com~-~-~04/Sep/2018:20:38:28 +0900~GET~/index.php?&q=type%3Apiyo~200~144155~-~- 3
現在の表示結果
txt
1#log 2123.hoge.jp - - [01/Sep/2018:02:00:03 +0900] "GET /index.php?&q=1 HTTP/1.1" 200 622 "https://www.hoge.com" "Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1" 3↓ 4#tsv 5123.hoge.jp~-~-~01/Sep/2018:02:00:03 +0900~GET~/index.php?&q=1~200~622~https://www.hoge.com~Mozilla/5.0~(iPhone;~CPU~iPhone~OS~11_4_1~like~Mac~OS~X)~AppleWebKit/605.1.15~(KHTML,~like~Gecko)~Version/11.0~Mobile/15E148~Safari/604.1" 6
分割ルール(取得したいテキスト)
- 全ての列の「"」はエスケープ
- %h(クライアントのホスト名)そのまま
- %l(リモートログ名)そのまま
- %u(Basic認証のユーザー名)そのまま
- %t(リクエスト時刻)[中身]の中身を取得[]は不要
- %r(リクエストの最初の行)HTTPメソッドとリクエストURL(スペースが含まれる場合にはエンコード)に分割、HTTP○○(HTTPS○○)は不要
- %>s(HTTPステータス)そのまま
- %b(レスポンスのバイト数)そのまま
- %{Referer}i(リファラ)そのまま(スペースはそのまま取得)
- %{User-Agent}i(ユーザーエージェント)そのまま(スペースはそのまま取得)
Apacheのログ
conf
1 2"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" 3
Pythonスクリプト
python
1 2import bz2 3import re 4import codecs 5 6def conv_line(l): 7 cols = l.split(' ') # まずは無条件で空白で分割する 8 dst = cols[:3] 9 dst += [cols[3].lstrip('[')+' '+cols[4].rstrip(']')] # 04/Sep/2018:20:38:28 +0900 10 dst += [cols[5].lstrip('"')] # GET 11 dst += [cols[6].rstrip('"')] # /index.php?&q=type%3Apiyo 12 dst += [col.strip('"') for col in cols[8:]] 13 return '~'.join(dst) 14 15fr = bz2.open(r'C:\Users\user\Desktop\bz2\access_log.bz2', 'rt') 16fw = codecs.open(r'C:\Users\user\Desktop\bz2\access_log.bz2.tsv', 'w', encoding='utf-8') 17 18line = fr.readline() 19line = line.replace('~', '') 20 21while line: 22 #リクエストの最初の行(リクエストURL)に「"」が含まれている場合ダメ 23 #fline = re.sub(r'^(\S+) (\S+) (\S+) [([^]]+)] "([A-Z]+) ([^ "]+)? (?:HTTP|HTTPS)/[0-9.]+" ([0-9]{3}) ([0-9]+|-) "([^\"]*)" "([^\"]*)"', r'\1~\2~\3~\4~\5~\6~\7~\8~\9~\10', line) 24 fline = conv_line(line) 25 check = re.search(r'/public/|/bot/|Googlebot|msnbot|bingbot|applebot|SemrushBot|AhrefsBot|MJ12bot|AdsBot|DotBot|istellabot|Twitterbot|YandexMobileBot|/bots|/bot.html|robots.txt', fline) 26 if check is None: 27 fw.write(fline) 28 line = fr.readline() 29 line = line.replace('~', '') 30fr.close() 31fw.close() 32 33
コピペ & 参考にさせていただいたページ
- PYTHONでAPACHEアクセスログをCSVファイルへ変換する方法
- Apacheのログ出力の要点
- [How to write UTF-8 in a CSV file
](https://stackoverflow.com/questions/18766955/how-to-write-utf-8-in-a-csv-file)
回答2件
あなたの回答
tips
プレビュー