李凡希的Blog | Free as in Freedom

李凡希的Blog | Free as in Freedom

5. 写Python脚本,建假DNS。把下面的内容存为C:\FakeDNS.py。同样,其中的192.168.8.102为A电脑的IP地址,请自行替换

#! /usr/bin/env python
# This code comes from
# http://code.activestate.com/recipes/491264-mini-fake-dns-server/
# with some modifications
import socket

class DNSQuery:
  def __init__(self, data):
    self.data=data
    self.domain=''
    tipo = (ord(data[2]) >> 3) & 15
    if tipo == 0:
      ini=12
      lon=ord(data[ini])
      while lon != 0:
        self.domain+=data[ini+1:ini+lon+1]+'.'
        ini+=lon+1
        lon=ord(data[ini])

  def respuesta(self, ip):
    packet=''
    if self.domain:
      packet+=self.data[:2] + "\x81\x80"
      packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00'
      packet+=self.data[12:]
      packet+='\xc0\x0c'
      packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04'
      packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.')))
    return packet

if __name__ == '__main__':
  udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  udps.bind(('',53))
  try:
    while 1:
      data, addr = udps.recvfrom(1024)
      p = DNSQuery(data)
      if p.domain == 'res.gk.sdo.com.':
        ip = '192.168.8.102'
      else:
        ip = socket.gethostbyname(p.domain)
      udps.sendto(p.respuesta(ip), addr)
      print p.domain + "=>" + ip
  except KeyboardInterrupt:
    udps.close()

6. 启动假DNS

在命行提示符中运行:

C:\Python27\python.exe C:\FakeDNS.py

你可能感兴趣的:(Blog)