查询域名的小程序

"""
File: dns.py
Author: timium@hotmail.com
From: http://blog.csdn.net/timium
"""

from socket import *
import string, os, sys, shutil
from time import time

class whoisserver:
    def __init__(self):
        self.timeout=20
       
    def _query(self, d):
        d,cc = d.split('.')
        s = socket(AF_INET, SOCK_STREAM)
        s.settimeout(self.timeout)
        s.connect((cc+'.whois-servers.net',43))
        s.send(d+'.'+cc+'/r/n')
        r=''
        while True:
            rr=s.recv(1024)
            r+=rr
            if rr=='':
                break
        s.close()           
        return r

    def query(self,d):
        retry = 2
        timeout = self.timeout
        while True:
            try:
                txt = self._query(d)
                return txt
            except Exception,e:
                retry -= 1
                if retry==0:
                    raise e
                timeout += self.timeout

    def get_valid_text(self, txt):
        return txt[:txt.find('>>>')]

    def query_available(self, d):
        txt = self.query(d)
        #todo: different server may return different result format
        return txt.find('No match for')!=-1

    def query_text(self, d):
        try:
            txt = self.query(d)
            return self.get_valid_text(txt)
        except Exception,e:
            return 'ERROR ' + str(e)

def lookup(d, cc=None):
    if cc==None and d.find('.')!=-1:
        d,cc = d.split('.')
    s = socket(AF_INET, SOCK_STREAM)
    s.settimeout(12)
    print 1,
    s.connect((cc+'.whois-servers.net',43))
    print 2,
    s.send(d+'.'+cc+'/r/n')
    print 3,
    r=''
    while True:
        rr=s.recv(1024)
        r+=rr
        if rr=='':
            break
    s.close()           
    print 4,'........',
    return r.find('No match for')!=-1

"""
source:      xxx.xxx
todo:        xxx.xxx.res
availabe:    xxx.xxx.good
error        xxx.xxx.error
"""
def batch(pn):
    namefile,todofile,goodfile,badfile = map(lambda x:pn+x, ['','.res','.good','.error'])
   
    # read names
    if not os.path.exists(todofile):
        shutil.copy(namefile, todofile)
        #os.popen('copy %s %s'%(namefile,todofile)).read()
       
    ds=open(todofile).read().split('/n')

    # read from error files

    # read processed
    good=[]
    bad=[]
    i=0

    st=time()
    try:
        for i in range(0, len(ds)):
            print i,'/t',ds[i],'............',
            try:
                if lookup(ds[i]):
                    good.append(ds[i])
                    print 'OK'
            except Exception,e:
                if e.__class__.__name__=='KeyboardInterrupt':
                    print 'Cancel'
                    raise e
                bad.append(ds[i])
                print 'ERR'
            print ''
    except Exception,e:
        print 'Canceled by user. Current:',ds[i], '(',i,'/',len(ds),')'
        i-=1
    et=time()
    pc=i+1
    print 'searched:',pc,', used time:',(et-st),'s, average:',(et-st)/pc,'s'
   
    open(todofile,'w').write('/n'.join(ds[i+1:]))
    print len(good),'domains available,', len(bad),'error'
    open(goodfile,'a').write('/n'.join(good)+'/n')
    open(badfile,'a').write('/n'.join(bad)+'/n')

def console():
    ws=whoisserver()
    while True:
        cmd = raw_input('>>>')
        if 'x'==cmd: break
        try:
            #value = eval(cmd)
            value=cmd.strip()
        except Exception,e:
            print e
            break

        if cmd.find('.')==-1:
            cmd += '.com'
        t=ws.query_text(cmd)
        print t
       
if __name__ == '__main__':
    if len(sys.argv)==1:
        console()
    else:
        pn=sys.argv[1]
        batch(pn)
        raw_input("Press any key to continue...")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值