给定一个.torrent文件,如何在python中生成一个磁力链接? [英] Given a .torrent file how do I generate a magnet link in python?

查看:177
本文介绍了给定一个.torrent文件,如何在python中生成一个磁力链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种将.torrents转换为磁铁链接的方法.想要在python中这样做的方法.有没有已经在执行此操作的库?

I need a way to convert .torrents into magnet links. Would like a way to do so in python. Are there any libraries that already do this?

推荐答案

您可以使用 bencode 模块,从BitTorrent中提取.

You can do this with the bencode module, extracted from BitTorrent.

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

To show you an example, I downloaded a torrent ISO of Ubuntu from here:

http://releases.ubuntu.com/12.04/ubuntu-12.04.1-desktop-i386.iso.torrent

然后,您可以像这样在Python中对其进行解析:

Then, you can parse it in Python like this:

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

仅从torrent元数据的"info"部分计算出一个磁石哈希值,然后将其编码为base32,如下所示:

A magnet hash is calculated from only the "info" section of the torrent metadata and then encoded in base32, like this:

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

您可以在此处,您会看到磁铁链接为:

You can verify that this is correct by looking here and you will see the magnet link is:

magnet:?xt=urn:btih:CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6

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

If you want to fill in some extra parameters to the magnet 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'

这篇关于给定一个.torrent文件,如何在python中生成一个磁力链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆