Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nslookup or dig in Google App Script

Is there any way to run an nslookup / dig in Google App Script? I m looking to get the results of this command in a Google Spreadsheet.

Thanks

like image 304
Yannis Avatar asked Dec 10 '22 22:12

Yannis


2 Answers

Find a web service that will let you use a GET or POST anonymously to query DNS info using a RESTful API, and you'll be able to use UrlFetchApp.fetch() to access it.

For example, StatDNS has a simple API. Here's a custom function that will resolve a Domain Name to IPv4 Address.

screenshot

code

/**
 * Peform a Network Service Lookup, using StatDNS API.
 *
 * @param {"google.com"} dn    A well-formed domain name to resolve.
 * @return {String}            Resolved IP address
 * @customfunction
 */
function NSLookup(dn) {
  var url = "http://api.statdns.com/%FQDN%/a".replace("%FQDN%",dn);
  var result = UrlFetchApp.fetch(url,{muteHttpExceptions:true});
  var rc = result.getResponseCode();
  var response = JSON.parse(result.getContentText());
  if (rc !== 200) {
    throw new Error( response.message );
  }
  var ip = response.answer[0].rdata;
  return ip;
}
like image 137
Mogsdad Avatar answered Dec 28 '22 07:12

Mogsdad


Since Mogsdad's suggested service is no longer free, I've made a modification of his code to fetch any DNS register from https://hackertarget.com/dns-lookup/ with a custom function of Apps Script.

code

/**
 * Peform a Network Service Lookup, using hackertarget API.
 *
 * @param {"google.com"} dn    A well-formed domain name to resolve.
 * @param {"A"} type           Type of data to be returned, such as A, AAA, MX, NS...
 * @return {String}            Resolved IP address
 * @customfunction
 */
function NSLookup(dn,type) {
  var url = "http://api.hackertarget.com/dnslookup/?q=" + dn;
  var result = UrlFetchApp.fetch(url,{muteHttpExceptions:true});
  var rc = result.getResponseCode();
  var response = result.getContentText();
  if (rc !== 200) {
    throw new Error( response.message );
  }
  //var resp = response.answer[0].rdata;
  var registers = response.split("\n");
  var register;
  var arrayLength;  // Not all queries return the same number of items
  var result = "";
  for (var i in registers) {
    register = registers[i].split("\t");
    arrayLength = register.length;
    if (register[arrayLength - 2] == type) {
      result = register[arrayLength - 1];
      break;
    }
  }
  return result;
}
like image 37
Miguel Jiménez Avatar answered Dec 28 '22 05:12

Miguel Jiménez