The company recently took over the project of a multinational enterprise, the enterprise single-domain, multi-site, and in the United States, Brazil, Japan, Tokyo, Singapore and other countries, the number of servers and client computers is huge. Due to the processing of some special faults, need to find out some of the network devices not in the domain and storage, NBU, and so on in the DNS server for forward parsing and reverse resolution of the records, manual view is limited to a large number of can not be implemented, so think of writing a Python script.
First, function Description:
1. Divided into two functions, forward parsing and reverse parsing
2. Forward parsing the query, according to the file written in the device or machine name, query the IP address, and open host-ip.txt, in HOST->IP format to write to the file, can not be resolved, using Host->nofound write.
3. Reverse parse query, according to the query result file Host->ip.txt in forward parsing, intercept the IP address part, and then write to the file in ip->host format, cannot parse, or use Ip-nofound write.
Second, the Code
Importsocketho_list= []#The name of the machine used to hold the contents of the file read, list typeWith open ('Hostna.txt','R') as F1: forIinchf1.readlines ():#print (i)Ho_list.append (I.strip ())Print(Ho_list) with open ('Host-ip.txt','W') as F2: forHostinchho_list:Print(host)Try: IP= Socket.getaddrinfo (Host,none) [0][4][0]#keep only the IP part #print (IP)F2.write (host+' -'+ip+'\ n') exceptException as E:#some can not forward the resolution of the device error, to ensure that the program runs normally Print('cannot lookup') F2.write (host+' -'+'Nofound'+'\ n') Continue
forward parsing
Importsocketip_list= []#used to save the IP address portion of the Read file, type listWith open ('Host-ip.txt','R') as F1: forIinchf1.readlines (): SP= I.split (' -') [1] #Print (I.split (') [1])Ip_list.append (Sp.strip ())#print (ip_list)With open ('Ip-host.txt','W') as F2: forIinchip_list:Print(i)ifi = ='Nofound': Continue Else: Try: Host= Socket.gethostbyaddr (i) [0]#take host name only partF2.write (i +' -'+ STR (host) +'\ n') exceptSocket.herror as E:f2.write (i+' -'+'Nofound'+'\ n')
Reverse parsing
Iii. Results
Forward parsing: Host-ip.txt
Servername->xxx.xxx.xxx.xxx
Reverse parsing: Ip-host.txt172.xxx.xxx.xxx->bogon
Python3.6 forward parsing and reverse parsing a host in a domain