In questo articolo vedremo come effettuare query DNS con Python usando le API di Google.
Dopo aver installato il modulo requests abbiamo bisogno di passare come parametri della richiesta GET il nome dell'host e il tipo di record DNS.
import requests
def get_dns_records(hostname=None, record_type='A'):
if hostname is None:
return None
api_url = 'https://dns.google.com/resolve?'
params = {'name': hostname, 'type': record_type}
try:
response = requests.get(api_url, params=params)
return response.json()
except requests.exceptions.RequestException:
return None
Le API di Google restituiranno un output JSON con le informazioni relative alla nostra richiesta. Esempio d'uso:
def main():
host = input('Enter host name:')
record = input('Enter record type: ')
print(get_dns_records(host, record))
if __name__ == '__main__':
main()
Possibile output:
Enter host name:gabrieleromanato.com
Enter record type: NS
{'Status': 0, 'TC': False, 'RD': True, 'RA': True, 'AD': False, 'CD': False, 'Question': [{'name': 'gabrieleromanato.com.', 'type': 2}], 'Answer': [{'name': 'gabrieleromanato.com.', 'type': 2, 'TTL': 1800, 'data': 'pdns1.registrar-servers.com.'}, {'name': 'gabrieleromanato.com.', 'type': 2, 'TTL': 1800, 'data': 'pdns2.registrar-servers.com.'}], 'Comment': 'Response from 2610:a1:1025::100.'}