利用python开源库制作并验证torrent种子文件

下面的文章来源于参考文献[1], 这里将我的实践过程记录如下,方便后来人参考,我的操作系统是Ubuntu 14.04 64bit

一.安装开源BT种子制作软件包

cd  /home/taoyx/下载/

wget http://jaist.dl.sourceforge.net/project/mktorrent/mktorrent/1.0/mktorrent-1.0.tar.gz

tar zxvf mktorrent-1.0.tar.gz

cd mktorrent-1.0

make

sudo make install

安装完成后,使用下面的命令查看mktorrent是否在下面的目录中

which mktorrent

/usr/local/bin/mktorrent

二.安装python的bencode模块,以便用来获取BT种子文件信息,

wget https://pypi.python.org/packages/source/b/bencode/bencode-1.0.tar.gz

tar zxvf bencode-1.0.tar.gz

cd bencode-1.0.tar.gz

sudo python setup.py install

三.利用下面的python脚本make_torrent.py来制作和验证BT种子文件信息, 注意,如果只制作而不验证, 直接在python中调用下面的命令行就可以了.

#!/usr/bin/env python
#encoding: utf-8

import os, re, time, sys
import hashlib, bencode

if len(sys.argv) != 3:
    print 'usage: %s <src_file> <dst_file>' % sys.argv[0]
    sys.exit(1)

bt_file = sys.argv[1]
bt_torrent = sys.argv[2]

if os.path.exists(bt_torrent):
    os.remove(bt_torrent)

if os.path.exists(bt_file):
    #make torrent ......
    cmd = '/usr/local/bin/mktorrent -v -p -l 18 -a http://bt1.text.cn/announce -a http://bt2.text.cn/announce -o %s %s' \
    % (bt_torrent, bt_file)
    #validate torrent info
    result = os.popen(cmd).readlines()[-1].strip()
    if 'done' in result:
        bt_path = {}
        bt_filename = open(bt_torrent, 'rb')
        bt_info = bencode.bdecode(bt_filename.read()).get('info')
        bt_info_hash_hex = hashlib.sha1(bencode.bencode(bt_info)).hexdigest()
        if os.path.isdir(bt_file):
            bt_file_size = 0
            for length in bt_info.get('files'):
                bt_file_size += int(length['length'])
                bt_path['/'.join(length['path'])] = length['length']
        else:
            bt_file_size = bt_info.get('length')
            bt_file_name = bt_info.get('name')
            bt_path[bt_file_name] = bt_file_size
        bt_filename.close()
        print bt_path
        print "Create torrent success"
    else:
        print "Create torrent fail"
        sys.exit(1)
else:
    print "The specified source can not find"
    sys.exit(0)

下面是调用效果图

《利用python开源库制作并验证torrent种子文件》

参考文献

[1].http://wangwei007.blog.51cto.com/68019/1216616

    原文作者:雪峰流云
    原文地址: https://blog.csdn.net/tao_627/article/details/31019919
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞