cPanel DNS Zone Cleanup

5/5 - (1 vote)

If you have servers in a two-way DNS cluster sync that causes all zones to be written to all servers, there is a way to clean this up. I’ve written a script to compare a list of zones on a server to /etc/userdomains to determine which zones belong to the server, so the extraneous ones can be removed. 

When you get the list, output the list to a file and loop it through the API to delete the zones:

for domain in $(cat listofdomains); do whmapi1 killdns domain="$domain" ; done

Note: You may want to disable DNS clustering before you do this, else this will delete the zones from all members of the cluster.

Script:

#!/bin/bash
# Script to compare DNS zones with user domains
# Compares zones from /var/named/*.db with domains in /etc/userdomains
echo "DNS Zone and User Domain Comparison"
echo "=================================="

# Check if required files/directories exist
if [[ ! -d "/var/named" ]]; then
  echo "Error: /var/named directory not found"
  exit 1
fi

if [[ ! -f "/etc/userdomains" ]]; then
  echo "Error: /etc/userdomains file not found"
  exit 1
fi

# Create temporary files for comparison
ZONES_FILE=$(mktemp)
DOMAINS_FILE=$(mktemp)

# Clean up temporary files on exit
trap 'rm -f "$ZONES_FILE" "$DOMAINS_FILE"' EXIT

# Extract zone names from /var/named/*.db files (remove .db extension)
echo "Extracting zones from /var/named/*.db files..."
for db_file in /var/named/*.db; do
  if [[ -f "$db_file" ]]; then
    basename "$db_file" .db
  fi
done | sort > "$ZONES_FILE"

# Extract domains from /etc/userdomains
echo "Extracting domains from /etc/userdomains..."
cut -d: -f1 /etc/userdomains | sort > "$DOMAINS_FILE"

# Count totals
ZONE_COUNT=$(wc -l < "$ZONES_FILE")
DOMAIN_COUNT=$(wc -l < "$DOMAINS_FILE")

echo
echo "Summary:"
echo "--------"
echo "Total zones found: $ZONE_COUNT"
echo "Total user domains: $DOMAIN_COUNT"

# Find zones that exist but have no corresponding user domain
echo
echo "Zones without corresponding user domains:"
echo "----------------------------------------"
comm -23 "$ZONES_FILE" "$DOMAINS_FILE" | while read zone; do
  echo " $zone"
done

echo
echo "Comparison complete."

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top