给定一个.torrent文件,如何在python中生成磁链接?

Seb*_*ixx 19 python bittorrent magnet-uri

我需要一种方法将.torrents转换成磁力链接.想在python中这样做.有没有图书馆已经这样做了?

jte*_*ace 35

您可以使用从BitTorrent中提取的bencode模块执行此操作.

为了向您展示一个示例,我从这里下载了一个Ubuntu的torrent ISO:

http://releases.ubuntu.com/12.04/ubuntu-12.04.1-desktop-i386.iso.torrent
Run Code Online (Sandbox Code Playgroud)

然后,您可以在Python中解析它,如下所示:

>>> import bencode
>>> torrent = open('ubuntu-12.04.1-desktop-i386.iso.torrent', 'r').read()
>>> metadata = bencode.bdecode(torrent)
Run Code Online (Sandbox Code Playgroud)

只从torrent元数据的"info"部分计算磁体哈希,然后在base32中编码,如下所示:

>>> hashcontents = bencode.bencode(metadata['info'])
>>> import hashlib
>>> digest = hashlib.sha1(hashcontents).digest()
>>> import base64
>>> b32hash = base64.b32encode(digest)
>>> b32hash
'CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6'
Run Code Online (Sandbox Code Playgroud)

您可以通过查看此处来验证这是否正确,您将看到磁铁链接是:

magnet:?xt=urn:btih:CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6
Run Code Online (Sandbox Code Playgroud)

如果要在磁体URI中填写一些额外的参数:

>>> params = {'xt': 'urn:btih:%s' % b32hash,
...           'dn': metadata['info']['name'],
...           'tr': metadata['announce'],
...           'xl': metadata['info']['length']}
>>> import urllib
>>> paramstr = urllib.urlencode(params)
>>> magneturi = 'magnet:?%s' % paramstr
>>> magneturi
'magnet:?dn=ubuntu-12.04.1-desktop-i386.iso&tr=http%3A%2F%2Ftorrent.ubuntu.com%3A6969%2Fannounce&xl=729067520&xt=urn%3Abtih%3ACT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6'
Run Code Online (Sandbox Code Playgroud)