Pi-Hole - Adding blocklist urls to the Gravity DB from the command-line
This is to add block list to the Gravity DB from the command line from a text file.
You will need a few things to do this
This is for allowing zmodem options if you telnet session allows it like SecurCRT that I used.
Install the following packages
sudo apt-get install lrzsz
sudo apt-get install sqlite3
Add the URL's per line for example
Blocklist: HERE
To add these URL's you have to add them to the following file
sudo nano /etc/pihole/adlists.list
Create a file to run as the import script
sudo nano /etc/pihole/adlists.sh
Then create a script and call it what ever you like and put this in
#!/bin/bash
set -e
DB_FILE="/etc/pihole/gravity.db"
BACKUP_FILE="/etc/pihole/gravity_backup_$(date +%Y%m%d_%H%M%S).db"
ADLIST_FILE="/etc/pihole/adlists.list"
# Check if adlists.list exists
if [ ! -f "$ADLIST_FILE" ]; then
echo "Error: $ADLIST_FILE not found!"
exit 1
fi
echo "1. Backing up existing gravity.db..."
sudo cp "$DB_FILE" "$BACKUP_FILE"
echo "2. Clearing existing adlists from database..."
sudo sqlite3 "$DB_FILE" "DELETE FROM adlist;"
echo "3. Importing HTTPS URLs from $ADLIST_FILE..."
count=0
# Process lines using process substitution to keep scope in the main shell
while IFS= read -r url; do
if [ -n "$url" ]; then
safe_url=$(echo "$url" | sed "s/'/''/g")
sudo sqlite3 "$DB_FILE" "INSERT INTO adlist (address, enabled, comment) VALUES ('$safe_url', 1, 'Imported from adlists.list');"
count=$((count + 1))
echo "Added: $safe_url"
fi
done < <(grep 'https://' "$ADLIST_FILE" | grep -v '^[[:space:]]*#' | grep -o 'https://[^[:space:]]*')
echo "Successfully imported $count adlists."
echo "4. Updating Gravity (downloading lists)..."
sudo pihole -g
echo "Done! Pi-hole gravity update complete."
Change the permissions on the file
sudo chmod +x /etc/pihole/adlists.sh
Docker Users
If you place the script within the working directory of pihole container you can do the following:
docker exec -it pihole chmod +x /etc/pihole/bash_script.sh
docker exec -it pihole chmod 777 /etc/pihole/adlists.list
docker exec -it pihole ./etc/pihole/bash_script.sh
Error Check
Run the following to make sure your database is still okay and does not display any errors like these
| 2025-03-25 21:53:21.039 EDT [1353/T9050] ERROR: SQLite3: no such table: info in "SELECT value FROM info WHERE property = 'updated';" (1) 2025-03-25 21:53:21.039 EDT [1353/T9050] WARNING: gravity_updated(): SELECT value FROM info WHERE property = 'updated'; - SQL error prepare: SQL logic error |
If so just rebuild the database like this
sudo mv /etc/pihole/gravity.db /etc/pihole/gravity_backup.db
sudo pihole -g