Last active
June 27, 2024 22:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script does the following:
/etc/resolv.conf
./etc/network/interfaces
./etc/rc.local
to run on boot.To use this script:
/usr/local/bin/set_dns.sh
.8.8.8.8
with your desired DNS server IP address./usr/local/bin/set_dns.sh
with the actual path where you saved the script.sudo bash /usr/local/bin/set_dns.sh
.After running the script and rebooting, your system should use the specified DNS server.