Skip to content

Instantly share code, notes, and snippets.

@schappim
Last active June 27, 2024 22:24
Show Gist options
  • Save schappim/f0a0472e0349daed57daf774b8afe6b2 to your computer and use it in GitHub Desktop.
Save schappim/f0a0472e0349daed57daf774b8afe6b2 to your computer and use it in GitHub Desktop.
Script to configure the DNS server on Debian-based Linux systems at boot
#!/bin/bash
# Set this to your desired DNS server
DNS_SERVER="8.8.8.8"
# Set the path for this script
SCRIPT_PATH="/usr/local/bin/set_dns.sh"
# Path to the resolv.conf file
RESOLV_CONF="/etc/resolv.conf"
# Path to the network interfaces file
INTERFACES_FILE="/etc/network/interfaces"
# Function to set DNS server in resolv.conf
set_dns_resolv_conf() {
echo "nameserver $DNS_SERVER" | sudo tee $RESOLV_CONF
}
# Function to set DNS server in interfaces file
set_dns_interfaces() {
if ! grep -q "dns-nameservers" $INTERFACES_FILE; then
echo "dns-nameservers $DNS_SERVER" | sudo tee -a $INTERFACES_FILE
else
sudo sed -i "s/dns-nameservers.*/dns-nameservers $DNS_SERVER/" $INTERFACES_FILE
fi
}
# Set DNS server
set_dns_resolv_conf
set_dns_interfaces
echo "DNS server has been set to $DNS_SERVER"
# Make the script executable
sudo chmod +x "$SCRIPT_PATH"
# Add the script to /etc/rc.local to run on boot
if ! grep -q "$SCRIPT_PATH" /etc/rc.local; then
sudo sed -i "/^exit 0/i $SCRIPT_PATH" /etc/rc.local
fi
echo "Script has been added to run on boot"
# If this script is not already in the correct location, move it there
if [ "$0" != "$SCRIPT_PATH" ]; then
sudo mv "$0" "$SCRIPT_PATH"
echo "Script has been moved to $SCRIPT_PATH"
fi
@schappim
Copy link
Author

schappim commented Jun 27, 2024

This script does the following:

  1. Sets the DNS server in /etc/resolv.conf.
  2. Adds or updates the DNS server in /etc/network/interfaces.
  3. Makes itself executable.
  4. Adds itself to /etc/rc.local to run on boot.

To use this script:

  1. Save it to a file, for example, /usr/local/bin/set_dns.sh.
  2. Replace 8.8.8.8 with your desired DNS server IP address.
  3. Replace /usr/local/bin/set_dns.sh with the actual path where you saved the script.
  4. Run the script with root privileges: sudo bash /usr/local/bin/set_dns.sh.

After running the script and rebooting, your system should use the specified DNS server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment