Automating OSINT with Python: a practical starter guide
When automation helps in open-source research and when it only hides mistakes. A complete, small Python script that queries free APIs, keeps the raw responses with hashes and writes a tidy result, plus the habits that keep automated collection reliable and within the rules.
· 7 min read
Much of open-source research is repetition. Look up the registration date of a domain. Now do it for the other forty domains on the list. Check which of two hundred usernames exist on a site. Convert five hundred post IDs to timestamps. A person doing this by hand is slow and, by item thirty, careless.
A short script does it in seconds, the same way every time, and leaves a record. You do not need to be a software developer. You need a few dozen lines of Python and some discipline about what the script is allowed to do. This guide gives both.
When to automate
Automate | Do by hand |
|---|---|
The same lookup across many items | A single lookup |
Converting, cleaning and counting data | Reading and judging content |
Checks you will repeat weekly | A one-off question |
Queries to documented APIs | Anything behind a login wall |
Recording exactly what was retrieved and when | Deciding what it means |
Two warnings. Automation makes it easy to collect far more than you need, including personal data about people who are not your subject. And a script that silently fails on a third of its inputs produces a confident, wrong answer. Both problems are solved by design, covered below.
Setting up
Install Python from python.org, then create an isolated environment for the project so that its packages do not interfere with anything else:
python -m venv .venv
source .venv/bin/activate # on Windows: .venv\Scripts\activate
pip install requestsThe requests library handles web requests. For data work, pandas is the usual addition.
A complete example
This script takes a list of domains and, for each, retrieves registration dates from RDAP and host names from certificate transparency logs. Both sources are free and need no key. It saves every raw response to disk with a hash, and writes a summary file.
import csv
import hashlib
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
import requests
OUT = Path("output")
RAW = OUT / "raw"
RAW.mkdir(parents=True, exist_ok=True)
session = requests.Session()
session.headers["User-Agent"] = "research-script/1.0"
def fetch(name: str, url: str):
"""Get a URL, save the raw response with its hash, return parsed JSON or None."""
retrieved = datetime.now(timezone.utc).isoformat(timespec="seconds")
try:
response = session.get(url, timeout=30)
except requests.RequestException as error:
log(name, url, retrieved, "error", str(error), "")
return None
digest = hashlib.sha256(response.content).hexdigest()
(RAW / f"{name}.json").write_bytes(response.content)
log(name, url, retrieved, response.status_code, "", digest)
if response.status_code != 200:
return None
try:
return response.json()
except ValueError:
return None
def log(name, url, retrieved, status, error, digest):
with open(OUT / "log.csv", "a", newline="", encoding="utf-8") as handle:
csv.writer(handle).writerow([name, url, retrieved, status, error, digest])
def lookup(domain: str) -> dict:
result = {"domain": domain, "registered": None, "expires": None, "hostnames": [], "problems": []}
rdap = fetch(f"{domain}_rdap", f"https://rdap.org/domain/{domain}")
if rdap is None:
result["problems"].append("rdap failed")
else:
for event in rdap.get("events", []):
if event.get("eventAction") == "registration":
result["registered"] = event.get("eventDate")
if event.get("eventAction") == "expiration":
result["expires"] = event.get("eventDate")
time.sleep(2)
certs = fetch(f"{domain}_crtsh", f"https://crt.sh/?q={domain}&output=json")
if certs is None:
result["problems"].append("crt.sh failed")
else:
names = set()
for row in certs:
for value in row.get("name_value", "").splitlines():
names.add(value.strip().lower())
result["hostnames"] = sorted(names)
return result
if __name__ == "__main__":
domains = [line.strip() for line in open(sys.argv[1], encoding="utf-8") if line.strip()]
results = []
for domain in domains:
print("checking", domain)
results.append(lookup(domain))
time.sleep(2)
(OUT / "summary.json").write_text(json.dumps(results, indent=2), encoding="utf-8")
failed = [r["domain"] for r in results if r["problems"]]
print(f"done: {len(results)} domains, {len(failed)} with problems: {failed}")Save it as domains.py, put one domain per line in domains.txt, and run:
python domains.py domains.txtYou get output/summary.json with the results, output/raw/ with every response exactly as received, and output/log.csv recording each request, its time in UTC, its status and the SHA-256 hash of what came back. What the fields mean is covered in our guide to investigating a domain.
What the script does right
The example is short, but it shows the habits that matter more than any particular library.
It keeps the raw data
The summary is your interpretation. The raw response is the evidence. If you later find a bug in the parsing, or someone questions a result, you can go back to exactly what the source returned without asking it again, by which time the answer may have changed. Hashing at the moment of collection lets you show the files are unaltered. See preserving web evidence.
It records time in UTC
Every request is logged with a timestamp in UTC. Sources change, and "the registry said this at 14:02 UTC on this date" is a statement that can be defended.
It reports failures out loud
Each failed lookup is recorded in the result and counted at the end. The alternative, a script that skips errors, produces a list that looks complete and is not. A missing result must never be mistaken for a negative one. "No certificate found" and "the lookup timed out" are different facts.
It is slow on purpose
The pauses between requests keep it well under any reasonable limit. Free services are run on small budgets, and a script that hammers them gets your address blocked and spoils the service for others.
It identifies itself
A user agent that says what the script is, where a service's rules ask for it, is good manners and often a requirement. Use a generic project name. Do not put personal details in it unless the service specifically asks for a contact.
API keys and secrets
Many services need a key. Keep keys out of the code, so they are not shared or committed to a repository by accident. Put them in environment variables:
import os
API_KEY = os.environ["SERVICE_API_KEY"]Set the variable in your terminal session or in a local file excluded from version control. Search public code repositories for a few minutes and you will find thousands of keys that someone pasted into a script. See GitHub OSINT.
Remember that the service sees every query made with your key. What you look up is disclosed to it. See OPSEC for OSINT.
Useful free APIs to start with
Source | Gives | Guide |
|---|---|---|
RDAP | Domain and IP registration data | |
crt.sh | Certificates and host names | |
Wayback CDX | Archived addresses and dates | |
Shodan InternetDB | Open ports for an IP address | |
GitHub API | Profiles, repositories, events | |
Bluesky public API | Profiles, posts, identity history | |
mempool.space | Bitcoin addresses and transactions | |
NHTSA vPIC | VIN decoding |
Small conversions are worth scripting too. Several platforms encode creation times in their IDs, and one function per platform turns a column of IDs into a timeline.
Staying within the rules
Being able to request something does not mean being permitted to.
Prefer official APIs. They are documented, stable and come with stated limits.
Read the terms. Many platforms forbid automated collection outside their API. Breaching terms can cost you the account and, for organisations, lead to legal claims.
Never automate past a barrier. Logging in with scripts, defeating rate limits, rotating addresses to avoid blocks and solving challenges designed to stop bots all move from research towards unauthorised access.
Respect rate limits, and back off when a service returns an error asking you to slow down.
Minimise personal data. Collect the fields the question needs. A script that downloads every follower of every account in a network has created a database of personal data that you must now justify, secure and eventually delete.
Check
robots.txtas a statement of the site owner's wishes, even where it is not legally binding.
Our overview of whether OSINT is legal covers scraping and data protection in more detail.
Making scripts trustworthy
Test on known answers. Run the script on items where you already know the result. A parser that returns a wrong date for a domain you checked by hand is wrong for all the others too.
Spot-check the output. Verify a random handful of results manually every time.
Handle the unexpected. APIs return empty lists, error pages with success codes, and fields that are sometimes missing. Use
.get()with defaults, as the example does.Cache. Do not ask a source the same question twice in one project. Read the saved raw file.
Version your code. Note which version of the script produced which results.
Write down the method. The report should say what was run, against what, and when. See our OSINT report template.
Using AI to write scripts
Language models are good at producing small scripts like the one above, and at explaining error messages. Treat what they write as a draft from a fast, confident junior colleague.
Read every line before running it. Know what it sends and where.
Check the endpoints. Models invent API addresses, parameters and fields that look plausible and do not exist.
Test on known answers.
Keep case data out of prompts to services your organisation has not approved.
See AI in OSINT.
Where to go next
Schedule it. Run a check daily with the operating system's scheduler and compare with yesterday's output. This turns a one-off lookup into monitoring.
Compare and alert. Report only what changed.
Use
pandasto join, filter and count results. See detecting coordinated behaviour for an example.Parse HTML with a library such as BeautifulSoup when no API exists and the terms allow it.
Learn the command line. Tools such as
curlandjqdo a surprising amount without any Python.
Our roadmap for learning OSINT puts scripting in context with the other skills.
Frequently asked questions
Do I need to know programming to do OSINT?
No. Most research is done in a browser. Basic scripting becomes valuable when you repeat the same lookup many times or handle large amounts of data.
Why is Python used for OSINT?
It is readable, free, has libraries for web requests and data handling, and most open-source research tools are written in it.
Is it legal to automate OSINT collection?
Querying public APIs within their limits is generally fine. Scraping sites against their terms, or automating past logins and blocks, carries contractual and legal risk, and personal data collected at scale falls under data protection law.
Why should I save raw API responses?
Because the source may change or disappear, and because your parsing may contain errors. The raw response with a hash and timestamp is the evidence of what was returned.
Can I use AI to write OSINT scripts?
Yes, as a starting point. Review the code, verify that the endpoints and fields exist, and test it against cases where you know the correct answer.
