Skip to content

Instantly share code, notes, and snippets.

@gidoBOSSftw5731
Created May 25, 2021 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gidoBOSSftw5731/7a0f0ba5240a748d4215fda8026a59ca to your computer and use it in GitHub Desktop.
Save gidoBOSSftw5731/7a0f0ba5240a748d4215fda8026a59ca to your computer and use it in GitHub Desktop.
Send emails automatically on any machine logins

This sends an email to the address specified with the environment variables of the session on every session creation (every login, not counting sudo.)

Env variables for SSH include the public key, the IP address, and whatever other authentication was done.

#please PREPEND this to /etc/pam.d/common-session, do NOT replace it.
session required pam_exec.so /etc/pam.scripts/ssh_alert.sh
#!/bin/bash
#location: /etc/pam.scripts/ssh_alert.sh
if [ "$PAM_TYPE" != "close_session" ]; then
host="`hostname -s`"
# Change these two lines where applicable
sender="root@$host <root@`hostname`>"
recepient="root+pam@insertyourdomainhere.tld"
subject="Login: $PAM_USER from $PAM_RHOST on $host"
# Message to send, e.g. the current environment variables.
#add date to the environment variables as a timestamp
export date=`date`
#replace newlines with \n
message="$(env|sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g')"
printf "Subject: $subject\nTo: $recipient\n\n$message" | /usr/sbin/sendmail -f "$sender" "$recepient"
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment