myvesta/bin/v-blacklist-email-account
2024-11-27 14:05:07 +01:00

103 lines
3.0 KiB
Bash

#!/bin/bash
# info: Add a specific email address to exim4 and spamassassin blacklist
# usage: v-blacklist-email-account EMAIL
#----------------------------------------------------------#
# Variable&Function #
#----------------------------------------------------------#
whoami=$(whoami)
if [ "$whoami" != "root" ]; then
echo "You must be root to execute this script"
exit 1
fi
# Importing system environment
source /etc/profile
# Determine Debian version and set SpamAssassin service name
release=$(cat /etc/debian_version | tr "." "\n" | head -n1)
if [ "$release" -lt 12 ]; then
SPAMD_SERVICE="spamassassin.service"
else
SPAMD_SERVICE="spamd.service"
fi
DENY_SENDERS_FILE="/etc/exim4/deny_senders"
SPAMASSASSIN_FILE="/etc/spamassassin/local.cf"
# Flags to track changes
SPAMASSASSIN_CHANGED=false
# Function to check if an entry already exists in a file
check_entry_exists() {
local entry=$1
local file=$2
grep -qF "$entry" "$file"
}
# Function to add an entry to a file
add_entry_to_file() {
local entry=$1
local file=$2
echo "$entry" >> "$file"
}
# Display usage if no arguments are provided
if [ $# -lt 1 ]; then
echo "Usage: v-blacklist-email EMAIL"
exit 1
fi
#----------------------------------------------------------#
# Action #
#----------------------------------------------------------#
EMAIL=$1
# Validate email format
if [[ ! "$EMAIL" =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "Invalid email address format."
exit 1
fi
# Prepare entries for Exim4 and SpamAssassin
EXIM_ENTRY="$EMAIL"
SPAMASSASSIN_ENTRY="blacklist_from $EMAIL"
#----------------------------------------------------------#
# Exim4 Blacklist #
#----------------------------------------------------------#
echo "Updating $DENY_SENDERS_FILE..."
if ! check_entry_exists "$EXIM_ENTRY" "$DENY_SENDERS_FILE"; then
add_entry_to_file "$EXIM_ENTRY" "$DENY_SENDERS_FILE"
echo "Added $EXIM_ENTRY to $DENY_SENDERS_FILE."
else
echo "$EXIM_ENTRY already exists in $DENY_SENDERS_FILE."
fi
#----------------------------------------------------------#
# SpamAssassin Blacklist #
#----------------------------------------------------------#
echo "Updating $SPAMASSASSIN_FILE..."
if ! check_entry_exists "$SPAMASSASSIN_ENTRY" "$SPAMASSASSIN_FILE"; then
add_entry_to_file "$SPAMASSASSIN_ENTRY" "$SPAMASSASSIN_FILE"
echo "Added $SPAMASSASSIN_ENTRY to $SPAMASSASSIN_FILE."
SPAMASSASSIN_CHANGED=true
else
echo "$SPAMASSASSIN_ENTRY already exists in $SPAMASSASSIN_FILE."
fi
if [ "$SPAMASSASSIN_CHANGED" == "true" ]; then
systemctl restart "$SPAMD_SERVICE"
echo "SpamAssassin service ($SPAMD_SERVICE) restarted."
fi
#----------------------------------------------------------#
# Done #
#----------------------------------------------------------#
exit 0