-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathMongoUtils.py
157 lines (126 loc) · 4.41 KB
/
MongoUtils.py
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
#!/usr/bin/env python
#
# MongoUtils.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307 USA
import sys
import getopt
MONGO_MODULE = True
try:
import gridfs
import pymongo
from bson.objectid import ObjectId
except ImportError:
MONGO_MODULE = False
class MongoUtils(object):
def __init__(self, host="localhost", port=27017):
self.__check_mongo_module()
self.__init_db(host, port)
def __check_mongo_module(self):
if not MONGO_MODULE:
print("[MongoUtils] PyMongo not installed. Please install it and retry.")
sys.exit(0)
def __init_db(self, host, port):
# MongoDB Connection class is marked as deprecated (MongoDB >= 2.4).
# The following code tries to use the new MongoClient if available and
# reverts to the old Connection class if not. This code will hopefully
# disappear in the next future.
client = getattr(pymongo, "MongoClient", None)
if client is None:
client = getattr(pymongo, "Connection", None)
try:
connection = client(host, int(port))
except Exception:
print("[MongoUtils] MongoDB instance not available")
sys.exit(0)
db = connection.thug
dbfs = connection.thugfs
self.urls = db.urls
self.analyses = db.analyses
self.thugfs = gridfs.GridFS(dbfs)
self.collections = (
db.urls,
db.analyses,
db.locations,
db.connections,
db.graphs,
db.samples,
db.behaviors,
db.certificates,
db.honeyagent,
db.exploits,
db.codes,
db.json,
)
def list_analyses(self):
print("ID\t\t\t\t| URL\t\t\t\t| Analysis datetime\n")
for analysis in self.analyses.find():
urls = self.urls.find(_id=analysis["url_id"])
if not urls:
continue
url = urls[0]["url"]
print("%s\t| %s\t| %s" % (analysis["_id"], url, analysis["timestamp"]))
def remove_analysis(self, analysis):
analysis_id = analysis["_id"]
for collection in self.collections:
collection.remove({"_id": analysis_id})
self.thugfs.delete({"_id": analysis_id})
def query_analysis_by_id(self, analysis_id):
analysis = self.analyses.find_one({"_id": ObjectId(analysis_id)})
if not analysis:
print("[MongoUtils] Analysis ID not found")
return None
return analysis
def usage():
msg = """
Synopsis:
MongoUtils.py
Usage:
python MongoUtils.py [ options ]
Options:
-h, --help \tDisplay this help information
-l, --ls \tList all the analyses
-r, --rm= \tRemove the analysis identified by the specified ID
-M, --mongodb-address= \tSpecify address and port of the MongoDB instance (format: host:port)
"""
print(msg)
sys.exit(0)
def main(args):
host = "localhost"
port = 27017
try:
options, args = getopt.getopt(
args, "hlr:M:", ["help", "ls", "rm=", "mongodb-address="]
)
except getopt.GetoptError:
usage()
if not options and not args:
usage()
for option in options:
if option[0] in ("-h", "--help"):
usage()
elif option[0] in ("-M", "--mongodb-address"):
host, port = option[1].split(":")
mongoutils = MongoUtils(host, port)
for option in options:
if option[0] in ("-l", "--ls"):
mongoutils.list_analyses()
for option in options:
if option[0] in ("-r", "--rm"):
analysis = mongoutils.query_analysis_by_id(option[1])
if analysis:
mongoutils.remove_analysis(analysis)
if __name__ == "__main__":
main(sys.argv[1:])