block all traffic to/from a domain by Bash Script

Target:
- Create a Bash script to block all traffic to/from a domain Youtube by resolving its IPs , then save the info to a file.
Setup Environment
First of all I create a directory for the task and create the script file with the extension .sh

Write Script
#!/bin/bash
DOMAIN="youtube.com"
OUTPUT_FILE="blocked_domains.txt"
IPs=$(dig +short "$DOMAIN" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}')
if [ -z "$IPs" ]; then
echo "Failed to resolve $DOMAIN"
exit 1
fi
for IP in $IPs; do
sudo iptables -A OUTPUT -d "$IP" -j REJECT
sudo iptables -A INPUT -s "$IP" -j REJECT
echo "$DOMAIN ($IP) has been blocked"
echo "$(date): $DOMAIN ($IP) blocked" >> "$OUTPUT_FILE"
done
echo "Blocking complete. Details saved in $OUTPUT_FILE."
chmod 777 script.sh
sudo ./script.sh
First I specify the domain I want to block , in this case I will choose youtube.com
Then I assign an IP variable and use the regex to extract the IP
If the domain couldn't be resolved, the script exits with a message
Then I block the outgoing & the ingoing traffic from this domain using iptables
Test
cat blocked_domains.txt
Sun Oct 5 07:41:17 PM EDT 2025: youtube.com (172.217.21.14) blocked
go to youtube.com




