-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfdns.py
More file actions
196 lines (174 loc) · 7.55 KB
/
fdns.py
File metadata and controls
196 lines (174 loc) · 7.55 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#coding: utf-8
import os
import sys
import requests
import shlex
import subprocess
import hashlib
import gzip
import json
import chardet
from datetime import datetime
from bs4 import BeautifulSoup
from elasticsearch import Elasticsearch, helpers
class Elastic(object):
def __init__(self, elastic=None, url='http://172.16.1.25:9090'):
self.elastic = elastic or Elasticsearch(url)
def exists(self, index):
return self.elastic.indices.exists(index)
def create(self, index, body=None):
self.elastic.indices.create(index, body=body, ignore=[400])
def insert(self, index, type, datas, id=None):
actions = []
for data in datas:
actions.append({
"_index": index,
"_type": type,
"_id": id,
"_source": data
})
try:
helpers.bulk(self.elastic, actions)
except Exception, e:
print ("{0} start bulk error: {1}".format(datetime.now(), e))
class Fdns(object):
def __init__(self):
self.website = "https://scans.io/study/sonar.fdns"
self.downurl, self.code = self.get_download_link()
def get_download_link(self):
resp = requests.get(self.website)
if resp.status_code != 200:
raise Exception("download page failed: %d" % resp.status_code)
soup = BeautifulSoup(resp.text, 'lxml')
try:
table = soup.findAll(name='table', attrs={'class':'table table-condensed'})[0]
tr = table.findAll(name='tr')[-1]
href = tr.findAll(name='a')[0]['href']
code = tr.findAll(name='code')[0].text
except Exception, msg:
raise Exception("get download link failed: {}".format(msg))
return (href, code.lower())
@staticmethod
def sha1(filepath, block_size=64*1024):
try:
with open(filepath, 'rb') as fd:
sha1obj = hashlib.sha1()
while True:
data = fd.read(block_size)
if not data:
break
sha1obj.update(data)
retsha1 = sha1obj.hexdigest()
return retsha1
except IOError:
raise Exception('Invalid file path: {}'.format(filepath))
@staticmethod
def make_dirs(dirpath, default='./sample'):
try:
if not os.path.exists(dirpath):
os.makedirs(dirpath)
return dirpath.rstrip(os.sep)
except Exception, e:
if not os.path.exists(default):
os.makedirs(default)
return dirpath.rstrip(os.sep)
@staticmethod
def download_file(downurl, localdir=None, showlog=False):
localdir = Fdns.make_dirs(localdir)
command_line = "wget -c -t100 -P {0} {1}".format(localdir, downurl)
tmp_cmdline = shlex.split(command_line)
try:
proc = subprocess.Popen(args=tmp_cmdline,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
bufsize=0)
except IOError:
raise EnvironmentError(1, "wget is not installed or could "
"not be found in system path")
while showlog and proc.poll() is None:
for streamline in iter(proc.stdout.readline, ''):
sys.stdout.write(streamline)
proc.communicate()
return proc.returncode
@staticmethod
def gzip_extract(gzpath, dstpath, block_size=64*1024):
try:
with gzip.open(gzpath, 'rb') as fr, open(dstpath, 'wb') as fw:
while True:
data = fr.read(block_size)
if not data:
break
fw.write(data)
except IOError:
raise Exception('Invalid file path: {}'.format(gzpath))
@staticmethod
def import_elastic(elastic, gzfile, step=500, sep=','):
with gzip.open(gzfile) as fd_file_down:
lines = []
type = 'json'
index = os.path.basename(gzfile)
elastic.create(index=index, body={
'mappings': {
'json': {
'properties' : {
'domain' : {
'type' : 'string',
'index': 'not_analyzed'
},
'record_type' : {
'type' : 'string',
'index': 'not_analyzed'
},
'record_value' : {
'type' : 'string',
'index': 'not_analyzed'
}
}
}
}
})
for line in fd_file_down:
success = False
if not success:
try:
fields = line.strip().split(sep)
data = dict(domain=fields[0], record_type=fields[1], record_value=fields[2])
lines.append(json.dumps(data))
success = True
except Exception:
pass
if not success:
try:
encoding = chardet.detect(line).get('encoding')
line = line.decode(encoding)
fields = line.strip().split(sep)
data = dict(domain=fields[0], record_type=fields[1], record_value=fields[2])
lines.append(json.dumps(data))
success = True
except Exception:
pass
if len(lines) >= step:
elastic.insert(index, type, lines)
lines[:] = []
if len(lines):
elastic.insert(index, type, lines)
def main():
fdns = Fdns()
localdir = "./sample"
downfilename = os.path.basename(fdns.downurl)
print ("{0} start download file: {1}".format(datetime.now(), downfilename))
while True:
returncode = fdns.download_file(fdns.downurl, localdir=localdir, showlog=False)
if returncode == 0:
break
print ("{0} start sha1 file: {1}".format(datetime.now(), downfilename))
downfilepath = localdir + os.path.sep + downfilename
if fdns.sha1(downfilepath) != fdns.code:
print "downfile failed: {}".format(fdns.downurl)
sys.exit()
print ("{0} start import file: {1}".format(datetime.now(), downfilename))
elastic = Elastic()
if not elastic.exists(downfilename):
fdns.import_elastic(elastic, downfilepath)
if __name__ == "__main__":
main()