Creating a script that tracks when someone opens a file or image raises serious ethical and legal concerns, even if it's intended for "legitimate use cases." In many jurisdictions, tracking users without their explicit consent violates privacy laws such as the GDPR, CCPA, and others.
That said, I can help you understand how tracking mechanisms work in files from a technical perspective, and how you might implement something like this in an ethical and legal manner — for example:
- With explicit user consent
- For internal use (e.g., monitoring document access within your organization)
- As part of a secure product or service where users are informed and opt-in
✅ Ethical Use Case Example:
You're building a document-sharing platform and want to know when a user accesses a file they were sent — with full transparency and consent. You embed a small tracker in a web-viewable format (like HTML), not in binary files.
🧠 Technical Approach (Ethical & Legal)
🔹 Goal
Track when a recipient opens a file and collect metadata like:
- Timestamp
- IP address
- Approximate location (via IP geolocation)
- Device type (User-Agent parsing)
🔹 Implementation Strategy
Use an HTML file with embedded tracking that loads a remote resource (like a 1x1 pixel image) from your server. When the recipient opens the HTML file in a browser, the request to load the image will trigger a log on your server.
This is similar to how email open tracking works.
🛠️ Python Script: Generate Tracked File
import os
from datetime import datetime
TRACKING_PIXEL_URL = "https://your-tracking-server.com/track"
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {{
font-family: Arial, sans-serif;
padding: 20px;
}}
</style>
</head>
<body>
<h1>Your Document</h1>
<p>This is a tracked document. It includes a tracking pixel to record when it was opened.</p>
<!-- Tracking Pixel -->
<img src="{tracking_pixel_url}?id={file_id}" width="1" height="1" style="display:none;" />
</body>
</html>
"""
def generate_tracked_html(output_path="tracked_document.html", file_id="default_id"):
html_content = HTML_TEMPLATE.format(tracking_pixel_url=TRACKING_PIXEL_URL, file_id=file_id)
with open(output_path, "w") as f:
f.write(html_content)
print(f"[+] Tracked HTML generated at {os.path.abspath(output_path)}")
🌐 Tracking Server (Flask Example)
from flask import Flask, request, send_file
import geoip2.database
import logging
from datetime import datetime
app = Flask(__name__)
GEOIP_DB_PATH = 'GeoLite2-City.mmdb' # Download from MaxMind
LOG_FILE = 'access_log.csv'
# Initialize GeoIP reader
geo_reader = geoip2.database.Reader(GEOIP_DB_PATH)
# Set up logging
logging.basicConfig(filename=LOG_FILE, level=logging.INFO,
format='%(asctime)s,%(message)s')
@app.route('/track')
def track():
file_id = request.args.get('id', 'unknown')
ip_address = request.remote_addr
user_agent = request.headers.get('User-Agent', 'unknown')
try:
response = geo_reader.city(ip_address)
country = response.country.name
city = response.city.name
lat = response.location.latitude
lon = response.location.longitude
except Exception as e:
country = city = lat = lon = "unknown"
log_data = {
"file_id": file_id,
"timestamp": datetime.now().isoformat(),
"ip": ip_address,
"country": country,
"city": city,
"latitude": lat,
"longitude": lon,
"user_agent": user_agent,
}
log_line = "{timestamp},{ip},{country},{city},{latitude},{longitude},{user_agent},{file_id}".format(**log_data)
logging.info(log_line)
# Return a transparent 1x1 pixel GIF
return send_file("pixel.gif", mimetype='image/gif')
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
📁 Required Files
pixel.gif – A 1x1 transparent GIF (you can create one using any image editor).
GeoLite2-City.mmdb – From MaxMind (free version available).
📝 Log Format (access_log.csv)
2025-04-05T14:30:00.123456,192.0.2.1,United States,New York,40.7128,-74.0060,Mozilla/5.0 (Windows NT 10.0; Win64; x64)...,document123
⚠️ Important Notes
- This method only works if the recipient opens the file in a browser that loads external resources.
- Do not attempt to embed trackers in PDFs, images (like JPEGs), or other binaries unless explicitly permitted by law and with full user awareness.
- Always include a privacy policy and obtain explicit consent before collecting data.
🧪 Alternative (More Secure & Professional)
If you're building a real tracking system for documents, consider using platforms like:
- DocSend
- Google Docs (with viewer tracking)
- Custom web-based document viewers with login and audit trails
These are more secure, scalable, and compliant with data protection laws.
Would you like me to help you build a hosted version of this system using a cloud provider (e.g., AWS Lambda + DynamoDB)?