Back to Resources
Level
Script
General
Unexpected or unauthorized DNS server configurations can expose a network to outages, slow response times, or even security risks. This script tackles that challenge by ensuring each Linux device strictly adheres to a permitted DNS server list, reducing the risk of misconfiguration or malicious updates.
This script checks the Linux system’s current DNS servers and compares them against a custom-defined “allowed” DNS list from Level’s cf_dns field. If any discrepancies are found, it issues an alert indicating that the servers are not compliant with the trusted configuration.
Because it verifies DNS at a system or root permission level, it can accurately monitor and detect any unauthorized changes in real time, providing a reliable safeguard against DNS misconfigurations.
#!/bin/bash
# This resource is provided as a convenience for Level users. We cannot
# guarantee it will work in all environments. Please test before deploying
# to your production environment. We welcome contributions to our community
# library
# Level Library
# https://level.io/library/script-linux-monitor-dns-servers
# Expected DNS servers (comma-separated list)
allowed_dns_servers_string="{{cf_dns}}"
# Convert the comma-separated list into an array
IFS=',' read -r -a allowed_dns_servers <<< "$allowed_dns_servers_string"
# Function to check DNS servers
check_dns_servers() {
# Get current DNS servers from resolv.conf as fallback if nmcli is not installed
if command -v nmcli &> /dev/null; then
readarray -t current_dns_servers < <(nmcli dev show | grep 'IP4.DNS' | awk '{print $2}')
else
readarray -t current_dns_servers < <(grep "^nameserver" /etc/resolv.conf | awk '{print $2}')
fi
echo "Allowed DNS servers: ${allowed_dns_servers[*]}"
echo "Current DNS servers: ${current_dns_servers[*]}"
if [[ ${#current_dns_servers[@]} -eq 0 ]]; then
echo "ALERT: No DNS servers configured"
exit 1
fi
# Compare current DNS servers against allowed list
for dns in "${current_dns_servers[@]}"; do
if [[ ! " ${allowed_dns_servers[*]} " =~ " ${dns} " ]]; then
echo "ALERT: Not all DNS servers are in the allowed list."
exit 1
fi
done
echo "SUCCESS: DNS servers match the allowed list."
}
# Check DNS servers
check_dns_servers
Linux Monitor - DNS Servers
This script, Linux Monitor - DNS Servers, retrieves the system's current DNS server configuration using nmcli and compares it against a predefined list of allowed DNS servers. It alerts if any DNS servers are missing or do not match the allowed list, ensuring the network's DNS configuration adheres to expected security and performance standards.
Bash
100
Local system
Explore more automations, scripts, and policies to further enhance your IT operations.