Skip to content

Instantly share code, notes, and snippets.

@tatsuryu
Created July 2, 2018 19:27
Show Gist options
  • Save tatsuryu/3349fc8f4bc862ce5a911a18db8eba76 to your computer and use it in GitHub Desktop.
Save tatsuryu/3349fc8f4bc862ce5a911a18db8eba76 to your computer and use it in GitHub Desktop.
Open VPN client connect/disconnect emailer script

This script is intended to be used with Open VPN as the client-connect and client-disconnect scripts, to send an email using Mailgun to a certain address when a client connects or disconnects.

To install this, copy the below file to /etc/openvpn/statuschange.sh, replace the to email with your own, the and the from email, the URL, and the API key with your own Mailgun login. (I use the sandbox because I didn't feel like messing with DNS.)

Then, add the following to /etc/openvpn/server.conf:

client-connect /etc/openvpn/statuschange.sh
client-disconnect /etc/openvpn/statuschange.sh
script-security 2

The first two lines should be self-explanatory; the third allows Open VPN to call "user-defined scripts," which is technically somewhat unsafe.

Finally, tell the Open VPN daemon to reload its configuration: sudo service openvpn reload (or comparable). Try connecting and disconnecting to the VPN; it should send an email on both events.

#!/bin/bash
if [ "$script_type" == "client-connect" ]; then
subj='Client Connected'
elif [ "$script_type" == "client-disconnect" ]; then
subj='Client Disconnected'
else
subj=$script_type
fi
(echo "$time_ascii: $common_name @ $untrusted_ip via $proto_1"; echo '---'; env) | \
curl -s --user 'api:key-redacted' \
https://api.mailgun.net/v2/redacted.example.com/messages \
-F from='Open VPN <[email protected]>' \
-F to='[email protected]' \
-F subject="$subj: $common_name" \
-F text=\<- >/dev/null 2>&1
echo "Sent email ($?): $script_type: $common_name"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment