Build a Hidden Camera Checker
Build a read-only tool to inventory authorized networks and Bluetooth signals.
Introduction
30 Second Summary
An unfamiliar charger, clock, or smoke alarm can make a private room feel uncertain. A careful check needs evidence that helps you investigate without turning ordinary devices into accusations.
In this project, you will use Claude Code to build a local Python checker that records devices observed on an authorized home network. The checker also listens for Bluetooth LE advertisements in two locations before creating an evidence report that separates observation from interpretation.
What You'll Build
You'll open camera-report.md and see each observed device, candidate clue, repeated Bluetooth identifier, and blind spot presented without turning suspicion into proof.
By the end of this project, you'll have:
- Run a read-only home inventory where IEEE Registration Authority data appears beside targeted port results for camera-like candidates.
- Record two Bluetooth LE listening windows without pairing, connecting, or reading device data.
- Open a defensible evidence report that separates facts, candidates, unknowns, blind spots, and the result of an owned-device test.
- Secret Mission: Turn the checker into a permission-first travel-room checklist with a flashlight sweep plus a safe stop-and-report response.
Are there any prerequisites?
You'll need a Mac running macOS 13 or later or a Windows 11 laptop with administrator credentials.
Bluetooth hardware, an owned or authorized home network, and an owned test device complete the prerequisites.
Before We Start
This first checkpoint captures the private home network you are authorized to assess. It also records your commitment to scan only approved devices and keep observations separate from conclusions.
Set Up Claude Code and the Safety Lab
Your checker will eventually observe devices on your authorized home network. It will also listen for nearby Bluetooth LE advertisements.
This step creates a verified workspace with Claude Code. Python will isolate the checker in a virtual environment.
Nmap will handle later host discovery from that workspace. Bleak will support later Bluetooth LE listening.
In this step, get ready to:
- Subscribe to Claude Pro and sign in to Claude Code.
- Install Python 3.15.2 plus Nmap 7.993.
- Create the hidden-camera-checker environment with Bleak 3.1.0.
Get Claude Code access
Claude Code needs an eligible Claude account before the terminal tool can start an authenticated session. Claude Pro provides that access for this project.
Claude Pro is recurring
This is the only paid part of the setup. Claude Pro costs $20 if billed monthly before applicable tax.
The subscription renews until you cancel it. The rest of the project uses free local tools.
- Open the official Claude pricing page.
- Purchase one month of Claude Pro.
macOS
- Press Cmd + Space to open Spotlight.
- Type Terminal and press Enter.
- Install Claude Code by running this command:
curl -fsSL https://claude.ai/install.sh | bash
What does this command do?
The command downloads the official Claude Code installer over HTTPS. It runs the installer in your current shell.
- Start Claude Code by running this command:
claude
What happens next?
Claude Code starts an interactive terminal session. Your browser opens so you can authenticate with the Claude account that has your Pro subscription.
- Complete the browser sign-in with your Claude Pro account.
- Return to Terminal after Claude Code confirms the session is ready.
- Leave the interactive session by entering:
/exit
Why exit now?
The exit command returns you to the normal terminal prompt. Your authenticated Claude Code access remains available for the project.
- Confirm Claude Code is available by running:
claude --version
What should I see?
Claude Code prints its installed version. This confirms the command is available through your terminal.
Claude command unavailable?
Close Terminal after the installer finishes. Open it again so the shell reloads its command path.
If the installation download failed, check your internet connection before rerunning the official installer command.
Ask for help with your Mac installation issue.
Windows
- Press Win + X to open the system menu.
- Select Windows PowerShell or Terminal.
- Confirm the prompt begins with PS.
- Install Claude Code by running this command:
irm https://claude.ai/install.ps1 | iex
What does this command do?
The command downloads the official Claude Code PowerShell installer. PowerShell runs the downloaded installation script.
- Start Claude Code by running this command:
claude
What happens next?
Claude Code starts an interactive terminal session. Your browser opens so you can authenticate with the Claude account that has your Pro subscription.
- Complete the browser sign-in with your Claude Pro account.
- Return to PowerShell after Claude Code confirms the session is ready.
- Leave the interactive session by entering:
/exit
Why exit now?
The exit command returns you to the normal PowerShell prompt. Your authenticated Claude Code access remains available for the project.
- Confirm Claude Code is available by running:
claude --version
What should I see?
Claude Code prints its installed version. This confirms the command is available through PowerShell.
Claude command unavailable?
Close PowerShell after the installer finishes. Open it again so the shell reloads its command path.
If the installation download failed, check your internet connection before rerunning the official installer command.
Ask for help with your Windows installation issue.
Claude Code is now installed and authenticated. You have the assistant that will help build the checker in the next step.
Install Python and Nmap
The project uses pinned tool versions so your environment matches the commands in this walkthrough. Check your current state before choosing an installation path.
macOS
- Return to Terminal from the previous substep.
- Check for Python plus Nmap by running:
python3.15 -VV
nmap
What do these checks show?
The Python command prints the interpreter version plus build details. The Nmap command prints its usage screen when the tool is available.
Windows
- Return to PowerShell from the previous substep.
- Check for Python plus Nmap by running:
python --version
nmap
What do these checks show?
The Python command prints the interpreter version. The Nmap command prints its usage screen when the tool is available.
✔️ I see Python 3.15.2 and Nmap 7.993
Both pinned tools are already available on your command path.
- Continue to the project environment substep.
ⓧ I see an older version
An older tool version can produce different setup behavior. Install the pinned releases before creating the project environment.
macOS
- Open the official Python release page for version 3.15.2.
- Download the macOS installer.
- Run the downloaded Python installer.
The certificate step is easy to miss because it runs after the main Python installer closes.
- Run Install Certificates.command from the installed Python folder.
You should see messages confirming that certificates were installed and updated.
An administrator prompt is expected during the Nmap installation because the package adds a system command.
- Open the official Nmap download page.
- Download nmap-7.993.dmg.
- Run the Nmap package from the downloaded disk image.
- Approve the installation with your administrator credentials when prompted.
- Verify the new installations by running:
python3.15 -VV
nmap
What should I see?
Python reports version 3.15.2. Nmap prints the 7.993 usage screen.
Windows
- Open the official Python release page for version 3.15.2.
- Download the recommended Windows 64-bit installer.
- Run the downloaded Python installer with the recommended settings.
A Windows security prompt is expected because these installers add software to your laptop.
- Open the official Nmap download page.
- Download nmap-7.993-setup.exe.
- Run the Nmap installer.
- Keep Npcap selected in the installer.
- Approve the installation when Windows asks for permission.
- Close PowerShell after both installations finish.
- Open a new PowerShell window through the Win + X menu.
- Verify the new installations by running:
python --version
nmap
What should I see?
Python reports Python 3.15.2. Nmap prints the 7.993 usage screen.
ⓧ One or both commands are missing
Your laptop needs the official installers before it can create the project environment.
macOS
- Open the official Python release page for version 3.15.2.
- Download the macOS installer.
- Run the downloaded Python installer.
The certificate step is easy to miss because it runs after the main Python installer closes.
- Run Install Certificates.command from the installed Python folder.
You should see messages confirming that certificates were installed and updated.
An administrator prompt is expected during the Nmap installation because the package adds a system command.
- Open the official Nmap download page.
- Download nmap-7.993.dmg.
- Run the Nmap package from the downloaded disk image.
- Approve the installation with your administrator credentials when prompted.
- Verify the installations by running:
python3.15 -VV
nmap
What should I see?
Python reports version 3.15.2. Nmap prints the 7.993 usage screen.
Windows
- Open the official Python release page for version 3.15.2.
- Download the recommended Windows 64-bit installer.
- Run the downloaded Python installer with the recommended settings.
A Windows security prompt is expected because these installers add software to your laptop.
- Open the official Nmap download page.
- Download nmap-7.993-setup.exe.
- Run the Nmap installer.
- Keep Npcap selected in the installer.
- Approve the installation when Windows asks for permission.
- Close PowerShell after both installations finish.
- Open a new PowerShell window through the Win + X menu.
- Verify the installations by running:
python --version
nmap
What should I see?
Python reports Python 3.15.2. Nmap prints the 7.993 usage screen.
Still missing a tool?
Close your current terminal after the installers finish. A new terminal reloads the command path used to find Python and Nmap.
On Windows, rerun the official Python installer if the Python command remains unavailable. Enable the installer's option that adds Python to your command path.
Ask for help with the missing command.
Create the project environment and verify it
The virtual environment keeps this project's Python packages separate from other projects. Its activation also makes the python command point to the project interpreter.
macOS
- Move to your Desktop by running this command:
cd ~/Desktop
Why start on the Desktop?
This gives the project a predictable location. You can find the folder later without searching through your home directory.
- Create the hidden-camera-checker folder by running these commands:
mkdir hidden-camera-checker
cd hidden-camera-checker
What do these commands do?
- The first command creates the project folder on your Desktop.
- The second command moves your terminal into that folder.
- Open the Desktop folder in Finder.
You should see the new hidden-camera-checker folder.
- Create the virtual environment by running these commands:
python3 -m venv .venv
source .venv/bin/activate
What do these commands do?
Python creates an isolated environment inside .venv. The activation command switches the current terminal to that environment.
Your terminal prompt now shows that the virtual environment is active.
Windows
- Move to your Desktop by running this command:
Set-Location -Path "$HOME\Desktop"
Why start on the Desktop?
This gives the project a predictable location. You can find the folder later without searching through your user directory.
- Create the hidden-camera-checker folder by running these commands:
mkdir hidden-camera-checker
cd hidden-camera-checker
What do these commands do?
- The first command creates the project folder on your Desktop.
- The second command moves PowerShell into that folder.
- Open the Desktop folder in File Explorer.
You should see the new hidden-camera-checker folder.
- Create the virtual environment by running these commands:
python -m venv .venv
.venv\Scripts\Activate.ps1
What do these commands do?
Python creates an isolated environment inside .venv. The activation script switches the current PowerShell session to that environment.
Your PowerShell prompt now shows that the virtual environment is active.
PowerShell blocks activation?
PowerShell can block local activation scripts under its current execution policy. Allow locally created scripts for your Windows account by running:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
This changes the policy for your user account. Retry the activation command after PowerShell accepts the change.
Ask for help with virtual environment activation.
Your activated environment is ready for one dependency file. Claude Code will create that file inside hidden-camera-checker.
- Start Claude Code from the activated project terminal by running:
claude
Why start Claude Code here?
Claude Code uses the current folder as its project context. Starting it here keeps the new file inside hidden-camera-checker.
- Prepare to approve a file edit if Claude Code asks for permission.
- Create the dependency file by pasting this prompt:
Create a requirements.txt file in the current hidden-camera-checker folder.
Put exactly this single line in the file: bleak==3.1.0
What does this file do?
The requirements.txt file records the exact Bleak release used by the project. The pin keeps future installations on version 3.1.0.
Claude Code confirms that requirements.txt was created in the project folder.
- Return to the activated terminal by entering:
/exit
What stays active?
Claude Code closes its interactive session. The virtual environment remains active in the underlying terminal.
- Use these tabs to confirm the complete requirements.txt file.
✔️ Awesome, I've got everything!
Good progress. Your dependency file now pins the Bleak version used throughout the project.
ⓧ I'd like to double check the full code
bleak==3.1.0
- Install Bleak into the active virtual environment by running:
python -m pip install bleak==3.1.0
What does this command do?
The command uses the active environment's Python interpreter to install Bleak. The version pin selects release 3.1.0.
The installation output confirms that Bleak 3.1.0 is available inside .venv.
Bleak installation failed?
Confirm that your terminal still shows the virtual environment indicator. Activate .venv again if the indicator is missing.
A download failure can also come from a disconnected network. Restore the connection before rerunning the same installation command.
Ask for help with the Bleak installation.
Before you run the final checks, which three success signals do you expect your terminal to show?
- Verify Claude Code, Python, plus Nmap by running:
claude --version
python --version
nmap
What should I see?
Claude Code prints an installed version. Python prints Python 3.15.2.
Nmap prints its 7.993 usage screen. With no target supplied, this command performs no network scan.
That's the foundation in place. Your authenticated assistant plus pinned local toolchain are ready without collecting any network or Bluetooth observations.
Your safety lab is verified. Next, you will use it to build the first read-only inventory of devices observed on your authorized home network.
Build a Raw Home Inventory
Your safety lab is ready. Now the checker needs a factual baseline of devices that your laptop can observe on your authorized home network.
This first slice uses Claude Code to build a Python checker around Nmap host discovery. It records IP addresses, hostnames, and MAC addresses without running a port scan.
In this step, get ready to:
- Create the network-only version of camera_checker.py.
- Identify the authorized private home network that the checker may observe.
- Run the checker to create a raw network.json inventory.
Create the network-only checker
The first version needs a strict safety boundary before it performs ARP discovery. It accepts only a private IPv4 network containing no more than 256 addresses.
- Return to the activated terminal in your hidden-camera-checker folder.
- Start Claude Code in the current folder by running this command:
claude
What does this command do?
The claude command starts an interactive Claude Code session with access to the current project folder. Claude Code can create camera_checker.py after you approve its file-edit request.
- Ask Claude Code to create camera_checker.py using the network-only code shown in the double-check tab below.
- Require the checker to accept only private IPv4 networks containing no more than 256 addresses.
- Require the checker to ask for OWN before discovery begins.
- Require discovery to use the Nmap arguments -sn, -PR, and -oX -.
- Require the checker to save only the observed IP address, hostname, and MAC address for each device.
- Tell Claude Code to create the file without running a network observation.
- Approve the file edit when Claude Code asks for permission.
Why use this discovery method?
The -sn option performs host discovery without a following port scan. The -PR option uses ARP discovery for targets on the local Ethernet network.
The -oX - option returns XML through standard output. Python can parse that structured result consistently on macOS and Windows.
✔️ Awesome, I've got everything!
Great. Double-check that Claude Code saved camera_checker.py in the hidden-camera-checker folder.
ⓧ I'd like to double check the full code
Compare your network-only file with this cumulative version.
from __future__ import annotations
import argparse
import ipaddress
import json
import os
import platform
import shutil
import subprocess
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def save_json(path: str | Path, payload: dict) -> None:
Path(path).write_text(
json.dumps(payload, indent=2, ensure_ascii=False),
encoding="utf-8",
)
def private_network(value: str) -> ipaddress.IPv4Network:
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError as error:
raise ValueError(f"Invalid CIDR: {value}") from error
if not isinstance(network, ipaddress.IPv4Network):
raise ValueError("This beginner project supports private IPv4 networks only.")
if not network.is_private:
raise ValueError("Refusing to scan a non-private network.")
if network.num_addresses > 256:
raise ValueError("Refusing a network larger than 256 addresses.")
return network
def confirm_authorization(network: ipaddress.IPv4Network) -> None:
print(f"Target: {network}")
print("Continue only if you own this network or have explicit permission.")
answer = input("Type OWN to continue: ").strip()
if answer != "OWN":
raise RuntimeError("Authorization confirmation was not provided.")
def nmap_command(arguments: list[str]) -> list[str]:
if not shutil.which("nmap"):
raise RuntimeError("Nmap was not found on PATH.")
command = ["nmap", *arguments]
if platform.system() == "Darwin" and hasattr(os, "geteuid"):
if os.geteuid() != 0:
command.insert(0, "sudo")
return command
def run_nmap(arguments: list[str]) -> ET.Element:
command = nmap_command(arguments)
completed = subprocess.run(
command,
capture_output=True,
text=True,
timeout=180,
check=False,
)
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip()
raise RuntimeError(f"Nmap failed: {detail}")
try:
return ET.fromstring(completed.stdout)
except ET.ParseError as error:
raise RuntimeError("Nmap did not return valid XML output.") from error
def host_name(host: ET.Element) -> str | None:
hostname = host.find("./hostnames/hostname")
if hostname is None:
return None
return hostname.attrib.get("name")
def parse_discovery(root: ET.Element) -> list[dict]:
devices: list[dict] = []
for host in root.findall("host"):
status = host.find("status")
if status is None or status.attrib.get("state") != "up":
continue
ipv4 = None
mac = None
for address in host.findall("address"):
if address.attrib.get("addrtype") == "ipv4":
ipv4 = address.attrib.get("addr")
elif address.attrib.get("addrtype") == "mac":
mac = address.attrib.get("addr")
if ipv4:
devices.append(
{
"ip": ipv4,
"hostname": host_name(host),
"mac": mac,
}
)
return devices
def print_network_table(devices: list[dict]) -> None:
print("\nObserved devices")
for device in devices:
print(
f"{device['ip']:<17} "
f"{(device.get('hostname') or '-')[:24]:<24} "
)
def run_network(args: argparse.Namespace) -> None:
network = private_network(args.subnet)
confirm_authorization(network)
discovery_xml = run_nmap(["-sn", "-PR", "-oX", "-", str(network)])
devices = parse_discovery(discovery_xml)
devices.sort(key=lambda item: ipaddress.ip_address(item["ip"]))
payload = {
"created_at": utc_now(),
"scope": str(network),
"authorization_confirmed": True,
"observation_wording": "Devices observed during this run; not every device.",
"devices": devices,
}
save_json(args.output, payload)
print_network_table(devices)
print(f"\nSaved {args.output}")
def parser() -> argparse.ArgumentParser:
main_parser = argparse.ArgumentParser(
)
subparsers = main_parser.add_subparsers(dest="command", required=True)
network_parser = subparsers.add_parser("network")
network_parser.add_argument("--subnet", required=True)
network_parser.add_argument("--output", default="network.json")
network_parser.set_defaults(function=run_network)
return main_parser
def main() -> int:
try:
args = parser().parse_args()
args.function(args)
return 0
except KeyboardInterrupt:
print("Stopped by user.", file=sys.stderr)
return 130
except Exception as error:
print(f"Error: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
Does the file differ?
Ask Claude Code to compare camera_checker.py with the double-check version. Keep this step limited to private-network validation, authorization, host discovery, XML parsing, table output, and JSON saving.
If the file still differs, use help me align my network-only file.
Confirm the authorized network scope
A CIDR describes a block of IP addresses with one value. The checker needs the active private IPv4 CIDR for the home network you own or have permission to observe.
- Ask Claude Code to inspect read-only operating-system network information for the active private IPv4 CIDR.
- Ask Claude Code to explain the proposed CIDR in plain English.
- Ask Claude Code to state how many addresses the proposed CIDR contains.
- Confirm that the proposed CIDR belongs to your authorized home network.
- Record the confirmed value here: your confirmed private home CIDR.
- End the Claude Code session by typing exit.
You return to the activated .venv shell inside hidden-camera-checker. Your confirmed scope is ready for the first observation.
Does the proposed scope look wrong?
Do not continue with a public address or a network containing more than 256 addresses. Ask Claude Code to identify the active private IPv4 network again from read-only system information.
Use help me verify my private home CIDR if you need help checking the boundary.
Run the first authorized observation
This action sends discovery probes only to the private network you confirmed. Stop here if your permission or network scope is unclear.
- Replace <confirmed-private-cidr> in the command below with your confirmed private home CIDR.
- Type OWN when the authorization prompt appears.
- Enter your administrator password if macOS requests it for Nmap.
Before you run this, do you expect every observed device name to make its purpose obvious?
- Create the raw inventory by running this command:
python camera_checker.py network --subnet <confirmed-private-cidr> --output network.json
What happens during this run?
- The private_network function rejects public IPv4 networks and scopes containing more than 256 addresses.
- The confirm_authorization function stops the run unless you type OWN exactly.
- Nmap performs host discovery with local-Ethernet ARP discovery and returns XML for Python to parse.
- The checker writes the observed IP address, hostname, and MAC address values to network.json.
You will see an observed-device table followed by Saved network.json. The table may contain clear names, missing names, or names that reveal little about each device.
That ambiguity is the intended result. An IP address or hostname alone cannot establish which observed device deserves closer inspection.
- Confirm that the table is labeled Observed devices.
- Confirm that the terminal ends with Saved network.json.
- Treat every row as a device observed during this run.
- Avoid describing the rows as every device on the network.
Did the observation fail?
Check that you replaced the CIDR placeholder with the private network you confirmed. The checker deliberately rejects public networks and scopes larger than 256 addresses.
If Nmap cannot run on macOS, confirm that you entered the requested administrator password. If the table is empty, confirm that the laptop is connected to the authorized home network.
Use help me diagnose my raw inventory run for focused debugging help.
You have created your first authorized network evidence and saved it locally. Next, you will add cautious registration clues so the checker can prioritize candidates without treating a clue as proof.
Add Registered-Organization Clues
Your raw inventory proved that authorized discovery works on your home network. However, an IP address with an unhelpful hostname gives you little reason to inspect one device before another.
You will use Claude Code to add current registration data from the IEEE Registration Authority. The checker will apply cautious candidate rules before giving Nmap a narrow two-port target list.
In this step, get ready to:
- Add fresh IEEE assignment downloads with longest-prefix matching.
- Flag candidates using visible hostnames or registered organizations.
- Check TCP ports 80 and 554 only for devices already marked as candidates.
Extend the network checker
IEEE assignment files connect available MAC address prefixes to registered organizations. The registration describes an address assignment without proving the device's current brand or purpose.
- In the Claude Code session from earlier, ask Claude Code to update camera_checker.py to the network-only cumulative version shown in Complete Code through main().
- Approve the proposed edit to camera_checker.py.
Why Use IEEE Public Listings?
The public MA-L, MA-M, and MA-S listings provide assignment data directly from the registration authority. The checker downloads fresh CSV copies without relying on a vendor-identification API.
The new code validates the downloaded headers before reading assignments. It stops if the expected assignment or organization columns cannot be found.
- The compact_hex() helper normalizes assignment prefixes and observed MAC addresses.
- The load_ieee_prefixes() function sorts prefixes from longest to shortest.
- The ieee_match() function returns the first matching organization and registry.
Review the candidate evidence flow
A device becomes a candidate only when a marker appears in its hostname or registered organization. The candidate label records which visible string matched.
- Ask Claude Code to explain how candidate_clues() compares DEFAULT_CAMERA_MARKERS with the hostname and ieee_organization fields.
- Ask Claude Code to trace how run_network() builds the candidate IP list before calling Nmap.
Claude Code should show that devices with an empty candidate_clues list never enter the targeted port scan. This keeps the evidence flow focused on devices already selected by a visible rule.
What Do the Port Results Mean?
The candidate scan uses -Pn to treat each supplied candidate as active. The -p selection is limited to 80,554.
TCP port 80 is registered for HTTP. TCP port 554 is registered for RTSP.
An open result means an application accepted a TCP connection from your laptop. A registered port does not prove that the application uses the assigned service or belongs to a camera.
Run the enriched inventory
This run stays inside the same authorized private network from your raw inventory. It performs discovery first before checking only the IP addresses selected by the candidate rules.
- Replace <confirmed-private-cidr> with the private CIDR you confirmed in the previous step.
- Prepare to type OWN when the authorization prompt appears.
Before you run this again, which rows do you expect to receive the narrow port check?
- Run the enriched network inventory with your confirmed private CIDR by running this command:
python camera_checker.py network --subnet <confirmed-private-cidr> --output network.json
What Does This Command Do?
- The command validates your private IPv4 scope before requesting authorization.
- The checker downloads fresh MA-L, MA-M, and MA-S assignment files into ieee-data.
- The discovery pass records observed IP addresses, hostnames, and available MAC addresses.
- The candidate pass applies the default markers plus any optional --marker values.
- The targeted pass checks ports 80 and 554 only for candidate IP addresses.
You should see an observed-device table with registered-organization, clue-count, and open-port columns. You should also see confirmation that network.json was saved.
That is the ambiguity reduced: each device now has explicit evidence fields without being declared a camera.
Did the Enriched Run Stop?
- Check your internet connection if the IEEE files could not be downloaded.
- Enter your macOS administrator password if sudo requests permission for Nmap.
- Confirm that the .venv from earlier is still activated if Python cannot find the project environment.
Ask for help with the exact stage that stopped.
- Ask Claude Code to inspect network.json and report its top-level keys plus the keys on one device object.
- Compare the reported keys with the enriched table from the network run.
The top level should include custom_markers and checked_candidate_ports. Every device should include ieee_organization, ieee_registry, candidate_clues, and open_ports.
✔️ Awesome, I've got everything!
- Save camera_checker.py if your editor still shows unsaved changes.
- Keep network.json for the evidence report you will generate later.
ⓧ I'd like to double check the full code
from __future__ import annotations
import argparse
import csv
import ipaddress
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import urlopen
IEEE_SOURCES = {
"MA-L": "https://standards-oui.ieee.org/oui/oui.csv",
"MA-M": "https://standards-oui.ieee.org/oui28/mam.csv",
"MA-S": "https://standards-oui.ieee.org/oui36/oui36.csv",
}
DEFAULT_CAMERA_MARKERS = (
"camera",
"webcam",
"cctv",
"surveillance",
"network video",
"ipcam",
"nvr",
"dvr",
"rtsp",
"hangzhou hikvision digital technology",
"axis communications",
"dahua technology",
)
PORT_LABELS = {80: "http", 554: "rtsp"}
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def save_json(path: str | Path, payload: dict) -> None:
Path(path).write_text(
json.dumps(payload, indent=2, ensure_ascii=False),
encoding="utf-8",
)
def load_json(path: str | Path) -> dict:
return json.loads(Path(path).read_text(encoding="utf-8"))
def compact_hex(value: str) -> str:
return re.sub(r"[^0-9A-Fa-f]", "", value).upper()
def private_network(value: str) -> ipaddress.IPv4Network:
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError as error:
raise ValueError(f"Invalid CIDR: {value}") from error
if not isinstance(network, ipaddress.IPv4Network):
raise ValueError("This beginner project supports private IPv4 networks only.")
if not network.is_private:
raise ValueError("Refusing to scan a non-private network.")
if network.num_addresses > 256:
raise ValueError("Refusing a network larger than 256 addresses.")
return network
def confirm_authorization(network: ipaddress.IPv4Network) -> None:
print(f"Target: {network}")
print("Continue only if you own this network or have explicit permission.")
answer = input("Type OWN to continue: ").strip()
if answer != "OWN":
raise RuntimeError("Authorization confirmation was not provided.")
def download_ieee_files(data_dir: Path) -> dict[str, Path]:
data_dir.mkdir(parents=True, exist_ok=True)
paths: dict[str, Path] = {}
for registry, url in IEEE_SOURCES.items():
destination = data_dir / f"{registry.lower().replace('-', '_')}.csv"
with urlopen(url, timeout=60) as response:
destination.write_bytes(response.read())
paths[registry] = destination
return paths
def find_header(fieldnames: list[str], required_words: tuple[str, ...]) -> str | None:
for fieldname in fieldnames:
lowered = fieldname.casefold()
if all(word in lowered for word in required_words):
return fieldname
return None
def load_ieee_prefixes(paths: dict[str, Path]) -> list[tuple[str, str, str]]:
prefixes: list[tuple[str, str, str]] = []
for registry, path in paths.items():
with path.open("r", encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle)
fieldnames = reader.fieldnames or []
assignment_key = find_header(fieldnames, ("assignment",))
organization_key = find_header(fieldnames, ("organization", "name"))
if not assignment_key or not organization_key:
raise RuntimeError(
f"Unexpected IEEE CSV headers in {path.name}: {fieldnames}"
)
for row in reader:
prefix = compact_hex(row.get(assignment_key, ""))
organization = (row.get(organization_key, "") or "").strip()
if prefix and organization:
prefixes.append((prefix, organization, registry))
prefixes.sort(key=lambda item: len(item[0]), reverse=True)
return prefixes
def ieee_match(
mac_address: str | None,
prefixes: list[tuple[str, str, str]],
) -> tuple[str | None, str | None]:
if not mac_address:
return None, None
compact_mac = compact_hex(mac_address)
if len(compact_mac) != 12:
return None, None
for prefix, organization, registry in prefixes:
if compact_mac.startswith(prefix):
return organization, registry
return None, None
def nmap_command(arguments: list[str]) -> list[str]:
if not shutil.which("nmap"):
raise RuntimeError("Nmap was not found on PATH.")
command = ["nmap", *arguments]
if platform.system() == "Darwin" and hasattr(os, "geteuid"):
if os.geteuid() != 0:
command.insert(0, "sudo")
return command
def run_nmap(arguments: list[str]) -> ET.Element:
command = nmap_command(arguments)
completed = subprocess.run(
command,
capture_output=True,
text=True,
timeout=180,
check=False,
)
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip()
raise RuntimeError(f"Nmap failed: {detail}")
try:
return ET.fromstring(completed.stdout)
except ET.ParseError as error:
raise RuntimeError("Nmap did not return valid XML output.") from error
def host_name(host: ET.Element) -> str | None:
hostname = host.find("./hostnames/hostname")
if hostname is None:
return None
return hostname.attrib.get("name")
def parse_discovery(root: ET.Element) -> list[dict]:
devices: list[dict] = []
for host in root.findall("host"):
status = host.find("status")
if status is None or status.attrib.get("state") != "up":
continue
ipv4 = None
mac = None
for address in host.findall("address"):
if address.attrib.get("addrtype") == "ipv4":
ipv4 = address.attrib.get("addr")
elif address.attrib.get("addrtype") == "mac":
mac = address.attrib.get("addr")
if ipv4:
devices.append(
{
"ip": ipv4,
"hostname": host_name(host),
"mac": mac,
}
)
return devices
def candidate_clues(device: dict, markers: list[str]) -> list[str]:
clues: list[str] = []
fields = {
"hostname": device.get("hostname") or "",
"registered organization": device.get("ieee_organization") or "",
}
for field_label, value in fields.items():
lowered = value.casefold()
for marker in markers:
if marker.casefold() in lowered:
clues.append(f"{field_label} contains '{marker}'")
return sorted(set(clues))
def parse_open_ports(root: ET.Element) -> dict[str, list[int]]:
results: dict[str, list[int]] = {}
for host in root.findall("host"):
ip_address = None
for address in host.findall("address"):
if address.attrib.get("addrtype") == "ipv4":
ip_address = address.attrib.get("addr")
break
if not ip_address:
continue
open_ports: list[int] = []
for port in host.findall("./ports/port"):
state = port.find("state")
if state is not None and state.attrib.get("state") == "open":
open_ports.append(int(port.attrib["portid"]))
results[ip_address] = sorted(open_ports)
return results
def print_network_table(devices: list[dict]) -> None:
print("\nObserved devices")
print("IP address Hostname Registered organization Clues Open")
print("-" * 105)
for device in devices:
ports = ",".join(str(port) for port in device["open_ports"]) or "-"
print(
f"{device['ip']:<17} "
f"{(device.get('hostname') or '-')[:24]:<24} "
f"{(device.get('ieee_organization') or '-')[:34]:<34} "
f"{len(device['candidate_clues']):<6} "
f"{ports}"
)
def run_network(args: argparse.Namespace) -> None:
network = private_network(args.subnet)
confirm_authorization(network)
data_paths = download_ieee_files(Path(args.data_dir))
prefixes = load_ieee_prefixes(data_paths)
discovery_xml = run_nmap(["-sn", "-PR", "-oX", "-", str(network)])
devices = parse_discovery(discovery_xml)
markers = [*DEFAULT_CAMERA_MARKERS, *args.marker]
for device in devices:
organization, registry = ieee_match(device.get("mac"), prefixes)
device["ieee_organization"] = organization
device["ieee_registry"] = registry
device["candidate_clues"] = candidate_clues(device, markers)
device["open_ports"] = []
candidates = [device for device in devices if device["candidate_clues"]]
if candidates:
port_xml = run_nmap(
[
"-Pn",
"-p",
"80,554",
"--open",
"-oX",
"-",
*[device["ip"] for device in candidates],
]
)
open_by_ip = parse_open_ports(port_xml)
for device in candidates:
device["open_ports"] = open_by_ip.get(device["ip"], [])
devices.sort(key=lambda item: ipaddress.ip_address(item["ip"]))
payload = {
"created_at": utc_now(),
"scope": str(network),
"authorization_confirmed": True,
"observation_wording": "Devices observed during this run; not every device.",
"custom_markers": args.marker,
"checked_candidate_ports": [80, 554],
"devices": devices,
}
save_json(args.output, payload)
print_network_table(devices)
print(f"\nSaved {args.output}")
def parser() -> argparse.ArgumentParser:
main_parser = argparse.ArgumentParser(
description="Read-only home network and Bluetooth observation helper."
)
subparsers = main_parser.add_subparsers(dest="command", required=True)
network_parser = subparsers.add_parser("network")
network_parser.add_argument("--subnet", required=True)
network_parser.add_argument("--output", default="network.json")
network_parser.add_argument("--data-dir", default="ieee-data")
network_parser.add_argument("--marker", action="append", default=[])
network_parser.set_defaults(function=run_network)
return main_parser
def main() -> int:
try:
args = parser().parse_args()
args.function(args)
return 0
except KeyboardInterrupt:
print("Stopped by user.", file=sys.stderr)
return 130
except Exception as error:
print(f"Error: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
Your network inventory now prioritizes visible clues while preserving uncertainty. Next, you will add a separate listening layer for nearby Bluetooth LE advertisements.
Compare Bluetooth Listening Posts
Your network checker now prioritizes devices using registration clues. However, the network inventory cannot observe nearby devices that only emit Bluetooth LE advertisements.
With Claude Code, you will add a separate listening layer built on Bleak. You will collect observations from two locations without pairing with nearby devices.
In this step, get ready to:
- Add Bluetooth advertisement listening to the checker.
- Record a ten-minute listening window inside the room.
- Record a ten-minute hallway listening window for comparison.
Add Bluetooth collection and report support
A Bluetooth advertisement is a short broadcast that nearby devices can observe. The collection code stores the latest summary returned by your operating system.
The finished file also needs report helpers that compare identifiers from two saved observations. The next step uses those helpers to build the evidence report.
- In the Claude Code session from earlier, request an exact update of camera_checker.py using the Complete Code through the report subcommand.
- Save camera_checker.py.
✔️ Awesome, I've got everything!
Your file now contains the network inventory plus the Bluetooth collection and reporting logic.
ⓧ I'd like to double check the full code
from __future__ import annotations
import argparse
import asyncio
import csv
import ipaddress
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import urlopen
from bleak import BleakScanner
IEEE_SOURCES = {
"MA-L": "https://standards-oui.ieee.org/oui/oui.csv",
"MA-M": "https://standards-oui.ieee.org/oui28/mam.csv",
"MA-S": "https://standards-oui.ieee.org/oui36/oui36.csv",
}
DEFAULT_CAMERA_MARKERS = (
"camera",
"webcam",
"cctv",
"surveillance",
"network video",
"ipcam",
"nvr",
"dvr",
"rtsp",
"hangzhou hikvision digital technology",
"axis communications",
"dahua technology",
)
PORT_LABELS = {80: "http", 554: "rtsp"}
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def save_json(path: str | Path, payload: dict) -> None:
Path(path).write_text(
json.dumps(payload, indent=2, ensure_ascii=False),
encoding="utf-8",
)
def load_json(path: str | Path) -> dict:
return json.loads(Path(path).read_text(encoding="utf-8"))
def compact_hex(value: str) -> str:
return re.sub(r"[^0-9A-Fa-f]", "", value).upper()
def private_network(value: str) -> ipaddress.IPv4Network:
try:
network = ipaddress.ip_network(value, strict=False)
except ValueError as error:
raise ValueError(f"Invalid CIDR: {value}") from error
if not isinstance(network, ipaddress.IPv4Network):
raise ValueError("This beginner project supports private IPv4 networks only.")
if not network.is_private:
raise ValueError("Refusing to scan a non-private network.")
if network.num_addresses > 256:
raise ValueError("Refusing a network larger than 256 addresses.")
return network
def confirm_authorization(network: ipaddress.IPv4Network) -> None:
print(f"Target: {network}")
print("Continue only if you own this network or have explicit permission.")
answer = input("Type OWN to continue: ").strip()
if answer != "OWN":
raise RuntimeError("Authorization confirmation was not provided.")
def download_ieee_files(data_dir: Path) -> dict[str, Path]:
data_dir.mkdir(parents=True, exist_ok=True)
paths: dict[str, Path] = {}
for registry, url in IEEE_SOURCES.items():
destination = data_dir / f"{registry.lower().replace('-', '_')}.csv"
with urlopen(url, timeout=60) as response:
destination.write_bytes(response.read())
paths[registry] = destination
return paths
def find_header(fieldnames: list[str], required_words: tuple[str, ...]) -> str | None:
for fieldname in fieldnames:
lowered = fieldname.casefold()
if all(word in lowered for word in required_words):
return fieldname
return None
def load_ieee_prefixes(paths: dict[str, Path]) -> list[tuple[str, str, str]]:
prefixes: list[tuple[str, str, str]] = []
for registry, path in paths.items():
with path.open("r", encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle)
fieldnames = reader.fieldnames or []
assignment_key = find_header(fieldnames, ("assignment",))
organization_key = find_header(fieldnames, ("organization", "name"))
if not assignment_key or not organization_key:
raise RuntimeError(
f"Unexpected IEEE CSV headers in {path.name}: {fieldnames}"
)
for row in reader:
prefix = compact_hex(row.get(assignment_key, ""))
organization = (row.get(organization_key, "") or "").strip()
if prefix and organization:
prefixes.append((prefix, organization, registry))
prefixes.sort(key=lambda item: len(item[0]), reverse=True)
return prefixes
def ieee_match(
mac_address: str | None,
prefixes: list[tuple[str, str, str]],
) -> tuple[str | None, str | None]:
if not mac_address:
return None, None
compact_mac = compact_hex(mac_address)
if len(compact_mac) != 12:
return None, None
for prefix, organization, registry in prefixes:
if compact_mac.startswith(prefix):
return organization, registry
return None, None
def nmap_command(arguments: list[str]) -> list[str]:
if not shutil.which("nmap"):
raise RuntimeError("Nmap was not found on PATH.")
command = ["nmap", *arguments]
if platform.system() == "Darwin" and hasattr(os, "geteuid"):
if os.geteuid() != 0:
command.insert(0, "sudo")
return command
def run_nmap(arguments: list[str]) -> ET.Element:
command = nmap_command(arguments)
completed = subprocess.run(
command,
capture_output=True,
text=True,
timeout=180,
check=False,
)
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip()
raise RuntimeError(f"Nmap failed: {detail}")
try:
return ET.fromstring(completed.stdout)
except ET.ParseError as error:
raise RuntimeError("Nmap did not return valid XML output.") from error
def host_name(host: ET.Element) -> str | None:
hostname = host.find("./hostnames/hostname")
if hostname is None:
return None
return hostname.attrib.get("name")
def parse_discovery(root: ET.Element) -> list[dict]:
devices: list[dict] = []
for host in root.findall("host"):
status = host.find("status")
if status is None or status.attrib.get("state") != "up":
continue
ipv4 = None
mac = None
for address in host.findall("address"):
if address.attrib.get("addrtype") == "ipv4":
ipv4 = address.attrib.get("addr")
elif address.attrib.get("addrtype") == "mac":
mac = address.attrib.get("addr")
if ipv4:
devices.append(
{
"ip": ipv4,
"hostname": host_name(host),
"mac": mac,
}
)
return devices
def candidate_clues(device: dict, markers: list[str]) -> list[str]:
clues: list[str] = []
fields = {
"hostname": device.get("hostname") or "",
"registered organization": device.get("ieee_organization") or "",
}
for field_label, value in fields.items():
lowered = value.casefold()
for marker in markers:
if marker.casefold() in lowered:
clues.append(f"{field_label} contains '{marker}'")
return sorted(set(clues))
def parse_open_ports(root: ET.Element) -> dict[str, list[int]]:
results: dict[str, list[int]] = {}
for host in root.findall("host"):
ip_address = None
for address in host.findall("address"):
if address.attrib.get("addrtype") == "ipv4":
ip_address = address.attrib.get("addr")
break
if not ip_address:
continue
open_ports: list[int] = []
for port in host.findall("./ports/port"):
state = port.find("state")
if state is not None and state.attrib.get("state") == "open":
open_ports.append(int(port.attrib["portid"]))
results[ip_address] = sorted(open_ports)
return results
def print_network_table(devices: list[dict]) -> None:
print("\nObserved devices")
print("IP address Hostname Registered organization Clues Open")
print("-" * 105)
for device in devices:
ports = ",".join(str(port) for port in device["open_ports"]) or "-"
print(
f"{device['ip']:<17} "
f"{(device.get('hostname') or '-')[:24]:<24} "
f"{(device.get('ieee_organization') or '-')[:34]:<34} "
f"{len(device['candidate_clues']):<6} "
f"{ports}"
)
def run_network(args: argparse.Namespace) -> None:
network = private_network(args.subnet)
confirm_authorization(network)
data_paths = download_ieee_files(Path(args.data_dir))
prefixes = load_ieee_prefixes(data_paths)
discovery_xml = run_nmap(["-sn", "-PR", "-oX", "-", str(network)])
devices = parse_discovery(discovery_xml)
markers = [*DEFAULT_CAMERA_MARKERS, *args.marker]
for device in devices:
organization, registry = ieee_match(device.get("mac"), prefixes)
device["ieee_organization"] = organization
device["ieee_registry"] = registry
device["candidate_clues"] = candidate_clues(device, markers)
device["open_ports"] = []
candidates = [device for device in devices if device["candidate_clues"]]
if candidates:
port_xml = run_nmap(
[
"-Pn",
"-p",
"80,554",
"--open",
"-oX",
"-",
*[device["ip"] for device in candidates],
]
)
open_by_ip = parse_open_ports(port_xml)
for device in candidates:
device["open_ports"] = open_by_ip.get(device["ip"], [])
devices.sort(key=lambda item: ipaddress.ip_address(item["ip"]))
payload = {
"created_at": utc_now(),
"scope": str(network),
"authorization_confirmed": True,
"observation_wording": "Devices observed during this run; not every device.",
"custom_markers": args.marker,
"checked_candidate_ports": [80, 554],
"devices": devices,
}
save_json(args.output, payload)
print_network_table(devices)
print(f"\nSaved {args.output}")
async def collect_bluetooth(label: str, seconds: int) -> dict:
print(f"Listening for Bluetooth LE advertisements at '{label}' for {seconds} seconds.")
discovered = await BleakScanner.discover(
timeout=float(seconds),
return_adv=True,
)
observations: list[dict] = []
for identifier, pair in discovered.items():
device, advertisement = pair
observations.append(
{
"identifier": identifier,
"address": device.address,
"os_name": device.name,
"local_name": advertisement.local_name,
"rssi_dbm": advertisement.rssi,
"service_uuids": sorted(advertisement.service_uuids),
"manufacturer_ids": sorted(advertisement.manufacturer_data.keys()),
}
)
observations.sort(key=lambda item: item["identifier"])
return {
"created_at": utc_now(),
"label": label,
"seconds": seconds,
"mode": "Advertisement listening only; no pairing or connection.",
"observations": observations,
}
def run_bluetooth(args: argparse.Namespace) -> None:
if args.seconds < 5 or args.seconds > 900:
raise ValueError("Bluetooth duration must be between 5 and 900 seconds.")
payload = asyncio.run(collect_bluetooth(args.label, args.seconds))
save_json(args.output, payload)
print(f"Observed {len(payload['observations'])} identifiers.")
print(f"Saved {args.output}")
def markdown_cell(value: object) -> str:
text = "-" if value in (None, "", []) else str(value)
return text.replace("|", "\\|").replace("\n", " ")
def observed_map(scan: dict) -> dict[str, dict]:
return {
item["identifier"]: item
for item in scan.get("observations", [])
if item.get("identifier")
}
def report_network_table(devices: list[dict]) -> list[str]:
lines = [
"| IP | Hostname | Registered organization | Candidate clues | Open candidate ports |",
"| --- | --- | --- | --- | --- |",
]
for device in devices:
port_text = ", ".join(
f"{port}/{PORT_LABELS.get(port, 'unknown')}" for port in device["open_ports"]
)
lines.append(
"| "
+ " | ".join(
[
markdown_cell(device["ip"]),
markdown_cell(device.get("hostname")),
markdown_cell(device.get("ieee_organization")),
markdown_cell("; ".join(device["candidate_clues"])),
markdown_cell(port_text),
]
)
+ " |"
)
return lines
def report_bluetooth_table(repeated: list[dict]) -> list[str]:
lines = [
"| Identifier observed in both places | Display name | Room RSSI | Hallway RSSI |",
"| --- | --- | --- | --- |",
]
for item in repeated:
lines.append(
"| "
+ " | ".join(
[
markdown_cell(item["identifier"]),
markdown_cell(item["name"]),
markdown_cell(item["first_rssi"]),
markdown_cell(item["second_rssi"]),
]
)
+ " |"
)
if not repeated:
lines.append("| None observed | - | - | - |")
return lines
def build_report(args: argparse.Namespace) -> None:
network = load_json(args.network)
first = load_json(args.first)
second = load_json(args.second)
first_map = observed_map(first)
second_map = observed_map(second)
repeated: list[dict] = []
for identifier in sorted(set(first_map) & set(second_map)):
first_item = first_map[identifier]
second_item = second_map[identifier]
repeated.append(
{
"identifier": identifier,
"name": first_item.get("local_name")
or first_item.get("os_name")
or second_item.get("local_name")
or second_item.get("os_name"),
"first_rssi": first_item.get("rssi_dbm"),
"second_rssi": second_item.get("rssi_dbm"),
}
)
devices = network.get("devices", [])
candidates = [device for device in devices if device.get("candidate_clues")]
owned = next(
(device for device in devices if device.get("ip") == args.owned_ip),
None,
)
if owned and owned.get("candidate_clues"):
validation = (
f"PASS: The controlled device at `{args.owned_ip}` was flagged because "
f"{'; '.join(owned['candidate_clues'])}. This validates the rule, not the device type."
)
elif owned:
validation = (
f"NOT CONFIRMED: `{args.owned_ip}` was observed but no candidate marker matched. "
"Use an exact visible hostname or registered organization from the inventory as a custom marker."
)
else:
validation = (
f"NOT CONFIRMED: `{args.owned_ip}` was not observed during the network run."
)
lines = [
"# Hidden Camera Checker Report",
"",
f"Generated: {utc_now()}",
f"Network scope: `{network.get('scope', 'unknown')}`",
"",
"## Facts",
"",
f"- Nmap and local-Ethernet ARP discovery observed {len(devices)} IPv4 devices during this run.",
f"- The first Bluetooth observation at `{first.get('label')}` recorded {len(first_map)} identifiers.",
f"- The second Bluetooth observation at `{second.get('label')}` recorded {len(second_map)} identifiers.",
f"- {len(repeated)} identifiers were returned by the operating system in both Bluetooth observations.",
"- No Bluetooth connection or pairing was requested by this tool.",
"",
*report_network_table(devices),
"",
"## Guesses and candidates",
"",
f"- {len(candidates)} network devices matched a camera-like name or registered-organization marker.",
"- A candidate label prioritizes inspection. It does not identify a camera.",
"- An open TCP port means an application accepted connections from this laptop on that port. It does not prove the application is HTTP, RTSP, or a camera.",
"",
*report_bluetooth_table(repeated),
"",
"## Owned-device validation",
"",
validation,
"",
"## Unknowns and blind spots",
"",
"- Powered-off, sleeping, shielded, wired-only, isolated, or radio-silent devices may not appear.",
"- Guest isolation, VLANs, firewalls, weak signal, randomized addresses, and scan timing can hide devices.",
"- IEEE data identifies the organization registered for an address block, not necessarily the retail brand, current owner, product type, or camera function.",
"- TCP ports 80 and 554 can be used by non-camera software, and cameras can use other ports or no reachable port.",
"- Bluetooth overlap does not establish that a device is a tracker, camera, or even the same physical object if identifiers change.",
"- This report is a prioritization aid, not a forensic detector or a guarantee that a room is camera-free.",
"",
"## Safe response",
"",
"If an object appears to be an indoor camera in a private room, do not touch or unplug it and do not confront anyone. Leave the area, preserve notes from a safe location, and report it to the property platform or host and local authorities when appropriate.",
"",
]
Path(args.output).write_text("\n".join(lines), encoding="utf-8")
print(validation)
print(f"Saved {args.output}")
def parser() -> argparse.ArgumentParser:
main_parser = argparse.ArgumentParser(
description="Read-only home network and Bluetooth observation helper."
)
subparsers = main_parser.add_subparsers(dest="command", required=True)
network_parser = subparsers.add_parser("network")
network_parser.add_argument("--subnet", required=True)
network_parser.add_argument("--output", default="network.json")
network_parser.add_argument("--data-dir", default="ieee-data")
network_parser.add_argument("--marker", action="append", default=[])
network_parser.set_defaults(function=run_network)
bluetooth_parser = subparsers.add_parser("bluetooth")
bluetooth_parser.add_argument("--label", required=True)
bluetooth_parser.add_argument("--seconds", type=int, default=600)
bluetooth_parser.add_argument("--output", required=True)
bluetooth_parser.set_defaults(function=run_bluetooth)
report_parser = subparsers.add_parser("report")
report_parser.add_argument("--network", required=True)
report_parser.add_argument("--first", required=True)
report_parser.add_argument("--second", required=True)
report_parser.add_argument("--owned-ip", required=True)
report_parser.add_argument("--output", default="camera-report.md")
report_parser.set_defaults(function=build_report)
return main_parser
def main() -> int:
try:
args = parser().parse_args()
args.function(args)
return 0
except KeyboardInterrupt:
print("Stopped by user.", file=sys.stderr)
return 130
except Exception as error:
print(f"Error: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
How does the listening layer work?
- The collect_bluetooth() function calls BleakScanner.discover(timeout=..., return_adv=True).
- The run_bluetooth() function saves each observation window as a JSON file.
- The code uses advertisement listening without creating a BleakClient instance.
- The report helpers compare identifiers returned in both observation files.
Record the room listening window
The first file establishes what this laptop observes from inside the room. Keeping the laptop in one place makes the location label meaningful.
- Turn on Bluetooth using your laptop's system controls.
- Place the laptop in the room you are authorized to check.
- Grant the terminal Bluetooth permission if your operating system requests it after the scan begins.
This listening window runs for ten minutes. The quiet wait is expected while Bleak collects advertisements.
Before you run the scan, which nearby devices do you expect this laptop to observe?
- Collect the room observation by running this command:
python camera_checker.py bluetooth --label room --seconds 600 --output room.json
What does this command capture?
- The room label records where this listening window happened.
- The 600 value keeps the scanner active for ten minutes.
- The room.json file stores the latest operating-system summary for each observed identifier.
- The scanner listens for advertisements without pairing or connecting.
- Wait for the scan to finish.
- Locate room.json in the hidden-camera-checker folder.
You will see an observed-identifier count. You will also see Saved room.json in the terminal.
Did the room observation fail?
Confirm Bluetooth is enabled. Check that the terminal has permission to use Bluetooth.
Confirm the terminal still shows the activated .venv environment before retrying.
Help me troubleshoot the room observation.
Record the hallway listening window
The second window captures what the same laptop observes from a nearby location. Using the same laptop keeps the comparison tied to one operating system's view.
- Move the laptop to a hallway or adjacent area.
This scan also takes ten minutes. Keep the terminal open throughout the listening window.
Before you run the second scan, do you expect every room identifier to appear again?
- Collect the hallway observation by running this command:
python camera_checker.py bluetooth --label hallway --seconds 600 --output hallway.json
What changes in the second run?
- The hallway label distinguishes this listening location from the room.
- The hallway.json file preserves the second observation window.
- The same duration gives both files matching ten-minute time windows.
- Wait for the second scan to finish.
- Locate hallway.json in the hidden-camera-checker folder.
You will see another observed-identifier count. You will also see Saved hallway.json in the terminal.
- Ask Claude Code to inspect room.json plus hallway.json for their recorded observation fields.
- Ask Claude Code to list the identifier values returned in both files.
Each observed item can include an identifier plus available names. It can also include an address plus RSSI, service UUIDs, and manufacturer IDs.
What does an overlap mean?
An overlap means this laptop received the same identifier during both observation windows. Device identity and movement remain unknown.
Identifiers can be absent or randomized. They can also be platform-specific or unstable across computers.
On macOS, Bleak uses a CoreBluetooth UUID instead of exposing a Bluetooth address. The files remain records of what this laptop observed.
Is hallway.json missing or empty?
Confirm Bluetooth stayed enabled after you moved the laptop. Nearby devices may also remain silent during the selected window.
Retry the hallway observation without pairing with any nearby device. Keep the laptop in the same hallway location until the command finishes.
Help me check the hallway observation.
You now have two location-specific Bluetooth observations collected without connecting to nearby devices. Next, you will test the candidate rule with a device you control and generate the evidence report.
Generate and Validate the Evidence Report
Your authorized network inventory now includes registration clues and candidate-only port results. Your two Bluetooth LE listening windows capture what the laptop observed in the room and hallway.
Those observations can still invite conclusions that the evidence cannot support. This step tests the candidate rule with an owned device before turning the results into a Markdown report that keeps facts separate from guesses.
In this step, get ready to:
- Validate the candidate rule with a video-capable device you own.
- Generate the final evidence report from your saved observations.
- Confirm the report preserves every evidence boundary and safety response.
Validate the candidate rule
A custom marker turns an exact visible hostname or registered IEEE organization into a controlled test of the candidate rule. A match establishes that the rule fired while leaving the device type unresolved.
- Connect a video-capable device you own to the authorized home network.
- Limit this controlled test to the device you own.
- Open network.json from the existing hidden-camera-checker folder in a text editor.
- Locate the inventory record for your owned device.
- Record its ip value here: <owned-device-ip>.
- Record one exact visible hostname or ieee_organization value here: <owned-device-visible-string>.
- Record the private IPv4 CIDR from the scope field here: <confirmed-private-cidr>.
Before you rerun the inventory, predict whether the owned record will gain a non-empty candidate clue.
- Replace the CIDR placeholder with <confirmed-private-cidr>.
- Replace the marker placeholder with <owned-device-visible-string>.
- Type OWN when the authorization prompt appears.
- Rerun the authorized inventory with your controlled marker by running this command:
python camera_checker.py network --subnet <confirmed-private-cidr> --marker "<owned-device-visible-string>" --output network.json
What does this command do?
- The --marker option adds your controlled string to the candidate rules.
- The checker refreshes network.json with observations from this authorized run.
- Only records with candidate clues reach the narrow Nmap check.
- That check covers TCP ports 80 and 554.
- Reload network.json in your text editor.
- Find the record whose ip matches <owned-device-ip>.
- Confirm its candidate_clues list is non-empty.
- Confirm its candidate clue names the visible field that matched your marker.
- Confirm custom_markers contains your exact controlled string.
- Confirm the record contains its candidate-only open_ports result.
That controlled result is in place. Your rule can now prioritize a device you own without claiming to identify its purpose.
Owned device still has no candidate clue?
Check that the IP matches the refreshed inventory record. Copy the hostname or registered organization exactly as it appears in that record.
Keep the marker inside quotation marks when it contains spaces.
Help me diagnose why my owned device did not receive a candidate clue.
Generate the evidence report
The report combines the network inventory with both Bluetooth observation files. It places direct observations and candidate interpretations in separate sections before evaluating the controlled test.
- Replace the owned-device IP placeholder with <owned-device-ip>.
- Generate camera-report.md from the four local evidence files by running the command below:
Before you run this, predict whether the validation will confirm a matching rule or a device type.
python camera_checker.py report --network network.json --first room.json --second hallway.json --owned-ip <owned-device-ip> --output camera-report.md
What does this command produce?
- The build_report() function reads network.json, room.json, and hallway.json.
- The Bluetooth comparison lists identifiers returned by the operating system in both listening windows.
- The owned-device lookup finds the inventory record matching your controlled IP.
- A PASS result confirms that the matching record has at least one candidate clue.
- Read the validation line printed in the terminal.
- Confirm the line begins with PASS:.
- Confirm the line says the result validates the rule.
- Confirm the terminal prints a saved message naming camera-report.md.
- Confirm camera-report.md exists inside the hidden-camera-checker folder.
The report now proves that your controlled string triggered the rule. It makes no claim that the string proves camera function.
Report validation did not pass?
A missing owned-device record usually means the IP does not match the refreshed inventory. A record without candidate clues usually means the marker does not exactly match its visible hostname or registered organization.
Help me trace an owned-device validation that did not return PASS.
Audit the evidence boundaries
The final read-through checks whether the report preserves uncertainty. Before you inspect it, predict whether any single name, organization, port, or repeated identifier can establish a device's purpose.
- Open camera-report.md from the existing hidden-camera-checker folder in a text editor.
- Check ## Facts for the network observation count.
- Check ## Facts for both Bluetooth observation counts.
- Check ## Guesses and candidates for cautious explanations of candidate clues.
- Check ## Owned-device validation for the PASS result.
- Confirm the validation states that the result validates the rule instead of the device type.
How should the report be read?
Facts describe what the tools observed during specific runs. Candidate clues prioritize records for review.
The controlled PASS result shows that a visible string triggered the matching rule. The device's purpose remains unknown.
Blind spots define what the checker cannot observe or establish. They prevent uncertainty from becoming a claim.
- Confirm ## Unknowns and blind spots states that powered-off, sleeping, shielded, wired-only, isolated, or radio-silent devices may not appear.
- Confirm the section states that guest isolation, VLANs, firewalls, weak signal, randomized addresses, and scan timing can hide devices.
- Confirm the section states that IEEE data identifies the organization registered for an address block without proving the retail brand, current owner, product type, or camera function.
- Confirm the section states that TCP ports 80 and 554 can be used by non-camera software.
- Confirm the section states that cameras can use other ports or no reachable port.
- Confirm the section states that Bluetooth overlap does not establish a tracker, camera, or physical identity.
- Confirm the section describes the report as a prioritization aid instead of a forensic detector or room-safety guarantee.
- Check ## Safe response for the instruction to leave an apparent indoor-camera scene untouched.
- Confirm the safe response says to avoid confrontation.
- Confirm the safe response says to preserve notes from a safe location.
- Confirm the safe response says to report the situation through appropriate channels.
You should now see all five report sections with PASS under owned-device validation. You have a defensible evidence report that records observations while preserving every important uncertainty.
Secret mission
Secret Mission: Run the Travel-Room Safety Sweep
Turn your tested home checker into a permission-first travel-room routine. Complete an authorized network check plus two five-minute Bluetooth listening windows. Add a flashlight sweep with a clear leave-and-report response.
Clean Up Your Resources
Clean Up Your Resources
Your checker and its evidence stay on your laptop. These local files create no ongoing cloud costs. Your Claude Pro subscription is the only recurring paid resource.
Cost warning
Claude Pro costs $20 when billed monthly. Applicable tax may increase the total.
Canceling renewal prevents another monthly charge. Your access continues until the current billing period ends.
Resources you used:
- The local hidden-camera-checker folder. It contains .venv, ieee-data, camera_checker.py, requirements.txt, network.json, room.json, hallway.json, camera-report.md, trip-report.md, and trip-room-checklist.md.
- The Claude Pro subscription. It is the only resource that can create another monthly charge.
Keep everything running
No action is needed. Choose this if you plan to use the checker for future authorized observations.
- Keep the hidden-camera-checker folder in a private location because its evidence files contain local device identifiers.
- Retain Claude Pro if you want continued access to Claude Code.
- Confirm authorization before every future network scan.
- Treat every future result as an observation instead of proof of a device's identity.
Pause - I'll come back to this later
Stop the active tools while preserving the checker and its evidence for another authorized session.
- Type exit in the Claude Code session to end it.
- Type deactivate in the activated project terminal to leave the virtual environment.
- Keep the hidden-camera-checker folder in a private location.
- Return to your signed-in Claude account.
- Select Settings.
- Select Billing.
- Cancel Claude Pro renewal if you do not need another month.
Your Claude Pro access continues until the current billing period ends. Your local checker remains ready for a future authorized test.
Delete - I don't want to use this again
This option permanently removes the checker and its local evidence. It also stops the only recurring subscription used by the project.
Review Your Evidence First
Deleting the project folder removes your reports and observation files. Preserve only the records you have a legitimate reason to keep.
Local identifiers can reveal details about nearby devices. Store any retained evidence somewhere private.
macOS
- Use Finder search to locate the hidden-camera-checker folder.
- Move the hidden-camera-checker folder to Trash.
- Search for copies of camera-report.md, trip-report.md, and trip-room-checklist.md.
- Move any unwanted copies outside the project folder to Trash.
- Empty Trash to remove the files permanently.
- Search for hidden-camera-checker once more.
You should see no remaining project folder. Any report copies you chose to remove should also be absent.
Windows
- Use File Explorer search to locate the hidden-camera-checker folder.
- Move the hidden-camera-checker folder to the Recycle Bin.
- Search for copies of camera-report.md, trip-report.md, and trip-room-checklist.md.
- Move any unwanted copies outside the project folder to the Recycle Bin.
- Empty the Recycle Bin to remove the files permanently.
- Search for hidden-camera-checker once more.
You should see no remaining project folder. Any report copies you chose to remove should also be absent.
Removing the local files does not cancel Claude Pro. Complete the subscription cleanup separately.
- Return to your signed-in Claude account.
- Select Settings.
- Select Billing.
- Cancel Claude Pro renewal.
Your paid access continues until the current billing period ends. The subscription should no longer renew for another month.
Nice Work!
Nice Work!
You did it! Your read-only checker now turns authorized observations into a cautious evidence report without presenting clues as proof.
You've learned how to:
- Build a read-only checker with Claude Code. It limits Nmap discovery to an authorized private IPv4 CIDR of no more than 256 addresses.
- Apply fresh IEEE registration data as a clue. The checker tests TCP ports 80 and 554 only for devices already flagged by cautious rules.
- Compare two Bluetooth LE listening windows without pairing or connecting. Your evidence report keeps observation separate from interpretation.
- Secret Mission: Convert the home workflow into a permission-first travel-room checklist. It pairs a flashlight sweep with a safe stop-and-report response.
Ready to quiz yourself?