[ctf4b 奈良 (2015)] curlで取ってきたhtmlから必要な情報をスクレイピング
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding: utf-8 | |
''' | |
ctf4b 奈良 (2015) | |
形式: Attack&Defense | |
チーム: 友利奈緒キャンプ | |
参加者名: 友利奈緒 | |
問題: Webアプリケーションの脆弱性を突いて顧客情報をcsv形式のテキストで提出する | |
脆弱性の場所: http://<ipaddr>/admin/customers/detail/<num> (?) | |
スクリプトの機能: curlで取ってきたhtmlから必要な情報をスクレイピング | |
''' | |
import sys | |
import re | |
def usage(): | |
print "HTMLから必要な情報を取って整形するやつ" | |
print "usage: python scrape.py <dirname>" | |
if len(sys.argv) != 2: | |
usage() | |
exit() | |
# note: htmlのforに付いていた名前 | |
fields = ["name", "kana", "email", "tel", "zip_code", "prefecture_id", "address"] | |
# note: ./a_and_d_web_nara/fuel/app/config/prefectures.php を参考にしてprefecture_idを推測 | |
prefs = ["---", "北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県", "茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県", "新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県", "徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"] | |
csv = "" | |
for i in xrange(1,100 + 1): # note: range()の終わり番号に注意(取りこぼしの原因) | |
text = open(sys.argv[1] + "/" + str(i)).read() | |
csv = "" | |
for x in fields: | |
#--- templete: 部分抽出 --- | |
# forじゃなくてlabelの中身でスイッチすればよかった。label[for=email]が2つある | |
if x != "email": | |
REGEXP = "for=\"" + x + "\">\S+<\/label>\n\s+(\S+(\s\S+)*)\s+<\/fieldset>" | |
else: | |
REGEXP = "メールアドレス:<\/label>\n\s+(\S+(\s\S+)*)\s+<\/fieldset>" | |
pattern = re.compile(REGEXP) | |
m = pattern.search(text) | |
# print m.group(1) | |
data = m.group(1) | |
#------------------------ | |
if m == None: | |
print x + "の正規表現を見なおそう!" | |
print "[info] i = " + str(i) | |
exit() | |
#--- templete: 前処理 --- | |
if x == "prefecture_id": | |
# note: MySQLでAUTO_INCREMENTで採番している場合、1始まりとなる | |
data = str(prefs.index(data) + 1) | |
#---------------------- | |
#--- teplete: 整形 --- | |
csv += data + "," | |
#-------------------- | |
#--- templete: 後処理 --- | |
# print str(i) + ": " + csv[:-1] | |
print csv[:-1] | |
#---------------------- | |
''' | |
コーディングメモ | |
現地ではREGEXPをまともに書けなくて何の情報も取れなかった | |
onlineのregexp testerでチェックしながら正規表現を作ればよかった(反省) | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment