← 1.1.1.1 (DNS-резолвер) / 1.1.1.1 / additional-options
DNS в Google Sheets
Создание функции
В этом руководстве создаётся пользовательская функция Google Sheets, которая обращается к DNS-резолверу Cloudflare 1.1.1.1 по протоколу DNS over HTTPS (DoH): он шифрует DNS-запросы поверх HTTPS. После настройки вы сможете ввести формулу вида =NSLookup("A", "example.com") в любой ячейке, чтобы получить записи DNS, не покидая таблицу. Это удобно для массового аудита доменов, планирования миграции или отслеживания изменений DNS сразу по многим доменам.
Для начала откройте таблицу Google Sheets и создайте пользовательская функция в Google Apps Script ↗ следующим кодом:
function NSLookup(type, domain, useCache = false, minCacheTTL = 30) {
// --- Parameter validation ---
if (typeof type == "undefined") {
throw new Error("Missing parameter 1 dns type");
}
if (typeof domain == "undefined") {
throw new Error("Missing parameter 2 domain name");
}
if (typeof useCache != "boolean") {
throw new Error("Only boolean values allowed in 3 use cache");
}
if (typeof minCacheTTL != "number") {
throw new Error("Only numeric values allowed in 4 min cache ttl");
}
type = type.toUpperCase();
domain = domain.toLowerCase();
// --- Optional caching layer (uses Google Apps Script CacheService) ---
let cache = null;
if (useCache) {
// Cache key and hash
cacheKey = domain + "@" + type;
cacheHash = Utilities.base64Encode(cacheKey);
cacheBinKey = "nslookup-result-" + cacheHash;
cache = CacheService.getScriptCache();
const cachedResult = cache.get(cacheBinKey);
if (cachedResult != null) {
return cachedResult;
}
}
// --- DNS-over-HTTPS query to Cloudflare's 1.1.1.1 resolver ---
const url =
"https://cloudflare-dns.com/dns-query?name=" +
encodeURIComponent(domain) +
"&type=" +
encodeURIComponent(type);
const options = {
muteHttpExceptions: true,
headers: {
accept: "application/dns-json",
},
};
const result = UrlFetchApp.fetch(url, options);
const rc = result.getResponseCode();
const resultText = result.getContentText();
if (rc !== 200) {
throw new Error(rc);
}
// --- Standard DNS response codes ---
const 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
];
const response = JSON.parse(resultText);
if (response.Status !== 0) {
return errors[response.Status].name;
}
// --- Extract answer records and determine cache TTL ---
const outputData = [];
let cacheTTL = 0;
for (const i in response.Answer) {
outputData.push(response.Answer[i].data);
const ttl = response.Answer[i].TTL;
cacheTTL = Math.min(cacheTTL || ttl, ttl);
}
const outputString = outputData.join(",");
if (useCache) {
cache.put(cacheBinKey, outputString, Math.max(cacheTTL, minCacheTTL));
}
return outputString;
}Использование 1.1.1.1
При вызове NSLookup функцию с типом записи и доменом, в ячейке отображается соответствующее значение DNS-записи: данные (например, IP-адрес), которые DNS возвращает для этого домена и типа записи.
Полная сигнатура функции:
=NSLookup(type, domain, useCache, minCacheTTL)
| Параметр | Обязательный | По умолчанию | Описание |
|---|---|---|---|
type |
Да | , | Тип DNS-записи для запроса (например, A, AAAA, MX). |
domain |
Да | , | Доменное имя для поиска. |
useCache |
Нет | false |
Установите значение true, чтобы кешировать результаты с помощью CacheService из Google Apps Script, что снижает число повторных DNS-запросов в больших таблицах. |
minCacheTTL |
Нет | 30 |
Минимальное время хранения в кэше в секундах. Фактическое значение TTL равно большему из этого значения и TTL, возвращённого в ответе DNS. |
Поддерживаемые типы записей DNS
AAAAACAACNAMEDSDNSKEYMXNSNSECNSEC3RRSIGSOATXT
Например, если ячейка B1 содержит A (тип записи) и B2 содержит example.com (домен), введя в другой ячейке следующую формулу:
=NSLookup(B1, B2)В зависимости от региональных настроек в качестве разделителя аргументов может потребоваться точка с запятой:
=NSLookup(B1; B2)
Возвращает A-запись для этого домена:
198.41.214.162, 198.41.215.162