Skip to content

Instantly share code, notes, and snippets.

@werdl
Created April 4, 2025 19:32
Show Gist options
  • Save werdl/5d8c9d30ce05fcb0af9dd4d87a2e5d2c to your computer and use it in GitHub Desktop.
Save werdl/5d8c9d30ce05fcb0af9dd4d87a2e5d2c to your computer and use it in GitHub Desktop.
Guess a file type based on a random snippet of its hex (required xxd)
#!/usr/bin/env python3
import os
import random
import subprocess
import sys
def prompt_file():
directory = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
while True:
files = [os.path.join(root, file) for root, _,
files in os.walk(directory) for file in files]
file = random.choice(files)
if os.access(file, os.R_OK):
break
lines = subprocess.run(
["xxd", "-R", "never", file], capture_output=True, text=True)
lines = lines.stdout.splitlines()
# Print a random block of 20 lines
start = random.randint(0, len(lines) - 20)
end = start + 20
print("\n".join(lines[start:end]))
file_type = subprocess.run(["file", file], capture_output=True, text=True).stdout.split(
":")[1].split(",")[0].strip()
other_file_types = set()
while len(other_file_types) < 2:
other_file = random.choice(files)
other_file_type = subprocess.run(
["file", other_file], capture_output=True, text=True
).stdout.split(":")[1].split(",")[0].strip()
if other_file_type != file_type:
other_file_types.add(other_file_type)
other_file_types = list(other_file_types)
file_types = [file_type] + other_file_types
random.shuffle(file_types)
print("Guess the file type:")
for i, ftype in enumerate(file_types, start=1):
print(f"{i}) {ftype}")
guess = int(input("Enter the number of your guess: ")) - 1
if file_types[guess] == file_type:
print(f"Correct! The file type is {file_type}")
else:
print(f"Wrong! The file type is {file_type}")
while True:
prompt_file()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment