Login Mail Alert Using Rsyslog
I wanted a way to know who authenticates on my servers. This is especially useful if you work in a team or want to have some additional security in place.
Rsyslogd is a service that ships with most distros which proceeds logs before they are written to disk.
We will create a simple script which will be executed whenever a user session gets opened.
This way we will be able to log any user logins whether it’s from terminal, ssh, su, cockpit, etc.
In my case I will send a mail with the login details which will look like this:
# Login Email Alert
# includes ssh / cockpit / any login
mkdir -p /root/scripts
cat << 'EOF' > /root/scripts/loginalert.sh
#!/bin/bash
recepient="user@example.com"
host="`hostname`"
subject="Rsyslogd: User session opened on $host"
# $@ = args passed to script, will be the log line by default e.g
# Sep 30 13:08:51 <hostname> sshd[6536]: pam_unix(sshd:session): session opened for user <username> by (uid=0)
message="$@"
echo "$message" | mail -s "$subject" "$recepient"
EOF
chmod +x /root/scripts/loginalert.sh
cat << 'EOF' > /etc/rsyslog.d/loginalert.conf
$ModLoad omprog
$ActionExecOnlyOnceEveryInterval 2
if $msg contains 'session opened for user' and not ($msg contains 'cron') then {
^/root/scripts/loginalert.sh
}
EOF
systemctl restart rsyslog
Write a Reply or Comment