用Python養一隻DHT爬蟲

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實現的爬蟲:

# 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()
相關文章
相關標籤/搜索