使用Python實現BT種子和磁力連結的相互轉換

來源:互聯網
上載者:User
bt種子檔案轉換為磁力連結

BT種子檔案相對磁力鏈來說儲存不方便,而且在網站上存放BT檔案容易引起著作權糾紛,而磁力鏈相對來說則風險小一些。而且很多論壇或者網站限制了檔案上傳的類型,分享一個BT種子還需要改檔案尾碼或者壓縮一次,其他人需要下載時候還要額外多一步下載種子的操作。

所以將BT種子轉換為佔用空間更小,分享更方便的磁力鏈還是有挺大好處的。

首先一個方案是使用bencode這個外掛程式,通過pip方式安裝或者自行下載源檔案https://pypi.python.org/pypi/bencode/1.0通過python setup.py install方式安裝均可。

相應的將BT種子轉換為磁力鏈代碼為:

import bencode, hashlib, base64, urllibtorrent = open('ubuntu-12.04.2-server-amd64.iso.torrent', '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' % paramstrprint magneturi

還有另外一個效率相對較高,而且更方便的方案是安裝libtorrent,在ubuntu只需要apt-get install python-libtorrent即可對應轉換磁力鏈的代碼為:

import libtorrent as btinfo = bt.torrent_info('test.torrent')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 pythonimport shutilimport tempfileimport os.path as ptimport sysimport libtorrent as ltfrom time import sleepdef 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("")    sys.exit(0)  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("Aborting...")      ses.pause()      print("Cleanup dir " + tempdir)      shutil.rmtree(tempdir)      sys.exit(0)  ses.pause()  print("Done")  torinfo = handle.get_torrent_info()  torfile = lt.create_torrent(torinfo)  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.bencode(torfile.generate())  f = open(output, "wb")  f.write(lt.bencode(torfile.generate()))  f.close()  print("Saved! Cleaning up dir: " + tempdir)  ses.remove_torrent(handle)  shutil.rmtree(tempdir)  return outputdef 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()    sys.exit(0)  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  [torrent file]
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.