Nslookup 或挖掘 Google 应用程序脚本

Nslookup or dig in Google App Script

有什么方法可以 运行 在 Google App 脚本中进行 nslookup / dig 吗?我希望在 Google 电子表格中获得此命令的结果。

谢谢

找到一个网络服务,让您可以使用 GET 或 POST 匿名查询 DNS 信息,使用 RESTful API,您将能够使用 UrlFetchApp.fetch() 访问它。

例如,StatDNS 有一个简单的 API。这是一个将域名解析为 IPv4 地址的自定义函数。

代码

/**
 * 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;
}

由于 Mogsdad 建议的服务不再免费,我修改了他的代码以从 Apps 脚本的 https://hackertarget.com/dns-lookup/ with a custom function 获取任何 DNS 注册。

代码

/**
 * 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;
}

我 运行 在可靠地使用这两种方法时遇到了一些问题,尤其是对于 MX 记录。我已经编写了一个简单的后端服务来使用 NodeJS 解析名称。

节点 JS 服务

const http = require('http');
const dns = require('dns');
const url = require('url');
const port = 80;

function reqHandle(req, res) {
  const path = url.parse(req.url, true);
  const type = path.pathname.substring(1);
  if(['A', 'MX', 'NS'].indexOf(type) === -1 || !path.query.q) {
    res.writeHead(500);
    res.write('Unable to determine request type');
    res.end();
    return
  }
  console.log(`Lookup ${type} for ${path.query.q}`);
  dns.resolve(path.query.q, type, (err, v) => {
    res.writeHead(200, {"Content-Type": "application/json"});
    res.write(JSON.stringify({result: v || []}, null, 2));
    res.end();
  });
}

const server = http.createServer(reqHandle);

server.listen(port, '127.0.0.1', (err) => {
  if(err) {
    console.warn("Unable to start server", err);
    return;
  }
  console.log(`Server Listening on port ${port}`);
});

并在 Google 表格的脚本编辑器中使用以下代码(工具 -> 脚本编辑器)。您需要编辑函数以指向您的服务器地址。

/**
 * Peform a Network Service Lookup, using custom 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://my-server-address.com/"+type+"?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 data = JSON.parse(response);
  switch(type) {
    case "A":
    case "NS":
      return data.result.join(' ');
    case "MX":
      return data.result.map(function(v) {return v.exchange}).join(' ');
  }
    throw new Error( "Unsupported query type" );
}

自从 Cloudflare 开始提供 public DNS over HTTPS 后,我想出了一个替代解决方案。

将此应用程序脚本添加到您的 google 工作表,然后使用 NSLookup("goole.com", "A",)

/**
 * Peform a Network Service Lookup, using CloudFlare Public DNS-over-HTTPS 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...
 * @param {true} first         Return first result only, else return all 
 * @return {String}            DNS Lookup Result
 * @customfunction
 */
function NSLookup(dn,type, first) {
  var url = "https://cloudflare-dns.com/dns-query?ct=application/dns-json&name=" + dn + "&type=" + type;
  var result = UrlFetchApp.fetch(url,{muteHttpExceptions:true});
  var rc = result.getResponseCode();
  var response = result.getContentText();
  if (rc !== 200) {
    throw new Error( response.message );
  }
  var resultData = JSON.parse(response);
  var result = [];
  for(var i = 0; i < resultData.Answer.length; i++) {
    result.push(resultData.Answer[i].data);
  }
  if(first) {
    return result.length > 0 ? result[0] : "";
  }
  return result.join(" ");
}

Google Public DNS 提供 API https://dns.google.com/resolve? 可以在 Apps 脚本程序中使用 UrlFetchApp 从 [=24= 获取结果] Public DNS 服务器。

这是示例代码。

function NSLookup() {
  var api_url = 'https://dns.google.com/resolve'; // Google Pubic DNS API Url
  var type = 'MX'; // Type of record to fetch, A, AAAA, MX, CNAME, TXT, ANY
  var name = 'accemy.com'; // The domain name to lookup
  var requestUrl = api_url + '?name=' + name + '&type=' + type; // Build request URL
  var response = UrlFetchApp.fetch(requestUrl); // Fetch the reponse from API
  var responseText = response.getContentText(); // Get the response text

  var json = JSON.parse(responseText); // Parse the JSON text

  var answers = json.Answer.map(function(ans) {
    return ans.data
  }).join('\n'); // Get the values
  return answers;
}

这是我在 Google 表格中使用的代码。它从今天开始工作。它还会抛出正确的错误消息。

function NSLookup(type, domain) {
   
  if (typeof type == 'undefined') {
    throw new Error('Missing parameter 1 dns type');
  }
   
  if (typeof domain == 'undefined') {
    throw new Error('Missing parameter 2 domain name');
  }
  
  type = type.toUpperCase();
   
  var url = 'https://cloudflare-dns.com/dns-query?name=' + encodeURIComponent(domain) + '&type=' + encodeURIComponent(type);
  
  var options = {
    "muteHttpExceptions": true,
    "headers": {
      "accept": "application/dns-json"
    }
  };
  
  var result = UrlFetchApp.fetch(url, options);
  var rc = result.getResponseCode();
  var resultText = result.getContentText();
   
  if (rc !== 200) {
    throw new Error(rc);
  }
  
  var errors = [
    { "name": "NoError", "description": "No Error"}, // 0
    { "name": "FormErr", "description": "Format Error"}, // 1
    { "name": "ServFail", "description": "Server Failure"}, // 2
    { "name": "NXDomain", "description": "Non-Existent Domain"}, // 3
    { "name": "NotImp", "description": "Not Implemented"}, // 4
    { "name": "Refused", "description": "Query Refused"}, // 5
    { "name": "YXDomain", "description": "Name Exists when it should not"}, // 6
    { "name": "YXRRSet", "description": "RR Set Exists when it should not"}, // 7
    { "name": "NXRRSet", "description": "RR Set that should exist does not"}, // 8
    { "name": "NotAuth", "description": "Not Authorized"} // 9
  ];
  
  var response = JSON.parse(resultText);
   
  if (response.Status !== 0) {
    return errors[response.Status].name;
  }
   
  var outputData = [];
   
  for (var i in response.Answer) {
    outputData.push(response.Answer[i].data);
  }
   
  var outputString = outputData.join(',');
   
  return outputString;
   
}

这是 Google 张中的示例输出: