使用自定义后端的Python DNS服务器
有没有用Python写的DNS服务器,我可以很方便地使用自己的后台?
其实,我就是想为一些域名提供我自己的IP地址的查询结果,但其他的查询就交给真正的DNS服务器处理。
3 个回答
4
很多人会建议你用Twisted来写这个,并且加一些自定义的功能,这样你就可以自己回答请求了。如果你想了解更多,可以看看这些链接:
http://twistedmatrix.com/documents/10.1.0/names/howto/names.html
http://twistedmatrix.com/documents/10.1.0/api/twisted.names.dns.DNSDatagramProtocol.html
5
其实,我发现了一种更简单的方法:使用PowerDNS和管道后端。
http://doc.powerdns.com/pipebackend-dynamic-resolution.html
http://doc.powerdns.com/backends-detail.html#PIPEBACKEND
只需安装PowerDNS服务器,写一个小脚本把请求转发到你的服务器,这样就完成了。
13
我最近写了一个这样的东西,也许你可以把它当作一个例子。它使用了一个DHT作为后端,并在那里面查找所有的.kad域名。如果你简单地把P2PMapping
替换成你自己的映射(比如一个字典,像{'google.com' : '127.0.0.1'}
),它应该就能实现你想要的功能。
"""
Created on 16.08.2010
@author: Jochen Ritzel
"""
import dht
from twisted.names import dns, server, client, cache
from twisted.application import service, internet
class P2PMapping(dht.EntangledDHT):
def __contains__(self, key):
return key.endswith('.kad')
class MapResolver(client.Resolver):
"""
Resolves names by looking in a mapping.
If `name in mapping` then mapping[name] should return a IP
else the next server in servers will be asked for name
"""
def __init__(self, mapping, servers):
self.mapping = mapping
client.Resolver.__init__(self, servers=servers)
self.ttl = 10
def lookupAddress(self, name, timeout = None):
# find out if this is a .kad. request
if name in self.mapping:
result = self.mapping[name] # get the result
def packResult( value ):
return [
(dns.RRHeader(name, dns.A, dns.IN, self.ttl, dns.Record_A(value, self.ttl)),), (), ()
]
result.addCallback(packResult) # put it in a A Record
return result
else:
return self._lookup(name, dns.IN, dns.A, timeout)
## this sets up the application
application = service.Application('dnsserver', 1, 1)
## set up the DHT
mapping = P2PMapping(bootstrap=[('127.0.0.1', 4001)])
mapping['jochen.kad'] = '99.99.99.99' # "register" domain with IP
# set up a resolver that uses the mapping or a secondary nameserver
p2presolver = MapResolver(mapping, servers=[('192.168.178.1', 53)])
# create the protocols
f = server.DNSServerFactory(caches=[cache.CacheResolver()], clients=[p2presolver])
p = dns.DNSDatagramProtocol(f)
f.noisy = p.noisy = False
# register as tcp and udp
ret = service.MultiService()
PORT=53
for (klass, arg) in [(internet.TCPServer, f), (internet.UDPServer, p)]:
s = klass(PORT, arg)
s.setServiceParent(ret)
# run all of the above as a twistd application
ret.setServiceParent(service.IServiceCollection(application))
# run it through twistd!
if __name__ == '__main__':
import sys
print "Usage: twistd -y %s" % sys.argv[0]