python DHT網路爬蟲

大囚長發表於2019-02-14
DHT是什麼
  • DHT全稱叫分散式雜湊表(Distributed Hash Table),是一種分散式儲存方法。在不需要伺服器的情況下,每個客戶端負責一個小範圍的路由,並負責儲存一小部分資料,從而實現整個DHT網路的定址和儲存。
  • 各種部落格已經有很多關於DHT介紹,這裡就不詳細列舉了
加入DHT網路可以做什麼
  1. 老司機開車(神祕程式碼)
  2. P2P資源共享
DHT網路的其中一種協議實現(Kademlia)
  • 要加入一個DHT網路,需要首先知道這個網路中的任意一個節點。如何獲得這個節點?在一些開源的P2P軟體中,會提供一些節點地址
  • 主要協議
  1. ping(用於確定某個節點是否線上。這個請求主要用於輔助路由表的更新)
  2. find_node(用於查詢某個節點,以獲得其地址資訊。)
  3. get_peer(通過資源的infohash獲得資源對應的peer列表。)
  4. announce_peer(通知其他節點自己開始下載某個資源,announce_peer中會攜帶get_peer回應訊息裡的token。)
DHT爬蟲的工作原理
  1. 通過其他節點的announce_peer發來的infohash確認網路中有某個資源可被下載
  2. 通過從網路中獲取這個資源的種子檔案,來獲得該資源的描述
  3. 不停的認識新節點,讓遠端節點儲存自身到遠端的路由表中
爬蟲做的工作
  1. BOOTSTRAP過程,加入DHT網路(主動認識DHT網路的其中一個節點)
  2. 加入進DHT網路後。遠端節點會主動告訴我們它認識哪些節點
  3. 認識遠端節點認識的節點
  4. 當遠端成功儲存自身節點到遠端路由表中的時候,目的達成
  5. 等待遠端的announce_peer訊息
  6. 成功獲取遠端的下載hash
  7. 開車
python DHT爬蟲
# coding: utf-8

import socket
from hashlib import sha1
from random import randint
from struct import unpack, pack
from socket import inet_aton, inet_ntoa
from bisect import bisect_left
from threading import Timer
# from time import sleep

from bencode import bencode, bdecode

BOOTSTRAP_NODES = [
    ("router.bittorrent.com", 6881),
    ("dht.transmissionbt.com", 6881),
    ("router.utorrent.com", 6881)
] 
TID_LENGTH = 4
KRPC_TIMEOUT = 10
REBORN_TIME = 5 * 60
K = 8

def entropy(bytes):
    s = ""
    for i in range(bytes):
        s += chr(randint(0, 255))
    return s

    # """把爬蟲"偽裝"成正常node, 一個正常的node有ip, port, node ID三個屬性, 因為是基於UDP協議,     
    # 所以向對方傳送資訊時, 即使沒"明確"說明自己的ip和port時, 對方自然會知道你的ip和port,     
    # 反之亦然. 那麼我們自身node就只需要生成一個node ID就行, 協議裡說到node ID用sha1演算法生成,     
    # sha1演算法生成的值是長度是20 byte, 也就是20 * 8 = 160 bit, 正好如DHT協議裡說的那範圍: 0 至 2的160次方,     
    # 也就是總共能生成1461501637330902918203684832716283019655932542976個獨一無二的node.     
    # ok, 由於sha1總是生成20 byte的值, 所以哪怕你寫SHA1(20)或SHA1(19)或SHA1("I am a 2B")都可以,     
    # 只要保證大大降低與別人重複機率就行. 注意, node ID非十六進位制,     
    # 也就是說非FF5C85FE1FDB933503999F9EB2EF59E4B0F51ECA這個樣子, 即非hash.hexdigest(). """
def random_id():
    hash = sha1()
    hash.update( entropy(20) )
    return hash.digest()

def decode_nodes(nodes):
    n = []
    length = len(nodes)
    if (length % 26) != 0: 
        return n
    for i in range(0, length, 26):
        nid = nodes[i:i+20]
        ip = inet_ntoa(nodes[i+20:i+24])
        port = unpack("!H", nodes[i+24:i+26])[0]
        n.append( (nid, ip, port) )
    return n

def encode_nodes(nodes):
    strings = []
    for node in nodes:
        s = "%s%s%s" % (node.nid, inet_aton(node.ip), pack("!H", node.port))
        strings.append(s)

    return "".join(strings)

def intify(hstr):
    #"""這是一個小工具, 把一個node ID轉換為數字. 後面會頻繁用到.""" 
    return long(hstr.encode('hex'), 16) #先轉換成16進位制, 再變成數字

def timer(t, f):
    Timer(t, f).start()


class BucketFull(Exception):
    pass


class KRPC(object):
    def __init__(self):
        self.types = {
            "r": self.response_received,
            "q": self.query_received
        }
        self.actions = {
            "ping": self.ping_received,
            "find_node": self.find_node_received,
            "get_peers": self.get_peers_received,
            "announce_peer": self.announce_peer_received,
        }

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(("0.0.0.0", self.port))

    def find_node_handler(self,msg):
        pass

    def response_received(self, msg, address):
        self.find_node_handler(msg)

    def query_received(self, msg, address):
        try:
            self.actions[msg["q"]](msg, address)
        except KeyError:
            pass

    def send_krpc(self, msg, address):
        try:
            self.socket.sendto(bencode(msg), address)
        except:
            pass


class Client(KRPC):
    def __init__(self, table):
        self.table = table

        timer(KRPC_TIMEOUT, self.timeout)
        timer(REBORN_TIME, self.reborn)
        KRPC.__init__(self)

    def find_node(self, address, nid=None):
        print "find node:",address
        nid = self.get_neighbor(nid) if nid else self.table.nid
        tid = entropy(TID_LENGTH)
        
        msg = {
            "t": tid,
            "y": "q",
            "q": "find_node",
            "a": {"id": nid, "target": random_id()}
        }
        self.send_krpc(msg, address)

    def find_node_handler(self, msg):
        try:
            nodes = decode_nodes(msg["r"]["nodes"])
            for node in nodes:
                (nid, ip, port) = node
                if len(nid) != 20: continue
                if nid == self.table.nid: continue
                self.find_node( (ip, port), nid )
        except KeyError:
            pass

    def joinDHT(self):
        for address in BOOTSTRAP_NODES: 
            self.find_node(address)

    def timeout(self):
        if len( self.table.buckets ) < 2:
            self.joinDHT()
        timer(KRPC_TIMEOUT, self.timeout)

    def reborn(self):
        self.table.nid = random_id()
        self.table.buckets = [ KBucket(0, 2**160) ]
        timer(REBORN_TIME, self.reborn)

    def start(self):
        self.joinDHT()

        while True:
            try:
                (data, address) = self.socket.recvfrom(65536)
                msg = bdecode(data)
                self.types[msg["y"]](msg, address)
            except Exception:
                pass

    def get_neighbor(self, target):
        return target[:10]+random_id()[10:]


class Server(Client):
    def __init__(self, master, table, port):
        self.table = table
        self.master = master
        self.port = port
        Client.__init__(self, table)

    def ping_received(self, msg, address):
        try:
            nid = msg["a"]["id"]
            msg = {
                "t": msg["t"],
                "y": "r",
                "r": {"id": self.get_neighbor(nid)}
            }
            self.send_krpc(msg, address)
            self.find_node(address, nid)
        except KeyError:
            pass

    def find_node_received(self, msg, address):
        try:
            target = msg["a"]["target"]
            neighbors = self.table.get_neighbors(target)
            
            nid = msg["a"]["id"]
            msg = {
                "t": msg["t"],
                "y": "r",
                "r": {
                    "id": self.get_neighbor(target), 
                    "nodes": encode_nodes(neighbors)
                }
            }
            self.table.append(KNode(nid, *address))
            self.send_krpc(msg, address)
            self.find_node(address, nid)
        except KeyError:
            pass

    def get_peers_received(self, msg, address):
        try:
            infohash = msg["a"]["info_hash"]

            neighbors = self.table.get_neighbors(infohash)

            nid = msg["a"]["id"]
            msg = {
                "t": msg["t"],
                "y": "r",
                "r": {
                    "id": self.get_neighbor(infohash), 
                    "nodes": encode_nodes(neighbors)
                }
            }
            self.table.append(KNode(nid, *address))
            self.send_krpc(msg, address)
            self.master.log(infohash)
            self.find_node(address, nid)
        except KeyError:
            pass

    def announce_peer_received(self, msg, address):
        try:
            infohash = msg["a"]["info_hash"]
            nid = msg["a"]["id"]

            msg = { 
                "t": msg["t"],
                "y": "r",
                "r": {"id": self.get_neighbor(infohash)}
            }

            self.table.append(KNode(nid, *address))
            self.send_krpc(msg, address)
            self.master.log(infohash)
            self.find_node(address, nid)
        except KeyError:
            pass
# 該類只例項化一次. 
class KTable(object):
    # 這裡的nid就是通過node_id()函式生成的自身node ID. 協議裡說道, 每個路由表至少有一個bucket,     
 #  還規定第一個bucket的min=0, max=2^160次方, 所以這裡就給予了一個buckets屬性來儲存bucket, 這個是列表.
    def __init__(self, nid):
        self.nid = nid
        self.buckets = [ KBucket(0, 2**160) ]

    def append(self, node):
        index = self.bucket_index(node.nid)
        try:
            bucket = self.buckets[index]
            bucket.append(node)
        except IndexError:
            return
        except BucketFull:
            if not bucket.in_range(self.nid): 
                return
            self.split_bucket(index)
            self.append(node)


        # 返回與目標node ID或infohash的最近K個node.    
 
        # 定位出與目標node ID或infohash所在的bucket, 如果該bucuck有K個節點, 返回.     
        # 如果不夠到K個節點的話, 把該bucket前面的bucket和該bucket後面的bucket加起來, 只返回前K個節點.    
        # 還是不到K個話, 再重複這個動作. 要注意不要超出最小和最大索引範圍.    
        # 總之, 不管你用什麼演算法, 想盡辦法找出最近的K個節點.    
    def get_neighbors(self, target):
        nodes = []
        if len(self.buckets) == 0: return nodes
        if len(target) != 20 : return nodes

        index = self.bucket_index(target)
        try:
            nodes = self.buckets[index].nodes
            min = index - 1
            max = index + 1

            while len(nodes) < K and ((min >= 0) or (max < len(self.buckets))):
                if min >= 0:
                    nodes.extend(self.buckets[min].nodes)

                if max < len(self.buckets):
                    nodes.extend(self.buckets[max].nodes)

                min -= 1
                max += 1

            num = intify(target)
            nodes.sort(lambda a, b, num=num: cmp(num^intify(a.nid), num^intify(b.nid)))
            return nodes[:K] #K是個常量, K=8 
        except IndexError:
            return nodes

    def bucket_index(self, target):
        return bisect_left(self.buckets, intify(target))


        # 拆表    
 
        # index是待拆分的bucket(old bucket)的所在索引值.     
        # 假設這個old bucket的min:0, max:16. 拆分該old bucket的話, 分界點是8, 然後把old bucket的max改為8, min還是0.     
        # 建立一個新的bucket, new bucket的min=8, max=16.    
        # 然後根據的old bucket中的各個node的nid, 看看是屬於哪個bucket的範圍裡, 就裝到對應的bucket裡.     
        # 各回各家,各找各媽.    
        # new bucket的所在索引值就在old bucket後面, 即index+1, 把新的bucket插入到路由表裡. 
    def split_bucket(self, index):
        old = self.buckets[index]
        point = old.max - (old.max - old.min)/2
        new = KBucket(point, old.max)
        old.max = point
        self.buckets.insert(index + 1, new)
        for node in old.nodes[:]:
            if new.in_range(node.nid):
                new.append(node)
                old.remove(node)

    def __iter__(self):
        for bucket in self.buckets:
            yield bucket


class KBucket(object):
    __slots__ = ("min", "max", "nodes")

    # min和max就是該bucket負責的範圍, 比如該bucket的min:0, max:16的話,     
    # 那麼儲存的node的intify(nid)值均為: 0到15, 那16就不負責, 這16將會是該bucket後面的bucket的min值.     
    # nodes屬性就是個列表, 儲存node. last_accessed代表最後訪問時間, 因為協議裡說到,     
    # 當該bucket負責的node有請求, 回應操作; 刪除node; 新增node; 更新node; 等這些操作時,     
    # 那麼就要更新該bucket, 所以設定個last_accessed屬性, 該屬性標誌著這個bucket的"新鮮程度". 用linux話來說, touch一下.    
    # 這個用來便於後面說的定時重新整理路由表.    

    def __init__(self, min, max):
        self.min = min
        self.max = max
        self.nodes = []


    # 新增node, 引數node是KNode例項.    

    # 如果新插入的node的nid屬性長度不等於20, 終止.    
    # 如果滿了, 丟擲bucket已滿的錯誤, 終止. 通知上層程式碼進行拆表.    
    # 如果未滿, 先看看新插入的node是否已存在, 如果存在, 就替換掉, 不存在, 就新增,    
    # 新增/替換時, 更新該bucket的"新鮮程度".    
    def append(self, node):
        if node in self:
            self.remove(node)
            self.nodes.append(node)
        else:
            if len(self) < K:
                self.nodes.append(node)
            else:
                raise BucketFull

    def remove(self, node):
        self.nodes.remove(node)

    def in_range(self, target):
        return self.min <= intify(target) < self.max

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, node):
        return node in self.nodes

    def __iter__(self):
        for node in self.nodes:
            yield node

    def __lt__(self, target):
        return self.max <= target


class KNode(object):
     # """    
    #        nid就是node ID的簡寫, 就不取id這麼模糊的變數名了. __init__方法相當於別的OOP語言中的構造方法,     
    #        在python嚴格來說不是構造方法, 它是初始化, 不過, 功能差不多就行.    
    #        """ 
    __slots__ = ("nid", "ip", "port")
    
    def __init__(self, nid, ip, port):
        self.nid = nid
        self.ip = ip
        self.port = port

    def __eq__(self, other):
        return self.nid == other.nid



#using example
class Master(object):
    def __init__(self, f):
        self.f = f
        self.hashArr = []

    def log(self, infohash):
        nhash = infohash.encode("hex")
        if nhash not in self.hashArr:
            self.hashArr.append(nhash)
            self.f.write(+"\n")
            self.f.flush()
try:
    print "start DHT Spider"
    f = file("hash.txt","a+")
    m = Master(f)
    s = Server(Master(f), KTable(random_id()), 6881)
    s.start()    
except KeyboardInterrupt:
    s.socket.close()
    f.close()

相關文章