使用Python实现BT种子和磁力链接的相互转换
使⽤Python实现BT种⼦和磁⼒链接的相互转换
bt种⼦⽂件转换为磁⼒链接
BT种⼦⽂件相对磁⼒链来说存储不⽅便,⽽且在⽹站上存放BT⽂件容易引起版权纠纷,⽽磁⼒链相对来说则风险⼩⼀些。⽽且很多论坛或者⽹站限制了⽂件上传的类型,分享⼀个BT种⼦还需要改⽂件后缀或者压缩⼀次,其他⼈需要下载时候还要额外多⼀步下载种⼦的操作。
所以将BT种⼦转换为占⽤空间更⼩,分享更⽅便的磁⼒链还是有挺⼤好处的。
相应的将BT种⼦转换为磁⼒链代码为:
import bencode, hashlib, base64, urllib
torrent = open('ubuntu-12.04.t', 'rb').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'],
'tr': metadata['announce'],
'xl': metadata['info']['length']}
paramstr = urllib.urlencode(params)
magneturi = 'magnet:?%s' % paramstr
print magneturi
还有另外⼀个效率相对较⾼,⽽且更⽅便的⽅案是安装libtorrent,在ubuntu只需要apt-get install python-libtorrent即可对应转换磁⼒链的代码为:
import libtorrent as bt
info = bt.torrent_info('t')
print "magnet:?xt=urn:btih:%s&dn=%s" % (info.info_hash(), info.name())
转换磁⼒链接为bt种⼦⽂件
下⾯来看⼀个反过程,将磁⼒链转化为种⼦⽂件。
1、需要先安装python-libtorrent包,在ubuntu环境下,可以通过以下指令完成安装:
# sudo apt-get install python-libtorrent
2、代码如下:
#!/usr/bin/env python
import shutil
import tempfile
import os.path as pt
import sys
托福和雅思import libtorrent as lt
from time import sleep
def magnet2torrent(magnet, output_name=None):
if output_name and \
not pt.isdir(output_name) and \
廿怎么读not pt.isdir(pt.dirname(pt.abspath(output_name))):
print("Invalid output folder: " + pt.dirname(pt.abspath(output_name)))
print("")
tempdir = tempfile.mkdtemp()
ses = lt.session()
params = {
'save_path': tempdir,
深圳化妆学校那里好'duplicate_is_error': True,
'storage_mode': lt.storage_mode_t(2),
'paused': False,
'auto_managed': True,
'duplicate_is_error': True
}
handle = lt.add_magnet_uri(ses, magnet, params)
print("Downloading Metadata (this may take a while)")
while (not handle.has_metadata()):
try:
sleep(1)
except KeyboardInterrupt:
print("")
ses.pause()
print("Cleanup dir " + tempdir)
<(tempdir)
ses.pause()
print("Done")
torinfo = _torrent_info()
torfile = lt.create_torrent(torinfo)
5月1日放假多少天output = pt.abspath(torinfo.name() + ".torrent")
if output_name:
if pt.isdir(output_name):
output = pt.abspath(pt.join(
output_name, torinfo.name() + ".torrent"))
elif pt.isdir(pt.dirname(pt.abspath(output_name))):
output = pt.abspath(output_name)
print("Saving torrent file here : " + output + " ...")
torcontent = lt.ate())
f = open(output, "wb")
f.write(lt.ate()))
f.close()
print("Saved! Cleaning up dir: " + tempdir)
<(tempdir)
return output
def showHelp():
print("")
print("USAGE: " + pt.basename(sys.argv[0]) + " MAGNET [OUTPUT]")  print(" MAGNET\t- the magnet url")
print(" OUTPUT\t- the output torrent file name")
print("")
def main():
if len(sys.argv) < 2:
showHelp()
magnet = sys.argv[1]货款利率
牛魔王output_name = None
if len(sys.argv) >= 3:
output_name = sys.argv[2]
magnet2torrent(magnet, output_name)
if __name__ == "__main__":
main()
3、⽤法如下
# python Magnet_To_Torrent2.py <magnet link> [torrent file]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。