Extracting geo-location and metadata from documents, images, and browsers involves different techniques and tools depending on the type of file and the information you are seeking. Here’s a general overview for each category:
1. Documents:
Extracting Metadata:
For documents such as PDFs, Microsoft Word, or Excel files, you can use libraries or tools that provide access to document metadata.
- Python Libraries:
PyPDF2for PDF files.python-docxfor Microsoft Word files.openpyxlfor Microsoft Excel files.
Example (Using PyPDF2 for PDFs):
import PyPDF2
def extract_pdf_metadata(pdf_file_path):
with open(pdf_file_path, 'rb') as pdf_file:
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
document_info = pdf_reader.getDocumentInfo()
print(f"Title: {document_info.title}")
print(f"Author: {document_info.author}")
# Extract other metadata fields as needed
# Usage
extract_pdf_metadata('example.pdf')
2. Images:
Extracting Metadata:
For images, metadata often includes information like GPS coordinates (geo-location), camera settings, and timestamps.
- Python Libraries:
Pillow(PIL Fork) is a powerful image processing library.exifreadfor reading EXIF data from images.
Example (Using Pillow for Images):
from PIL import Image
def extract_image_metadata(image_file_path):
with Image.open(image_file_path) as img:
exif_data = img._getexif()
if exif_data:
print(f"GPS Info: {exif_data.get(34853)}") # GPS Info tag
# Extract other metadata fields as needed
# Usage
extract_image_metadata('example.jpg')
3. Browsers:
Extracting Browser History:
For browsers, extracting history may involve interacting with browser APIs or accessing browser data directly.
- Python Libraries:
sqlite3for working with SQLite databases where browsers store history.
Example (Extracting Chrome History from SQLite Database):
import sqlite3
import os
def extract_chrome_history():
chrome_history_path = os.path.expanduser('~/.config/google-chrome/Default/History')
connection = sqlite3.connect(chrome_history_path)
cursor = connection.cursor()
cursor.execute("SELECT title, url, last_visit_time FROM urls ORDER BY last_visit_time DESC LIMIT 10;")
history_entries = cursor.fetchall()
for entry in history_entries:
print(f"Title: {entry[0]}, URL: {entry[1]}, Last Visit Time: {entry[2]}")
# Usage
extract_chrome_history()
Note:
- Extracting geo-location from documents and images may require specific tools or libraries depending on the file format and how the information is stored.
- Be aware of privacy and legal considerations when extracting and using geo-location data.
Extracting geo-location information
import requests
class IPtoGeo(object):
def __init__(self, ip_address):
self.latitude = ''
self.longitude = ''
self.country = ''
self.city = ''
self.time_zone = ''
self.ip_address = ip_address
self.get_location()
def get_location(self):
json_request = requests.get('https://freegeoip.app/json/%s' % self.ip_address).json()
if 'country_name' in json_request.keys():
self.country = json_request['country_name']
if 'country_code' in json_request.keys():
self.country_code = json_request['country_code']
if 'time_zone' in json_request.keys():
self.time_zone = json_request['time_zone']
if 'city' in json_request.keys():
self.city = json_request['city']
if 'latitude' in json_request.keys():
self.latitude = json_request['latitude']
if 'longitude' in json_request.keys():
self.longitude = json_request['longitude']
if __name__ == '__main__':
ip = IPtoGeo('8.8.8.8')
print(ip.__dict__)Explanation:
-
Class
IPtoGeo:- The class is designed to represent an IP address and its corresponding geolocation information.
- The constructor (
__init__method) initializes instance variables for latitude, longitude, country, city, time zone, and the given IP address. - The
get_locationmethod is then called to fetch the geolocation information.
-
Method
get_location:- It sends a GET request to the freegeoip.app API, passing the IP address in the URL.
- The response is expected to be in JSON format, and it is parsed using
requests.get(...).json(). - The method then checks for various keys in the JSON response to extract relevant geolocation information (country, country code, time zone, city, latitude, and longitude).
- Extracted information is stored in the instance variables.
-
Usage in
__main__block:- An instance of the
IPtoGeoclass is created with the IP address ‘8.8.8.8’. - The
__dict__attribute is used to print the dictionary representation of the instance, showing the values of its attributes.
- An instance of the
-
API Endpoint:
- The API endpoint used is
'https://freegeoip.app/json/%s' % self.ip_address. It returns geolocation information for the given IP address.
- The API endpoint used is
Note: Ensure that you have internet access and that the freegeoip.app API is accessible from your environment when running this code. Additionally, be aware of the terms of use of the API and any rate limits that may apply.
Domain Geo-Location
import requests
def geoip(domain):
headers = {
"Content-Type": "application/json"
}
response = requests.get('http://freegeoip.app/json/' + domain,headers=headers)
return(response.text)
print(geoip('python.org'))The provided Python code defines a function geoip(domain) that sends a GET request to the freegeoip.app API to retrieve geolocation information for a given domain. Here’s an explanation of the code:
Explanation:
-
Importing
requests:- The code begins by importing the
requestslibrary, which is commonly used for making HTTP requests.
- The code begins by importing the
-
Function
geoip(domain):- The
geoipfunction takes a single parameterdomain, representing the domain for which geolocation information is to be retrieved.
- The
-
Headers:
- The
headersdictionary is defined with the key “Content-Type” set to “application/json.” This header is typically used to specify the media type of the resource.
- The
-
HTTP GET Request:
- The
requests.getfunction is used to send a GET request to the freegeoip.app API. - The URL is constructed by appending the provided
domainto the base URL:'http://freegeoip.app/json/' + domain. - The
headersparameter is set to include the defined headers.
- The
-
Response Handling:
- The response from the API is stored in the
responsevariable. - The function returns the content of the response as a text string using
response.text.
- The response from the API is stored in the
-
Usage Example:
- The
geoipfunction is called with the domain ‘python.org’. - The result is printed using
print(geoip('python.org')).
- The
geoip2 module
The geoip2 module is a Python library that provides an interface to MaxMind’s GeoIP2 databases. These databases contain information about IP addresses, including their geographical location (country, city, latitude, longitude), network information, and more.
Here’s a brief overview of using the geoip2 module:
Installation:
You can install the geoip2 module using pip:
pip install geoip2
Usage Example:
import geoip2.database
def get_geoip_info(ip_address):
# Provide the path to the GeoIP2 database file
database_path = 'path/to/GeoLite2-City.mmdb'
# Create a reader object using the GeoIP2 database file
with geoip2.database.Reader(database_path) as reader:
try:
# Query the GeoIP2 database with the given IP address
response = reader.city(ip_address)
# Access information from the response object
country = response.country.name
city = response.city.name
latitude = response.location.latitude
longitude = response.location.longitude
print(f"Country: {country}")
print(f"City: {city}")
print(f"Latitude: {latitude}")
print(f"Longitude: {longitude}")
except geoip2.errors.AddressNotFoundError:
print("IP address not found in the GeoIP2 database.")
# Example usage
get_geoip_info('8.8.8.8')
Explanation:
-
Import
geoip2andgeoip2.database:- Import the necessary modules from the
geoip2library.
- Import the necessary modules from the
-
Provide the GeoIP2 Database Path:
- Specify the path to the GeoIP2 database file (e.g., ‘GeoLite2-City.mmdb’).
- You can download the GeoIP2 databases from the MaxMind website.
-
Create a Reader Object:
- Use the
geoip2.database.Readerclass to create a reader object. This object is used to query the GeoIP2 database.
- Use the
-
Query the GeoIP2 Database:
- Use the
reader.city(ip_address)method to query the GeoIP2 database with the given IP address. - The response object contains information about the IP address, including country, city, location, etc.
- Use the
-
Access Information from the Response:
- Extract relevant information from the response object, such as country name, city name, latitude, and longitude.
-
Handle AddressNotFoundError:
- Catch the
geoip2.errors.AddressNotFoundErrorexception in case the provided IP address is not found in the GeoIP2 database.
- Catch the
Notes:
- Make sure to download the appropriate GeoIP2 database file for your use case from the MaxMind website (https://dev.maxmind.com/geoip/geoip2/geolite2/).
- Update the
database_pathvariable with the correct path to your GeoIP2 database file.
The geoip2 module provides a convenient way to retrieve geolocation information based on IP addresses and is widely used in applications that require IP-based geolocation.
Geo-location from domain name
#!/usr/bin/env python3
import socket
import geoip2.database
import argparse
parser = argparse.ArgumentParser(description='Get IP Geolocation info')
parser.add_argument('--hostname', action="store", dest="hostname",default='python.org')
given_args = parser.parse_args()
hostname = given_args.hostname
ip_address = socket.gethostbyname(hostname)
print("IP address: {0}".format(ip_address))
reader = geoip2.database.Reader('GeoLite2-City.mmdb')
response = reader.city(ip_address)
if response is not None:
print('Country: ',response.country)
print('Continent: ',response.continent)
print('Location: ', response.location)The provided Python script is a command-line utility that takes a hostname as an argument, resolves its IP address, and then uses the geoip2 module to obtain geolocation information for that IP address. Here’s an explanation of the code:
Explanation:
-
Shebang Line:
#!/usr/bin/env python3is a shebang line that indicates the path to the Python interpreter to use when executing the script.
-
Imports:
- The script imports the necessary modules:
socketfor hostname resolution andgeoip2.databasefor working with the GeoIP2 database.
- The script imports the necessary modules:
-
Argument Parsing with
argparse:- The script uses the
argparsemodule to define and parse command-line arguments. - It accepts a single optional argument
--hostname, which specifies the hostname to look up (default is ‘python.org’).
- The script uses the
-
Resolving Hostname to IP:
- The script uses
socket.gethostbyname(hostname)to resolve the given hostname to an IP address. - The resolved IP address is then printed to the console.
- The script uses
-
GeoIP2 Database Reader:
- It creates a
geoip2.database.Readerobject using the ‘GeoLite2-City.mmdb’ database file. - The database file is assumed to be in the same directory as the script. You may need to adjust the path based on your setup.
- It creates a
-
Querying the GeoIP2 Database:
- The script queries the GeoIP2 database with the resolved IP address using
reader.city(ip_address).
- The script queries the GeoIP2 database with the resolved IP address using
-
Displaying Geolocation Information:
- The geolocation information, such as country, continent, and location, is printed to the console.
-
Note:
- Make sure to have the
geoip2library installed (pip install geoip2) and download the GeoIP2 database file (‘GeoLite2-City.mmdb’) from the MaxMind website.
- Make sure to have the
You can run this script from the command line, providing a hostname using the --hostname option, and it will display geolocation information based on the resolved IP address. For example:
python script_name.py --hostname example.com
How to use the maxinddb-geolite2
#!/usr/bin/env python3
import socket
from geolite2 import geolite2
import argparse
import json
parser = argparse.ArgumentParser(description='Get IP Geolocation info')
parser.add_argument('--hostname', action="store", dest="hostname", default='python.org')
given_args = parser.parse_args()
hostname = given_args.hostname
ip_address = socket.gethostbyname(hostname)
print("IP address: {0}".format(ip_address))
reader = geolite2.reader()
response = reader.get(ip_address)
print (json.dumps(response,indent=4))
print ("Continent:",json.dumps(response['continent']['names']['en'],indent=4))
print ("Country:",json.dumps(response['country']['names']['en'],indent=4))
print ("Latitude:",json.dumps(response['location']['latitude'],indent=4))
print ("Longitude:",json.dumps(response['location']['longitude'],indent=4))
print ("Time zone:",json.dumps(response['location']['time_zone'],indent=4))The provided Python script is a command-line utility that uses the geolite2 library to obtain geolocation information for a given hostname. It resolves the hostname to an IP address, queries the MaxMind GeoLite2 database, and then prints the geolocation information in JSON format. Here’s an explanation of the code:
Explanation:
-
Shebang Line:
#!/usr/bin/env python3is a shebang line that indicates the path to the Python interpreter to use when executing the script.
-
Imports:
- The script imports necessary modules:
socketfor hostname resolution,geolite2for working with the GeoLite2 database,argparsefor command-line argument parsing, andjsonfor JSON formatting.
- The script imports necessary modules:
-
Argument Parsing with
argparse:- The script uses
argparseto define and parse command-line arguments. - It accepts a single optional argument
--hostname, specifying the hostname to look up (default is ‘python.org’).
- The script uses
-
Resolving Hostname to IP:
- The script uses
socket.gethostbyname(hostname)to resolve the given hostname to an IP address. - The resolved IP address is then printed to the console.
- The script uses
-
GeoLite2 Database Reader:
- It creates a
geolite2.reader()object, allowing you to query the GeoLite2 database.
- It creates a
-
Querying the GeoLite2 Database:
- The script queries the GeoLite2 database with the resolved IP address using
reader.get(ip_address).
- The script queries the GeoLite2 database with the resolved IP address using
-
Displaying Geolocation Information in JSON:
- The geolocation information is printed in JSON format using
json.dumps(response, indent=4).
- The geolocation information is printed in JSON format using
-
Extracting Specific Geolocation Details:
- Specific details such as continent name, country name, latitude, longitude, and time zone are extracted from the response and printed individually.
-
Note:
- Make sure to have the
geolite2library installed (pip install maxminddb-geolite2) and ensure you have the necessary permissions to read the GeoLite2 database file.
- Make sure to have the
You can run this script from the command line, providing a hostname using the --hostname option, and it will display geolocation information based on the resolved IP address. For example:
python script_name.py --hostname example.com
Extracting metadata from images
EXIF and PIL module
EXIF (Exchangeable Image File Format)
- Definition: A standard format for storing metadata within digital images.
- Purpose: Provides valuable information about the image, such as:
- Camera make and model
- Date and time of capture
- Exposure settings (aperture, shutter speed, ISO)
- Location (if GPS enabled)
- Image dimensions
- Copyright information
- And more
PIL (Python Imaging Library) Module
- Definition: A powerful Python library for working with images.
- Capabilities:
- Opening, manipulating, and saving images in various formats
- Resizing, cropping, rotating, and converting images
- Creating new images
- Drawing shapes and text on images
- Applying filters and effects
Accessing EXIF Data Using PIL
-
Import the PIL module:
from PIL import Image -
Open the image:
image = Image.open("path/to/image.jpg") -
Retrieve EXIF data (if available):
exif_data = image._getexif() # Note the underscore -
Access specific EXIF tags (using tag IDs from PIL.ExifTags):
if exif_data: camera_model = exif_data.get(0x0110) # Make date_taken = exif_data.get(0x0132) # Date/Time print("Camera:", camera_model) print("Date Taken:", date_taken) else: print("No EXIF data found.")
Key Points:
- PIL can read EXIF data, but it cannot write or modify it.
- For advanced EXIF manipulation, consider external libraries like
pyexiftool. - Be mindful of potential privacy implications when working with EXIF data.
Getting EXIF data from an image
from PIL import Image
from PIL.ExifTags import TAGS
for (i,j) in Image.open('images/image.jpg')._getexif().items():
print('%s = %s' % (TAGS.get(i), j))Explanation:
-
Importing PIL Modules:
from PIL import Image: Import theImageclass from the PIL (or Pillow) library.from PIL.ExifTags import TAGS: Import theTAGSdictionary, which maps EXIF tag numbers to human-readable names.
-
Opening an Image:
img = Image.open(image_path): Open the image file located at the specified path ('images/image.jpg') using theImage.open()method. This creates anImageobject (img).
-
Retrieving and Printing EXIF Data:
img._getexif(): Retrieve the EXIF data from the image. The_getexif()method returns a dictionary where keys are EXIF tag numbers, and values are the corresponding tag values.- The code then iterates over each key-value pair in the EXIF data and prints the information using the
TAGSdictionary to convert tag numbers to human-readable names.
-
Printing Format:
print('%s = %s' % (TAGS.get(tag), value)): Print each EXIF tag and its corresponding value in a formatted way.%sis a placeholder for a string, and%sand%sare replaced by the tag name and value, respectively.
Note:
- EXIF data may not be present in all image files, so the code includes error handling to avoid issues if the image has no EXIF data.
- Ensure that you have Pillow installed (
pip install Pillow) before running the code. - The
TAGSdictionary is crucial for converting EXIF tag numbers to human-readable names, providing more understandable output.
This script is useful for inspecting the metadata stored in images, which can include details about the camera settings, date and time, and other information captured at the time the photo was taken.
Decode GPS information and retrieve EXIF metadata
from PIL.ExifTags import TAGS, GPSTAGS
from PIL import Image
import os
def get_exif_metadata(image_path):
exifData = {}
image = Image.open(image_path)
if hasattr(image, '_getexif'):
exifinfo = image._getexif()
if exifinfo is not None:
for tag, value in exifinfo.items():
decoded = TAGS.get(tag, tag)
exifData[decoded] = value
decode_gps_info(exifData)
return exifData
def decode_gps_info(exif):
gpsinfo = {}
if 'GPSInfo' in exif:
Nsec = exif['GPSInfo'][2][2]
Nmin = exif['GPSInfo'][2][1]
Ndeg = exif['GPSInfo'][2][0]
Wsec = exif['GPSInfo'][4][2]
Wmin = exif['GPSInfo'][4][1]
Wdeg = exif['GPSInfo'][4][0]
if exif['GPSInfo'][1] == 'N':
Nmult = 1
else:
Nmult = -1
if exif['GPSInfo'][1] == 'E':
Wmult = 1
else:
Wmult = -1
latitude = Nmult * (Ndeg + (Nmin + Nsec/60.0)/60.0)
longitude = Wmult * (Wdeg + (Wmin + Wsec/60.0)/60.0)
exif['GPSInfo'] = {"Latitue" : latitude, "Longitude" : longitude}
def printMetadata():
for dirpath, dirnames, files in os.walk("images"):
for name in files:
print("[+] Metadata for file: %s " %(dirpath+os.path.sep+name))
try:
exifData = {}
exif = get_exif_metadata(dirpath+os.path.sep+name)
for metadata in exif:
print("Metadata: %s - Value: %s " %(metadata, exif[metadata]))
print("\n")
except:
import sys, traceback
traceback.print_exc(file=sys.stdout)
if __name__ == "__main__":
printMetadata()Explanation:
-
get_exif_metadataFunction:- Opens an image file using Pillow (
Image.open). - Retrieves the EXIF data using
image._getexif(). - Decodes the EXIF data using
TAGSand stores it in theexifDatadictionary. - Calls the
decode_gps_infofunction to handle GPS information. - Returns the
exifDatadictionary.
- Opens an image file using Pillow (
-
decode_gps_infoFunction:- Decodes GPS information from the EXIF data and calculates latitude and longitude.
- Updates the
exifdictionary with the calculated GPS coordinates.
-
printMetadataFunction:- Walks through the “images” directory and prints metadata for each image file.
- Calls
get_exif_metadatato retrieve and print the EXIF data. - Uses exception handling to catch any errors during the process.
-
if __name__ == "__main__":Block:- Calls the
printMetadatafunction when the script is executed.
- Calls the
-
Printing Metadata:
- The script prints metadata for each image file in the “images” directory, including any GPS coordinates that were decoded.
exifread module
import exifread
file = open('images/image.jpg', 'rb')
tags = exifread.process_file(file)
for tag in tags.keys():
print("Key: %s, value %s" % (tag, tags[tag]))Explanation:
-
Importing the
exifreadModule:import exifread: Import theexifreadmodule, which provides functions for reading EXIF metadata from image files.
-
Opening the Image File:
file = open('images/image.jpg', 'rb'): Open the image file (‘images/image.jpg’) in binary mode ('rb'). This allows reading the file as binary data.
-
Processing EXIF Tags:
tags = exifread.process_file(file): Use theprocess_filefunction fromexifreadto read and process EXIF tags from the opened image file. The result is a dictionary (tags) where keys are tag names, and values are the corresponding tag values.
-
Iterating and Printing Key-Value Pairs:
for tag in tags.keys():: Iterate through the keys of thetagsdictionary, which represent EXIF tags.print("Key: %s, value: %s" % (tag, tags[tag])): Print each key-value pair in a formatted string. The%splaceholders are replaced with the tag name (tag) and its corresponding value (tags[tag]).
-
Note:
- EXIF tags contain information such as camera settings, date and time, GPS coordinates, and more.
- The script assumes that the image file (‘images/image.jpg’) exists. Adjust the file path as needed.
- Ensure that you have the
exifreadlibrary installed (pip install exifread) before running the script.
Extracting Metadata from PDF documents
Extract Data from PDF
#!usr/bin/env python3
from PyPDF2 import PdfFileReader, PdfFileWriter
import os, time, os.path, stat
from PyPDF2.generic import NameObject, createStringObject
def get_metadata():
for dirpath, dirnames, files in os.walk("pdf"):
for data in files:
ext = data.lower().rsplit('.', 1)[-1]
if ext in ['pdf']:
print("[--- Metadata : " + "%s ", (dirpath+os.path.sep+data))
print("------------------------------------------------------------------------------------")
pdfReader = PdfFileReader(open(dirpath+os.path.sep+data, 'rb'))
info = pdfReader.getDocumentInfo()
for metaItem in info:
print ('[+] ' + metaItem.strip( '/' ) + ': ' + info[metaItem])
pages = pdfReader.getNumPages()
print ('[+] Pages:', pages)
layout = pdfReader.getPageLayout()
print ('[+] Layout: ' + str(layout))
xmpinfo = pdfReader.getXmpMetadata()
if hasattr(xmpinfo,'dc_contributor'): print ('[+] Contributor:' , xmpinfo.dc_contributor)
if hasattr(xmpinfo,'dc_identifier'): print ( '[+] Identifier:', xmpinfo.dc_identifier)
if hasattr(xmpinfo,'dc_date'): print ('[+] Date:', xmpinfo.dc_date)
if hasattr(xmpinfo,'dc_source'): print ('[+] Source:', xmpinfo.dc_source)
if hasattr(xmpinfo,'dc_subject'): print ('[+] Subject:' , xmpinfo.dc_subject)
if hasattr(xmpinfo,'xmp_modifyDate'): print ('[+] ModifyDate:', xmpinfo.xmp_modifyDate)
if hasattr(xmpinfo,'xmp_metadataDate'): print ('[+] MetadataDate:', xmpinfo.xmp_metadataDate)
if hasattr(xmpinfo,'xmpmm_documentId'): print ('[+] DocumentId:' , xmpinfo.xmpmm_documentId)
if hasattr(xmpinfo,'xmpmm_instanceId'): print ('[+] InstanceId:', xmpinfo.xmpmm_instanceId)
if hasattr(xmpinfo,'pdf_keywords'): print ('[+] PDF-Keywords:', xmpinfo.pdf_keywords)
if hasattr(xmpinfo,'pdf_pdfversion'): print ('[+] PDF-Version:', xmpinfo.pdf_pdfversion)
if hasattr(xmpinfo,'dc_publisher'):
for published in xmpinfo.dc_publisher:
if publisher:
print ("[+] Publisher:\t" + publisher)
fsize = os.stat((dirpath+os.path.sep+data))
print ('[+] Size:', fsize[6], 'bytes \n\n')
if __name__ == "__main__":
get_metadata()The provided Python script uses the PyPDF2 library to extract and print metadata from PDF files. The script recursively walks through the “pdf” directory, identifies PDF files, and retrieves information such as document properties, number of pages, layout, and additional XMP metadata.
Explanation:
-
Shebang Line:
#!/usr/bin/env python3: Specifies the Python interpreter to use.
-
Imports:
from PyPDF2 import PdfFileReader: Import thePdfFileReaderclass from the PyPDF2 library.import os: Import theosmodule for working with the file system.
-
get_metadataFunction:- Walks through the “pdf” directory using
os.walk. - Identifies PDF files based on their extension.
- Opens each PDF file and uses
PdfFileReaderto extract document information, number of pages, layout, and XMP metadata. - Prints the extracted metadata.
- Walks through the “pdf” directory using
-
Printing Specific XMP Metadata:
- Checks for the presence of specific XMP metadata attributes using
hasattrand prints them if available.
- Checks for the presence of specific XMP metadata attributes using
-
File Size:
- Uses
os.statto get file size information and prints the size in bytes.
- Uses
-
if __name__ == "__main__":Block:- Calls the
get_metadatafunction when the script is executed.
- Calls the
This script is useful for extracting basic information about PDF files, such as document properties and XMP metadata. Make sure to have the PyPDF2 library installed (pip install PyPDF2).
Extract Text From PDF
#!/usr/bin/env python3
import PyPDF2
# Open the PDF file for reading in binary mode
pdfFile = open("pdf/XMPSpecificationPart3.pdf", "rb")
# Create a PdfFileReader object
pdfReader = PyPDF2.PdfFileReader(pdfFile)
# Prompt the user to enter the page number
page_number = input("Enter page number:")
# Get the specified page object
pageObj = pdfReader.getPage(int(page_number) - 1)
# Extract text from the page
text_pdf = str(pageObj.extractText())
# Print the extracted text
print(text_pdf)
Explanation:
-
Shebang Line:
#!/usr/bin/env python3: Specifies the Python interpreter to use.
-
Importing
PyPDF2Module:import PyPDF2: Imports the PyPDF2 module for working with PDF files.
-
Opening the PDF File:
pdfFile = open("pdf/XMPSpecificationPart3.pdf", "rb"): Opens the specified PDF file (“pdf/XMPSpecificationPart3.pdf”) in binary mode.
-
Creating a
PdfFileReaderObject:pdfReader = PyPDF2.PdfFileReader(pdfFile): Creates aPdfFileReaderobject to read the PDF file.
-
User Input for Page Number:
page_number = input("Enter page number:"): Prompts the user to enter the page number they want to extract text from.
-
Getting the Specified Page Object:
pageObj = pdfReader.getPage(int(page_number) - 1): Gets the specified page object using thegetPagemethod. Note that page numbers are zero-indexed in PyPDF2.
-
Extracting Text from the Page:
text_pdf = str(pageObj.extractText()): Extracts text from the specified page using theextractTextmethod and converts it to a string.
-
Printing Extracted Text:
print(text_pdf): Prints the extracted text to the console.
Identifying the technology used by a website
The “BuiltWith” service is typically associated with web technologies and is not directly related to a Python module named “builtwith.” However, I’ll provide information on both:
-
BuiltWith Service:
- BuiltWith is a web service that allows you to discover the technologies used on websites. It provides insights into the web hosting, content delivery networks (CDNs), analytics, advertising, and other technologies implemented by a website.
-
BuiltWith Python Module:
- The
builtwithPython module is a tool that allows you to use the BuiltWith service programmatically. It can be used to retrieve information about the technologies employed by a particular website.
- The
Here’s a basic example of how you can use the builtwith Python module:
import builtwith
# Specify the website URL
website_url = "https://example.com"
# Use builtwith to retrieve technology information
result = builtwith.lookup(website_url)
# Print the result
print(result)
This script will print a dictionary containing information about the technologies used by the specified website. The builtwith module can be installed using:
pip install builtwith
Please note that while using web scraping tools and services, it’s important to respect the terms of service of the websites you interact with and ensure compliance with legal and ethical considerations.
Extracting metadata from web browsers
Fire forensics with python
#!/usr/bin/env python3
import sqlite3
import os
def getDownloads(downloadDB):
try:
# Connect to the downloads database
connection = sqlite3.connect(downloadDB)
cursor = connection.cursor()
# Execute a query to retrieve download information
cursor.execute('SELECT name, source, datetime(endTime/1000000,\'unixepoch\') FROM moz_downloads;')
# Print the downloaded files information
print('\n[*] --- Files Downloaded --- ')
for row in cursor:
print('[+] File: ' + str(row[0]) + ' from source: ' + str(row[1]) + ' at: ' + str(row[2]))
except Exception as exception:
print('\n[*] Error reading moz_downloads database ', exception)
def getCookies(cookiesDB):
try:
# Connect to the cookies database
connection = sqlite3.connect(cookiesDB)
cursor = connection.cursor()
# Execute a query to retrieve cookie information
cursor.execute('SELECT host, name, value FROM moz_cookies')
# Print the cookie information
print('\n[*] -- Found Cookies --')
for row in cursor:
print('[+] Host: ' + str(row[0]) + ', Cookie: ' + str(row[1]) + ', Value: ' + str(row[2]))
except Exception as exception:
print('\n[*] Error reading moz_cookies database ', exception)
def getHistory(placesDB):
try:
# Connect to the browsing history database
connection = sqlite3.connect(placesDB)
cursor = connection.cursor()
# Execute a query to retrieve browsing history information
cursor.execute("select url, datetime(visit_date/1000000, 'unixepoch') from moz_places, moz_historyvisits where visit_count > 0 and moz_places.id== moz_historyvisits.place_id;")
# Print the browsing history information
print('\n[*] -- Found History --')
for row in cursor:
print('[+] ' + str(row[1]) + ' - Visited: ' + str(row[0]))
except Exception as exception:
print('\n[*] Error reading moz_places, moz_historyvisits databases ', exception)
def main():
# Check if the required SQLite databases exist and extract information
if os.path.isfile('downloads.sqlite'):
getDownloads('downloads.sqlite')
else:
print('[!] downloads.sqlite not found ')
if os.path.isfile('cookies.sqlite'):
getCookies('cookies.sqlite')
else:
print('[!] cookies.sqlite not found ')
if os.path.isfile('places.sqlite'):
getHistory('places.sqlite')
else:
print('[!] places.sqlite not found: ')
if __name__ == '__main__':
main()
The Python script is designed to extract information from Mozilla Firefox databases related to downloads, cookies, and browsing history. It connects to the SQLite databases used by Firefox to store this information and retrieves relevant data. Here’s a breakdown of the script:
Explanation:
-
getDownloadsFunction:- Connects to the SQLite database storing download information (
moz_downloads). - Executes a query to retrieve download details, including file name, source, and download time.
- Prints the downloaded files’ information.
- Connects to the SQLite database storing download information (
-
getCookiesFunction:- Connects to the SQLite database storing cookie information (
moz_cookies). - Executes a query to retrieve cookie details, including host, name, and value.
- Prints the cookie information.
- Connects to the SQLite database storing cookie information (
-
getHistoryFunction:- Connects to the SQLite databases storing browsing history information (
moz_placesandmoz_historyvisits). - Executes a query to retrieve browsing history details, including URL and visit time.
- Prints the browsing history information.
- Connects to the SQLite databases storing browsing history information (
-
mainFunction:- Checks if the required SQLite databases exist (
downloads.sqlite,cookies.sqlite, andplaces.sqlite). - Calls the corresponding functions to extract and print information from each database.
- Checks if the required SQLite databases exist (
-
if __name__ == '__main__':Block:- Calls the
mainfunction when the script is executed directly.
- Calls the
Note: This script assumes that the Firefox databases (downloads.sqlite, cookies.sqlite, and places.sqlite) are present in the same directory as the script. Adjust file paths as needed. Also, be aware of privacy and legal considerations when handling user data.