[python网络编程]DNSserver
生活随笔
收集整理的這篇文章主要介紹了
[python网络编程]DNSserver
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在上一篇中,使用scrapy改動源IP發送請求的最后我們提到因為hosts文件不支持正則,會導致我們的隨機域名DNS查詢失敗。
使用DNS代理服務器能夠解決問題,
以下是我用gevent寫的小工具。非常easy。我們僅僅攔截匹配的A記錄。然后發送DNS Response,假設不匹配,那么我們服務器就是一個DNS代理,轉發請求。
# -*- coding=utf-8 -*- import struct from cStringIO import StringIO from collections import namedtuple from gevent import socket from gevent.server import DatagramServerHex = lambda x : '0x{0:04x}'.format(x) # Hex(256) => "0x0100"QueryResult = namedtuple("DnsQuery","transactionID,flags,questions,answerRrs \authorityRrs,additionalRrs,qname,qtype,qclass" )LOCALDNS = ("114.114.114.114",53)Hosts = {"*.ttt.com":"173.194.127.144", # google ip }def preg_match(preg,real):"""only support '*'>>>preg_match("www.*.test*.com","www.python.test.com")True>>>preg_match("www.*.test*.com","www.python.tes.com")False"""pre = 0for s in preg.split('*'):now = real.find(s)if now < pre:return Falsepre = now +len(s)return Truedef udp_send(address,data):sock = socket.socket(type=socket.SOCK_DGRAM)sock.connect(address)sock.send(data)response, address = sock.recvfrom(8192*4)return response,addressclass DnsParser:@classmethoddef parseQuery(self,query):"""6a 02 01 00 00 01 j.....00 00 00 00 00 00 03 77 77 77 03 61 61 61 03 63 .......www.aaa.c6f 6d 00 00 01 00 01 om.....dns query package like above03 77 77 77 : three www"""transactionID,flags,questions,answerRrs,authorityRrs,additionalRrs = map(Hex,struct.unpack("!6H",query[:12]))quries = StringIO(query[12:])c = struct.unpack("!c",quries.read(1))[0]domain = []while c != '\x00':n = ord(c)domain.append(''.join(struct.unpack("!%sc" % n,quries.read(ord(c)))))c = struct.unpack("!c",quries.read(1))[0]domain = '.'.join(domain)qtype,qclass = map(Hex,struct.unpack("!2H",quries.read()))return QueryResult(transactionID,flags,questions,answerRrs,authorityRrs,additionalRrs,domain,qtype,qclass)@classmethoddef generateReqponse(self,queryData,ip):"""only support ipv4"""return ''.join([queryData[:2],"\x81\x80\x00\x01\x00\x02\x00\x00\x00\x00",queryData[12:],"\xc0\x0c","\x00\x01","\x00\x01","\x00\x00\x00\x1e","\x00\x04",struct.pack('BBBB',*map(int,ip.split('.')))])class DnsServer(DatagramServer):def handle(self,data,address):query = DnsParser.parseQuery(data)print "get dns query from %s,query:%s" %(str(address),str(query))find = Falsefor preg,ip in Hosts.iteritems():if preg_match(preg,query.qname):find = Truebreakif find and query.qtype == "0x0001": #only handle A recordprint 'domain:%s in hosts' % query.qnameresponse = DnsParser.generateReqponse(data,ip)self.socket.sendto(response,address)else:print 'transfer for %s' % query.qnameresponse,serveraddress = udp_send(LOCALDNS,data)self.socket.sendto(response,address)if __name__ == "__main__":DnsServer("192.168.9.178:53").serve_forever()哈哈,剛好100行,不得不說python的強大。
來個截圖:
功能有限。各位童鞋能夠擴展,代碼已經放到github,https://github.com/Skycrab/PyDnsProxy,有興趣的童鞋一起完好。
總結
以上是生活随笔為你收集整理的[python网络编程]DNSserver的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Fedora升级到4.3.4内核后vir
- 下一篇: CDH5之Unexpected erro