Neurohazard
暮雲煙月,皓首窮經;森羅萬象,如是我聞。

批量域名 DNS 解析脚本

wpadmin~June 4, 2019 /System Management

批量域名 DNS 解析脚本

正文

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time    : 5/7/2019 2:49 PM
# Author  : BLKStone
# Site    : http://wp.blkstone.me
# File    : dns_resolve.py
# Software:  PyCharm


import socket
import csv

def dns_query(domain):
    # your os sends out a dns query
    ip = socket.gethostbyname(domain)
    res = (domain, ip)
    return res

def load_file(path):
    domain_list = []
    with open(path, 'r') as f:
        for line in f.readlines():
            row = line.strip()
            domain_list.append(row)
    return domain_list


def quick_write(res_matrix):

    with open('dns_resolve_2.csv', 'w') as f:
        for row in res_matrix:
            col_number = len(row)
            line = str(row[0])
            for i in range(col_number-1):
                line = line + ',' + row[i+1]
            line = line + '\n'
            print(line)
            f.write(line)

def csv_write(res_matrix):

    csv.register_dialect('Dialect_1',
                         delimiter=',',
                         quoting=csv.QUOTE_NONE,
                         skipinitialspace=False)

    with open('dns_resolve.csv', 'w') as f:
        writer = csv.writer(f, dialect='Dialect_1')
        writer.writerows(res_matrix)
    f.close()



def main():
    # path = 'D:\\pydev\\vtest\\logs\\20190507_domain.txt'
    # path = 'D:\\pydev\\vtest\\logs\\20190506_domain_2.txt'
    # path = 'D:\\pydev\\vtest\\logs\\20190509_domain_2.txt'
    path = "D:\\pydev\\vtest\\logs\\20190513_domain_2.txt"
    filename = 'res.csv'


    domain_list = load_file(path)

    # 构造结果矩阵
    res_matrix = []
    for domain in domain_list:
        print("Resolve {domain}".format(domain=domain))
        try:
            res = dns_query(domain)
        except Exception as e:
            res = (domain, 'unknown')
        print(res)
        row = [res[0], res[1]]
        res_matrix.append(row)

    quick_write(res_matrix)


if __name__ == '__main__':
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *