我没有检查这是否有效,但它是开始的参考,请按照此链接在 python中使用 bencode 库的示例。
#!/usr/bin/python
import sys
import urllib
import bencode
import hashlib
import base64
if len(sys.argv) == 0:
print("Usage: file")
exit()
torrent = open(sys.argv[1], 'r').read()
metadata = bencode.bdecode(torrent)
hashcontents = bencode.bencode(metadata['info'])
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
params = {'xt': 'urn:btih:%s' % b32hash,
'dn': metadata['info']['name']}
announcestr = ''
for announce in metadata['announce-list']:
announcestr += '&' + urllib.urlencode({'tr':announce[0]})
paramstr = urllib.urlencode(params) + announcestr
magneturi = 'magnet:?%s' % paramstr
print(magneturi)