Home > Programming & scripting, Python > Getting a torrents info_hash for XBT Tracker using python

Getting a torrents info_hash for XBT Tracker using python

July 25th, 2007

I’ve been playing around with XBT tracker for a small project I’m concidering and needed a script for getting the info_hash info from torrent files to use in the xbt_files table.

Since I read through the sourceforge forums and it seems like I wasn’t alone in having a few issues at first, I might as well put the script here as well if someone else need it.
It is based on the original BitTorrent source code, and has stripped down all of the unneeded stuff from btshowmetainfo.py .

It simply takes a torrent filename as an argument and then prints the hash_info of that torrent to stdout.

Code:

#!/usr/bin/env python

from sys import *
from sha import *
from bencode import *

if len(argv) != 2:
    print "ERROR: use ./hash_info.py filename"
    exit(2)

filename = argv[1]

metainfo_file = open(filename, 'rb')
try:
    metainfo = bdecode(metainfo_file.read())
except ValueError:
    print "ERROR: Not a valid torrent file"
    exit(1)
metainfo_file.close()
info = metainfo['info']
info_hash = sha(bencode(info))

stdout.write(info_hash.digest())

Sample usage:

./hash_info.py /home/buffi/wow_a_torrent.torrent > wow_a_torrent.hash

download the script

The only dependency is bencode.py from BitTorrent. Download it and put it in the same folder as this script.
I also have bencode.py mirrored here

buffi Programming & scripting, Python

  1. January 31st, 2008 at 23:04 | #1

    Great code, lets see if it works. I am having some issues with uploaded torrents too and i need to know the Info_Hash so when this works it will help me quiet a lot i guess.

    Thanks in advance.

  2. July 12th, 2009 at 05:41 | #2

    I wrote code to generate it for you.

    You can write me and get an example.

  3. dan
    November 20th, 2009 at 12:07 | #3

    I’d propose to use

    stdout.write(info_hash.hexdigest())

    instead of

    stdout.write(info_hash.digest())

  1. No trackbacks yet.