這個問題一開始是在要用百度網(wǎng)盤分享文件的時候遇到的。
正常情況下,分享正常的文件自然不會有什么問題,但是有的時候總會遇到一些秒秒鐘被和諧的文件,這個時候我想用度盤離線下載的方式分享會更加可靠~~~
于是就有了后續(xù)——————
要用度盤離線,就得把要分享的文件的種子文件或者磁力鏈拿到。那么我們把要分享的文件制作一遍種子,把種子文件發(fā)給別人,這樣也能達到分享的目的!更為簡單的方法那就是把磁力鏈給別人。以下便是利用python獲取(種子)文件的info hash的方法(不同于網(wǎng)上說的用libtorrent/bencode之類的方法?。?/p>
使用環(huán)境:
Windows 10
已安裝python3.5.1及pip
已配置python系統(tǒng)環(huán)境變量(python命令可以在任何目錄運行)
1.安裝magneturi
pip install magneturi
2.利用py3createtorrent制作種子
項目地址及詳細說明:http://py3createtorrent.readthedocs.io/en/latest/user.html
下載地址:https://bitbucket.org/rsnitsch/py3createtorrent/downloads/

你可以通過以下命令來簡單創(chuàng)建一個種子(注意是一行):
python py3createtorrent.py -p 4096 examplefile.mp4 udp://tracker.openbittorrent.com:80/announce
其中-p 4096是指定分塊為4096KiB,即通常指的4MB。
其中py3createtorrent.py、examplefile.mp4均在當(dāng)前路徑,如果不是請?zhí)鎿Q為絕對路徑。
我把py3createtorrent.py中533行的默認參數(shù)1024改成了4096,以跳過運行時出現(xiàn)
It is strongly recommended to use a maximum piece ?length of 1024 KiB! Do you really want to continue? yes/no:?
執(zhí)行以上命令后便會生成examplefile.mp4的種子文件examplefile.mp4.torrent
3.利用magneturi得到32位的hash(表示并沒有了解這個32位和常用40位info hash的區(qū)別,但是它們可以相互轉(zhuǎn)換)?,F(xiàn)在建立tohash.py,內(nèi)容如下:
#coding=gbk
import magneturi
import base64
import sys
torrentname = sys.argv[1]
mangetlink = magneturi.from_torrent_file(torrentname)
print (mangetlink)
然后執(zhí)行下列代碼:
python tohash.py 20170609中國文藝周末版——向上海美術(shù)制片廠致敬.mp4.torrent

得到的磁力鏈是32位hash的,這和用utorrent等軟件添加任務(wù)復(fù)制的manget鏈接是一樣的,但是基本上不能用于度盤離線,我們需要40位 的info hash。
我們需要對其進行變換,代碼如下:
b32Hash = 'RDFF6W4MZRQCFV4DLICDV4H5VLLDU4SO'
b16Hash = base64.b16encode(base64.b32decode(b32Hash))
b16Hash = b16Hash.lower()
b16Hash = str(b16Hash,"utf-8")
print (b16Hash)
然后可以得到40位的info hash:
88ca5f5b8ccc6022d7835a043af0fdaad63a724e
3.簡便的info hash獲取整合。
基于以上過程,我將各個步驟整合起來,最終可以直接對文件制作種子并得到磁力鏈。
getfhash.py
import sys
import os
import subprocess
fname = sys.argv[1]
os.system('python py3createtorrent.py -p 4096 '+fname+' udp://tracker.openbittorrent.com:80/announce')
os.system('python tohash.py '+fname+'.torrent')

tohash.py
#coding=gbk
#用于獲取種子文件info hash值
import magneturi
import base64
import sys
torrentname = sys.argv[1]
mangetlink = magneturi.from_torrent_file(torrentname)
ch = ''
n = 20
b32Hash = n * ch + mangetlink[20:]
#print (b32Hash)
b16Hash = base64.b16encode(base64.b32decode(b32Hash))
b16Hash = b16Hash.lower()
b16Hash = str(b16Hash,"utf-8")
print ("40位info hash值:"+'\n'+b16Hash)
print ("磁力鏈:"+'\n'+"magnet:?xt=urn:btih:"+b16Hash)

4.演示:
現(xiàn)在py3createtorrent.py、tohash.py、getfhash.py、待獲取info hash的文件都在同一目錄。
(獲取info hash的文件已經(jīng)上傳過百度網(wǎng)盤)

執(zhí)行命令:
python getfhash.py 20170609中國文藝周末版——向上海美術(shù)制片廠致敬.mp4
稍等片刻:

現(xiàn)在需要把種子上傳至百度云,否則后面沒法直接用磁力鏈離線:


現(xiàn)在離線:



5.最后
現(xiàn)在可把info hash告訴別人,補全磁力鏈,這樣就可以起分享作用了!
88ca5f5b8ccc6022d7835a043af0fdaad63a724e
當(dāng)然你也可以分享完整的磁力鏈,不過這在公開的地方容易和諧掉~~~
建議只發(fā)布info hash。
magnet:?xt=urn:btih:88ca5f5b8ccc6022d7835a043af0fdaad63a724e
歡迎指正!