爬虫dht
DHT是什么
- DHT全稱叫分布式哈希表(Distributed Hash Table),是一種分布式存儲方法。在不需要服務器的情況下,每個客戶端負責一個小范圍的路由,并負責存儲一小部分數據,從而實現整個DHT網絡的尋址和存儲。
- 各種博客已經有很多關于DHT介紹,這里就不詳細列舉了
加入DHT網絡可以做什么
DHT網絡的其中一種協議實現(Kademlia)
- 要加入一個DHT網絡,需要首先知道這個網絡中的任意一個節點。如何獲得這個節點?在一些開源的P2P軟件中,會提供一些節點地址
- 主要協議
DHT爬蟲的工作原理
爬蟲做的工作
使用Python實現的爬蟲:
# coding: utf-8import 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[轉載于:https://www.cnblogs.com/mamatichong/p/9952255.html
總結
- 上一篇: python车辆型号识别_基于Tenso
- 下一篇: dht网络协议 服务器,概述DHT网络