PAM, the Linux Pluggable Authentication Modules, allows you to execute programs and scripts when SSH sessions are opened and closed.

# /etc/pam.d/sshd
session optional        pam_exec.so     /path/to/script.sh
# /path/to/script.sh

#!/bin/bash
if [ $PAM_TYPE = "open_session" ]; then
  # 
fi
exit 0

WARNING:
Botching your script or failing to return 0 will cause SSH login to fail. Don’t lock yourself out, test your script!