Nslookup或挖掘Google App Script

时间:2015-06-02 19:24:53

标签: google-apps-script google-sheets nslookup dig

有没有办法在Google App Script中运行nslookup / dig?我希望在Google电子表格中获得此命令的结果。

由于

6 个答案:

答案 0 :(得分:3)

找一个允许您使用RESTful API匿名使用GET或POST来查询DNS信息的Web服务,并且您将能够使用UrlFetchApp.fetch()来访问它。

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

screenshot

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

答案 1 :(得分:2)

由于Mogsdad建议的服务不再免费,我已对其代码进行了修改,以便使用https://hackertarget.com/dns-lookup/的应用脚本从custom function获取任何DNS注册。

<强>码

eval

答案 2 :(得分:1)

Google Public DNS提供https://dns.google.com/resolve?的API,可与UrlFetchApp一起在Apps脚本程序中使用,以从Google Public DNS Server获取结果。

这是示例代码。

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

答案 3 :(得分:1)

这是我在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表格中的示例输出:

screenshot

答案 4 :(得分:0)

我在使用这两个问题时遇到了一些问题,特别是对于MX Records。我编写了一个简单的后端服务来使用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表格(工具 - &gt;脚本编辑器)的脚本编辑器中使用以下代码。您需要编辑该功能以指向您的服务器地址。

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

答案 5 :(得分:0)

自Cloudflare开始通过HTTPS提供公共DNS以来,我提出了另一种解决方案。

将此应用脚本添加到您的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(" ");
}