Skip to content

Instantly share code, notes, and snippets.

@mtask
Last active February 8, 2023 21:14
Show Gist options
  • Save mtask/f02cfa8df78b4eac1f267792eb4ff04a to your computer and use it in GitHub Desktop.
Save mtask/f02cfa8df78b4eac1f267792eb4ff04a to your computer and use it in GitHub Desktop.
xyz
import os
import sys
import subprocess
import argparse
import json
def file_types_summary(path):
file_types = {}
for root, dirs, files in os.walk(path):
for f in files:
full_path = os.path.join(root, f)
try:
res = subprocess.check_output(['file', full_path]).decode('utf-8').split(':')[1].strip()
if res in file_types:
file_types[res] += 1
else:
file_types[res] = 1
except PermissionError:
print(f"Permission denied: {full_path}", file=sys.stderr)
return file_types
def file_full_details(path):
files_details = []
for root, dirs, files in os.walk(path):
for f in files:
d = {}
full_path = os.path.join(root, f)
d['path'] = full_path
try:
d['type'] = subprocess.check_output(['file', full_path]).decode('utf-8').split(':')[1].strip()
except Exception as e:
d['type'] = 'N/A'
print(str(e), file=sys.stderr)
try:
d['sha256'] = subprocess.check_output(['sha256sum', full_path]).decode('utf-8').split(' ')[0].strip()
except Exception as e:
d['sha256'] = 'N/A'
print(str(e), file=sys.stderr)
try:
d['sha1'] = subprocess.check_output(['sha1sum', full_path]).decode('utf-8').split(' ')[0].strip()
except Exception as e:
d['sha1'] = 'N/A'
print(str(e), file=sys.stderr)
try:
d['md5'] = subprocess.check_output(['md5sum', full_path]).decode('utf-8').split(' ')[0].strip()
except Exception as e:
d['md5'] = 'N/A'
print(str(e), file=sys.stderr)
files_details.append(d)
return files_details
def csv(headers, data):
print(headers)
for i in data:
if isinstance(i, dict):
print(f'{i["path"]}|{i["type"]}|{i["sha256"]}|{i["sha1"]}|{i["md5"]}')
else:
print(f'{i}|{data[i]}')
def get_args():
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-p','--path', help='Path to check', required=True)
parser.add_argument('-q','--quick', action='store_true', help='Path to check', required=False)
parser.add_argument('-o','--output', help='output type', required=True)
args = parser.parse_args()
return args
if __name__=="__main__":
args = get_args()
arg_path = os.path.expanduser(args.path)
output = args.output
if args.quick:
if output == 'csv':
result = file_types_summary(arg_path)
csv('Type|Count', result)
elif output == 'json':
print(json.dumps(result, indent=4))
else:
result = file_full_details(arg_path)
if output == 'csv':
csv('Path|Type|sha256|sha1|md5', result)
elif output == 'json':
print(json.dumps(result, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment