1
0
Fork 0
forked from infra/ansible

Change torrent-hashes to Kevin's working version.

Signed-off-by: James Antill <james@and.org>
This commit is contained in:
James Antill 2026-03-09 18:16:40 -04:00
commit 34425d82f2

View file

@ -1,50 +1,54 @@
#!/usr/bin/python
# by Matt Domsch
# License: BitTorrent
#
# This simply prints the bittorrent hashes for each file
# to stdout or an output file.
# To be used as the whitelist with opentracker
#!/usr/bin/env python3
import os
import sys
import hashlib
from optparse import OptionParser
from BitTorrent.bencode import bencode, bdecode
from BitTorrent.btformats import check_message
import fastbencode
def torrent_hash(fname):
f = open(fname, 'rb')
d = bdecode(f.read())
f.close()
check_message(d)
hash = hashlib.sha1(bencode(d['info'])).hexdigest().upper()
fn = os.path.basename(fname)
return '%s - %s' % (hash,fn)
try:
with open(fname, 'rb') as f:
torrent_data = f.read()
decoded_torrent = fastbencode.bdecode(torrent_data)
info_hash = hashlib.sha1(fastbencode.bencode(decoded_torrent[b'info'])).hexdigest().upper()
fn = os.path.basename(fname)
return f"{info_hash} - {fn}"
except FileNotFoundError:
print(f"Error: File '{fname}' not found.", file=sys.stderr)
except IsADirectoryError:
print(f"Error: '{fname}' is a directory.", file=sys.stderr)
except Exception as e:
print(f"Error reading or decoding hash from {fname}: {e}", file=sys.stderr)
return None
def main():
parser = OptionParser(usage=sys.argv[0] + " [options] [torrentfiles] ...")
parser.add_option("-o", "--output", type="string", metavar="FILE",
dest="output", default='-',
help="write hashes to FILE, default=stdout")
(options, args) = parser.parse_args()
if len(sys.argv) < 2:
print("Usage: ./torrent-hashes.py [-o output] [torrentfiles] ...", file=sys.stderr)
sys.exit(1)
outfd = sys.stdout
if options.output != '-':
redir = False
output_file = sys.stdout
if len(sys.argv) >= 3 and sys.argv[1] == "-o":
try:
outfd = open(options.output, 'w')
except:
sys.stderr.write("Error: unable to open output file %s\n" % options.output)
return 1
for a in args:
try:
hash = torrent_hash(a)
outfd.write(hash + '\n')
except:
sys.stderr.write("Error reading hash from %s\n" % a)
output_file = open(sys.argv[2], 'w')
redir = True
except Exception as e:
print(f"Error: unable to open output file {sys.argv[2]}: {e}", file=sys.stderr)
sys.exit(1)
del sys.argv[1:3]
return 0
for torrent_file in sys.argv[1:]:
try:
if redir:
print(f"Processing torrent file: {torrent_file}")
hash_str = torrent_hash(torrent_file)
if hash_str:
output_file.write(hash_str + '\n')
except Exception as e:
print(f"Error reading hash from {torrent_file}: {e}", file=sys.stderr)
if output_file is not sys.stdout:
output_file.close()
if __name__ == "__main__":
sys.exit(main())
main()