From 07cfbcfede4f4e45a44aef516ce6607e1a63517d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20De=20Keersmaeker?= <francois.dekeersmaeker@uclouvain.be> Date: Sat, 16 Nov 2024 21:36:17 +0100 Subject: [PATCH] Added function update_dns_table + refactor --- dns_unbound_cache_reader/__init__.py | 1 + .../dns_unbound_cache_reader.py | 50 +++++++++++++------ 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/dns_unbound_cache_reader/__init__.py b/dns_unbound_cache_reader/__init__.py index 547d4bd..59e7207 100644 --- a/dns_unbound_cache_reader/__init__.py +++ b/dns_unbound_cache_reader/__init__.py @@ -2,5 +2,6 @@ from .dns_unbound_cache_reader import ( DnsCacheSection, DnsRtype, DnsTableKeys, + update_dns_table, read_dns_cache ) diff --git a/dns_unbound_cache_reader/dns_unbound_cache_reader.py b/dns_unbound_cache_reader/dns_unbound_cache_reader.py index 7228e1a..a7bdbcf 100644 --- a/dns_unbound_cache_reader/dns_unbound_cache_reader.py +++ b/dns_unbound_cache_reader/dns_unbound_cache_reader.py @@ -55,30 +55,22 @@ class DnsTableKeys(Enum): ALIAS = "alias" -def read_dns_cache( +def update_dns_table( + dns_table: dict = {}, host: str = "127.0.0.1", file: str = None ) -> dict: """ - Read the Unbound DNS cache and return it as a dictionary, - in the format: - { - DnsTableKeys.IP: { - ip_address: domain_name, - ... - }, - DnsTableKeys.ALIAS: { - canonical_name: alias, - ... - } - } + Update the given DNS table by reading the current DNS cache. Args: + dns_table (dict): Dictionary containing the current DNS table. host (str): IP address of the Unbound DNS server. Default is localhost. file (str): Path to a file containing the Unbound DNS cache. Default is None. If specified, the function reads the cache from the file instead of the server. + Returns: + dict: Updated DNS table. """ - ### Get DNS cache ### dns_cache = None @@ -116,7 +108,6 @@ def read_dns_cache( end_idx = len(dns_cache) # Loop through the RRSET section - dns_table = {} for line in dns_cache[start_idx+1:end_idx]: # Lines containing metadata, skip @@ -204,3 +195,32 @@ def read_dns_cache( return dns_table + + + +def read_dns_cache( + host: str = "127.0.0.1", + file: str = None + ) -> dict: + """ + Read the Unbound DNS cache and return it as a dictionary, + in the format: + { + DnsTableKeys.IP: { + ip_address: domain_name, + ... + }, + DnsTableKeys.ALIAS: { + canonical_name: alias, + ... + } + } + + Args: + host (str): IP address of the Unbound DNS server. Default is localhost. + file (str): Path to a file containing the Unbound DNS cache. Default is None. + If specified, the function reads the cache from the file instead of the server. + Returns: + dict: Dictionary containing the DNS table read from the cache. + """ + return update_dns_table({}, host, file) -- GitLab