forked from VECERTUSA/Analyzer_forums
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvecert_forums.py
More file actions
434 lines (377 loc) · 15.7 KB
/
vecert_forums.py
File metadata and controls
434 lines (377 loc) · 15.7 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
VECERT.io
"""
import sys
import os
import re
import csv
import json
import urllib.parse
import urllib.request
from datetime import datetime
from typing import Any, Dict, List, Tuple
API_BASE = "https://vecertapi.com/api_analyzer"
MAX_PER_PAGE = 100
# ========== ANSI Colors ==========
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
FG = {
"cyan": "\033[36m",
"magenta": "\033[35m",
"yellow": "\033[33m",
"green": "\033[32m",
"red": "\033[31m",
"blue": "\033[34m",
"white": "\033[37m",
"grey": "\033[90m",
}
def c(text: str, *styles: str) -> str:
return "".join(styles) + text + RESET
# ========== Banner ==========
BANNER = r"""
──────────────────────────────────────────────────────
🛡️ V E C E R T 🛡️
─────────────────────────────────────
| Cyber Threat Intelligence Unit |
| Vigilance • Defense • Response |
─────────────────────────────────────
██╗ ██╗███████╗ ██████╗███████╗██████╗ ████████╗
██║ ██║██╔════╝██╔════╝██╔════╝██╔══██╗╚══██╔══╝
██║ ██║█████╗ ██║ █████╗ ██████╔╝ ██║
╚██╗ ██╔╝██╔══╝ ██║ ██╔══╝ ██╔══██╗ ██║
╚████╔╝ ███████╗╚██████╗███████╗██║ ██║ ██║
╚═══╝ ╚══════╝ ╚═════╝╚══════╝╚═╝ ╚═╝ ╚═╝
> website: https://vecert.io
> products: [email protected]
──────────────────────────────────────────────────────
"Monitoring the shadows of the net"
──────────────────────────────────────────────────────
"""
def print_banner():
print(c(BANNER, FG["cyan"], BOLD))
print(c("VECERT Forums Analyzer CLI", FG["magenta"], BOLD))
print(c("- VECERT API REST", FG["grey"]))
print()
# ========== HTTP / JSON ==========
def http_get_json(url: str, params: Dict[str, Any]) -> Dict[str, Any]:
q = {k: v for k, v in params.items() if v not in (None, "", [])}
qs = urllib.parse.urlencode(q, doseq=True)
full = f"{url}?{qs}" if qs else url
req = urllib.request.Request(
full,
headers={
"Accept": "application/json",
"User-Agent": "VECERT-CLI/2.1",
},
)
try:
with urllib.request.urlopen(req, timeout=20) as resp:
status = resp.getcode() or 200
data = resp.read()
if status < 200 or status >= 300:
raise RuntimeError(f"HTTP {status} from upstream")
try:
return json.loads(data.decode("utf-8"))
except json.JSONDecodeError:
raise RuntimeError("Invalid JSON from upstream")
except Exception as e:
raise RuntimeError(f"Request failed: {e}")
# ========== Table helpers ==========
def _stringify(x: Any) -> str:
if x is None:
return ""
return str(x)
def _col_widths(rows: List[List[str]]) -> List[int]:
widths = [0] * (len(rows[0]) if rows else 0)
for r in rows:
for i, cell in enumerate(r):
widths[i] = max(widths[i], len(cell))
return widths
def _draw_table(headers: List[str], rows: List[List[str]], header_color=FG["cyan"]) -> str:
"""Render a colored ASCII table with header and rows."""
all_rows = [headers] + rows if headers else rows
widths = _col_widths(all_rows)
def fmt_row(cols: List[str]) -> str:
return " " + " | ".join(cols[i].ljust(widths[i]) for i in range(len(cols))) + " "
sep = "-" + "-+-".join("-" * w for w in widths) + "-"
out = []
if headers:
out.append(c(fmt_row(headers), header_color, BOLD))
out.append(c(sep, FG["grey"]))
for idx, r in enumerate(rows):
style = FG["white"] if idx % 2 == 0 else FG["grey"]
out.append(c(fmt_row(r), style))
return "\n".join(out)
# ========== Printers ==========
def print_overview(data: Dict[str, Any]) -> None:
meta = data.get("meta", {})
total = meta.get("total", 0)
mode = meta.get("mode", "overview")
print(c("Mode: ", FG["grey"]) + c(mode, FG["yellow"], BOLD))
print(c("Total records: ", FG["grey"]) + c(f"{total:,}", FG["green"], BOLD))
print()
dist = data.get("distribution_by_source", [])
if isinstance(dist, list) and dist:
headers = ["Source", "Count", "Percentage"]
rows = []
for item in dist:
rows.append([
_stringify(item.get("source", "")),
f"{int(item.get('count', 0)):,}",
f"{float(item.get('percentage', 0.0)):.2f}%",
])
print(c("Distribution by Source", FG["magenta"], BOLD))
print(_draw_table(headers, rows))
print()
tops = data.get("top_10_authors", [])
if isinstance(tops, list) and tops:
headers = ["Author", "Posts"]
rows = []
for item in tops:
rows.append([
_stringify(item.get("author", "")),
f"{int(item.get('count', 0)):,}",
])
print(c("Top 10 Authors", FG["magenta"], BOLD))
print(_draw_table(headers, rows))
print()
def rows_from_data(data: Dict[str, Any]) -> List[List[str]]:
rows_data = data.get("data", [])
rows = []
for r in rows_data:
rows.append([
_stringify(r.get("title", "")),
_stringify(r.get("posted_date", "")),
_stringify(r.get("author", "")),
_stringify(r.get("source", "")),
_stringify(r.get("thread_url", "")),
])
return rows
def print_search(data: Dict[str, Any]) -> None:
meta = data.get("meta", {})
pagination = meta.get("pagination", {})
filters = meta.get("filters", {})
print(c("Mode: ", FG["grey"]) + c(meta.get("mode", "search"), FG["yellow"], BOLD))
clean_filters = {k: v for k, v in (filters or {}).items() if v not in (None, "", [])}
print(c("Filters: ", FG["grey"]) + c(str(clean_filters or {}), FG["cyan"]))
if pagination:
info = f"page {pagination.get('page', 1)}/{pagination.get('total_pages', 1)} • per_page={pagination.get('per_page', 25)} • total={pagination.get('total', 0)}"
print(c("Pagination: ", FG["grey"]) + c(info, FG["green"]))
print()
headers = ["Title", "Posted Date", "Author", "Source", "Thread URL"]
rows = []
for r in (data.get("data", []) or []):
rows.append([
_stringify(r.get("title", ""))[:80],
_stringify(r.get("posted_date", "")),
_stringify(r.get("author", ""))[:30],
_stringify(r.get("source", "")),
_stringify(r.get("thread_url", ""))[:80],
])
if rows:
print(_draw_table(headers, rows))
else:
print(c("(no results)", FG["red"]))
print()
# ========== Client state ==========
class QueryState:
def __init__(self):
self.title = ""
self.author = ""
self.posted_date = ""
self.page = 1
self.per_page = 25
# last response cache for export
self.last_meta: Dict[str, Any] = {}
self.last_rows_full: List[List[str]] = [] # current page rows (full values)
self.last_filters: Dict[str, Any] = {}
def any_filters(self) -> bool:
return any([self.title, self.author, self.posted_date])
def to_params(self) -> Dict[str, Any]:
return {
"title": self.title,
"author": self.author,
"posted_date": self.posted_date,
"page": max(1, self.page),
"per_page": max(1, min(MAX_PER_PAGE, self.per_page)),
}
def label_for_filename(self) -> str:
parts = []
if self.title: parts.append(f"title-{self.title}")
if self.author: parts.append(f"author-{self.author}")
if self.posted_date: parts.append(f"date-{self.posted_date}")
if not parts:
parts.append("overview")
label = "_".join(parts)
# sanitize to safe filename
label = re.sub(r"[^A-Za-z0-9._-]+", "_", label).strip("_").lower()
return label or "results"
# ========== Actions ==========
def show_overview():
print(c(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Fetching overview…", FG["grey"]))
data = http_get_json(API_BASE, {})
print_overview(data)
def run_query(state: QueryState):
params = state.to_params()
data = http_get_json(API_BASE, params if state.any_filters() else {})
# cache for export
state.last_meta = data.get("meta", {})
state.last_rows_full = rows_from_data(data) # untrimmed width
state.last_filters = (state.last_meta.get("filters") or state.to_params())
if state.any_filters():
print_search(data)
else:
print_overview(data)
def export_csv(state: QueryState):
if not state.any_filters():
print(c("You must run a search first (Title/Author/Posted Date). Overview cannot be exported.", FG["red"], BOLD))
return
if not state.last_rows_full and not state.last_meta:
print(c("No cached results. Run a search first.", FG["red"]))
return
# Ask export scope
print(c("Export options:", FG["yellow"], BOLD))
print(f" {c('1', FG['cyan'], BOLD)}) Current page only")
print(f" {c('2', FG['cyan'], BOLD)}) ALL pages for this query")
choice = input(c("Choose [1/2]: ", FG["white"], BOLD)).strip() or "1"
scope_all = (choice == "2")
# Confirm
print(c("Confirm export? [y/N]: ", FG["white"], BOLD), end="")
confirm = (input().strip().lower() in ("y", "yes"))
if not confirm:
print(c("Export cancelled.", FG["grey"]))
return
filename = f"vecert_{state.label_for_filename()}.csv"
rows_to_write: List[List[str]] = []
headers = ["Title", "Posted Date", "Author", "Source", "Thread URL"]
if not scope_all:
rows_to_write = state.last_rows_full
else:
# Fetch all pages
meta = state.last_meta or {}
pagination = meta.get("pagination", {})
total_pages = int(pagination.get("total_pages", 1)) or 1
# If we don't have pagination (e.g., API returned overview), re-run search to ensure
if not pagination:
print(c("No pagination info; re-running current query to get paginated data…", FG["grey"]))
_ = run_query(state)
# Start from page 1 to total_pages
params = state.to_params()
params["page"] = 1
rows_to_write = []
for p in range(1, total_pages + 1):
params["page"] = p
data = http_get_json(API_BASE, params)
page_rows = rows_from_data(data)
rows_to_write.extend(page_rows)
print(c(f"Fetched page {p}/{total_pages} ({len(page_rows)} rows)", FG["grey"]))
try:
with open(filename, "w", encoding="utf-8-sig", newline="") as f:
writer = csv.writer(f)
writer.writerow(headers)
writer.writerows(rows_to_write)
print(c(f"Exported {len(rows_to_write)} rows → {filename}", FG["green"], BOLD))
print(c(f"Location: {os.path.abspath(filename)}", FG["grey"]))
except Exception as e:
print(c(f"Failed to write CSV: {e}", FG["red"], BOLD))
# ========== Menu ==========
MENU = f"""
{c('Select an option:', FG['yellow'], BOLD)}
{c('1', FG['cyan'], BOLD)}) Search by {c('Title', FG['magenta'], BOLD)}
{c('2', FG['cyan'], BOLD)}) Search by {c('Author', FG['magenta'], BOLD)}
{c('3', FG['cyan'], BOLD)}) Search by {c('Posted Date', FG['magenta'], BOLD)} (YYYY-MM-DD or partial)
{c('4', FG['cyan'], BOLD)}) {c('Advanced', FG['magenta'], BOLD)} (combine filters)
{c('5', FG['cyan'], BOLD)}) Set {c('per_page', FG['magenta'], BOLD)} (max 100)
{c('6', FG['cyan'], BOLD)}) {c('Next page', FG['magenta'], BOLD)}
{c('7', FG['cyan'], BOLD)}) {c('Previous page', FG['magenta'], BOLD)}
{c('8', FG['cyan'], BOLD)}) Show {c('Overview', FG['magenta'], BOLD)}
{c('9', FG['cyan'], BOLD)}) Show {c('Current query', FG['magenta'], BOLD)}
{c('10', FG['cyan'], BOLD)}) {c('Export results to CSV', FG['magenta'], BOLD)}
{c('0', FG['cyan'], BOLD)}) {c('Exit', FG['red'], BOLD)}
"""
def prompt(msg: str) -> str:
return input(c(msg + " ", FG["white"], BOLD)).strip()
def menu_loop():
state = QueryState()
print_banner()
show_overview()
while True:
try:
print(MENU)
choice = prompt("Option")
print()
if choice == "0":
print(c("Bye.", FG["grey"]))
break
elif choice == "1":
state.title = prompt("Enter Title (substring)")
state.author = ""
state.posted_date = ""
state.page = 1
print()
run_query(state)
elif choice == "2":
state.author = prompt("Enter Author (substring)")
state.title = ""
state.posted_date = ""
state.page = 1
print()
run_query(state)
elif choice == "3":
state.posted_date = prompt("Enter Posted Date (YYYY-MM-DD or partial like 2024-07)")
state.title = ""
state.author = ""
state.page = 1
print()
run_query(state)
elif choice == "4":
state.title = prompt("Title (leave blank to skip)")
state.author = prompt("Author (leave blank to skip)")
state.posted_date = prompt("Posted Date (YYYY-MM-DD or partial, blank to skip)")
state.page = 1
print()
run_query(state)
elif choice == "5":
per = prompt(f"Per Page (1-{MAX_PER_PAGE})")
try:
per_int = int(per)
except ValueError:
per_int = state.per_page
state.per_page = max(1, min(MAX_PER_PAGE, per_int))
print(c(f"per_page set to {state.per_page}", FG["green"]))
print()
elif choice == "6":
state.page += 1
print(c(f"Moving to page {state.page}", FG["green"]))
print()
run_query(state)
elif choice == "7":
state.page = max(1, state.page - 1)
print(c(f"Moving to page {state.page}", FG["green"]))
print()
run_query(state)
elif choice == "8":
print()
show_overview()
elif choice == "9":
print(c("Current query:", FG["yellow"], BOLD))
print(c(str(state), FG["cyan"]))
print()
elif choice == "10":
export_csv(state)
print()
else:
print(c("Invalid option. Please choose 0-10.", FG["red"]))
print()
except (EOFError, KeyboardInterrupt):
print("\n" + c("Bye.", FG["grey"]))
break
except Exception as e:
print(c(f"Error: {e}", FG["red"]))
print()
# ========== Main ==========
if __name__ == "__main__":
menu_loop()