refactored by claude 3.5 sonnet
This commit is contained in:
parent
b6002a9afd
commit
f06ce051d2
@ -4,30 +4,48 @@
|
|||||||
# login mailer
|
# login mailer
|
||||||
#
|
#
|
||||||
|
|
||||||
# set env var EMAIL and ENDPOINT
|
|
||||||
LOG_FILE="/var/log/auth.log"
|
LOG_FILE="/var/log/auth.log"
|
||||||
LAST_LINE_FILE="/tmp/last_line_checked"
|
LAST_LINE_FILE="/tmp/last_line_checked"
|
||||||
LOG_OUTPUT="/var/log/server-toolkit/login-mailer.log"
|
LOG_OUTPUT="/var/log/server-toolkit/login-mailer.log"
|
||||||
HOSTNAME=$(hostname)
|
HOSTNAME=$(hostname)
|
||||||
|
|
||||||
|
if [[ -z "$EMAIL" || -z "$ENDPOINT" ]]; then
|
||||||
|
echo "Error: EMAIL and ENDPOINT environment variables must be set." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$(dirname "$LOG_OUTPUT")"
|
||||||
|
|
||||||
if [[ ! -f "$LAST_LINE_FILE" ]]; then
|
if [[ ! -f "$LAST_LINE_FILE" ]]; then
|
||||||
echo "0" >"$LAST_LINE_FILE"
|
echo "0" >"$LAST_LINE_FILE"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
LAST_LINE=$(cat "$LAST_LINE_FILE")
|
log_message() {
|
||||||
NEW_LINES=$(sed -n "$((LAST_LINE + 1)),\$p" "$LOG_FILE")
|
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >>"$LOG_OUTPUT"
|
||||||
|
}
|
||||||
|
|
||||||
if echo "$NEW_LINES" | grep "sshd.*Accepted"; then
|
LAST_LINE=$(cat "$LAST_LINE_FILE")
|
||||||
|
NEW_LINES=$(tail -n +$((LAST_LINE + 1)) "$LOG_FILE")
|
||||||
|
|
||||||
|
if echo "$NEW_LINES" | grep -q "sshd.*Accepted"; then
|
||||||
LOGIN_INFO=$(echo "$NEW_LINES" | grep "sshd.*Accepted" | awk '{print $9 " from " $11}')
|
LOGIN_INFO=$(echo "$NEW_LINES" | grep "sshd.*Accepted" | awk '{print $9 " from " $11}')
|
||||||
|
|
||||||
RESPONSE_CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "content-type: application/json" \
|
JSON_PAYLOAD=$(jq -n \
|
||||||
-d "$(jq -n --arg subject "New login on $HOSTNAME" --arg text "SSH login detected: $LOGIN_INFO" --arg recipient "$EMAIL" \
|
--arg subject "New login on $HOSTNAME" \
|
||||||
'{subject: $subject, text: $text, recipient: $recipient}')" \
|
--arg text "SSH login detected: $LOGIN_INFO" \
|
||||||
|
--arg recipient "$EMAIL" \
|
||||||
|
'{subject: $subject, text: $text, recipient: $recipient}')
|
||||||
|
|
||||||
|
RESPONSE_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "$JSON_PAYLOAD" \
|
||||||
"$ENDPOINT")
|
"$ENDPOINT")
|
||||||
|
|
||||||
if [[ "$RESPONSE_CODE" -ne 200 ]]; then
|
if [[ "$RESPONSE_CODE" -ne 200 ]]; then
|
||||||
echo "$(date '+%Y-%m-%d %H:%M:%S') - Failed to send login alert. Response code: $RESPONSE_CODE" >>"$LOG_OUTPUT"
|
log_message "Failed to send login alert. Response code: $RESPONSE_CODE"
|
||||||
|
else
|
||||||
|
log_message "Login alert sent successfully for: $LOGIN_INFO"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
wc -l "$LOG_FILE" | awk '{print $1}' >"$LAST_LINE_FILE"
|
wc -l <"$LOG_FILE" >"$LAST_LINE_FILE"
|
||||||
|
Loading…
x
Reference in New Issue
Block a user