Repository navigation
Expand file tree
/
Copy pathbatch_async.py
More file actions
56 lines (43 loc) · 2.35 KB
/
Copy pathbatch_async.py
File metadata and controls
56 lines (43 loc) · 2.35 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
"""Analyze a list of URLs with AsyncClient, a few at a time, and print one
JSON line per URL as it finishes.
export URLQUERY_APIKEY=<API key>
python batch_async.py urls.txt --tag campaign_42 > results.ndjson
One URL per line; blank lines and # comments are skipped. New analyses are
restricted. When a wait gives up, the line has the queue and report IDs: the
URL is queued, so don't submit it again.
"""
from __future__ import annotations
import argparse
import asyncio
import json
from urlquery_api import APIError, AsyncClient, WaitError
async def analyze(client: AsyncClient, limit: asyncio.Semaphore, url: str, tags: list[str]) -> dict:
async with limit:
try:
s = await client.submit(url, access="restricted", tags=tags or None, wait=True)
except WaitError as e:
return {"url": url, "error": str(e), "queue_id": e.submission.queue_id,
"report_id": e.submission.report_id}
except APIError as e:
return {"url": url, "error": str(e), "code": e.code}
if s.status != "done":
return {"url": url, "status": s.status, "report_id": s.report_id}
o = await client.report_overview(s.report_id)
return {"url": url, "status": s.status, "report_id": s.report_id, "final": o.final.url.addr,
"title": o.final.title, "alerts": [a.alert for a in o.detection.urlquery], "tags": o.tags}
async def main() -> None:
parser = argparse.ArgumentParser(description="Analyze a list of URLs with urlquery.")
parser.add_argument("file", help="one URL per line")
parser.add_argument("--tag", action="append", default=[], help="a tag for every submission")
parser.add_argument("--parallel", type=int, default=4, help="analyses at the same time (default 4)")
args = parser.parse_args()
with open(args.file) as f:
urls = list(dict.fromkeys(line.strip() for line in f if line.strip() and not line.startswith("#")))
# The semaphore keeps a few analyses in flight; more would only wait on
# the API key's rate limits.
limit = asyncio.Semaphore(args.parallel)
async with AsyncClient(user_agent="urlquery-batch-example") as client:
for done in asyncio.as_completed([analyze(client, limit, url, args.tag) for url in urls]):
print(json.dumps(await done), flush=True)
if __name__ == "__main__":
asyncio.run(main())