Posts Tagged ‘openvpn client-connect script’

Openvpn client-connect script

December 6, 2022

Allow only 1 vpn profile connection at a time. Script below will also work on disconnect but not using it for that.

  • create a folder in /etc/openvpn called “connection_files”
  • add a file named {username}_ip. Put the remote client’s IP address in there.
  • create a file named connectScript.sh, make it executable and put the following code in it…
#!/bin/bash

function handle_connect {
  CLIENTFILE=/etc/openvpn/connection_files/${username}_ip
  CONNECTIONS=/etc/openvpn/connection_files/${username}_conn
  if [ -e $CLIENTFILE ]; then
    MYIP=$(cat $CLIENTFILE)
    /usr/sbin/ss | grep $MYIP > $CONNECTIONS
    NUMCONN=$(cat $CONNECTIONS | wc -l)
      if [ $NUMCONN -eq 2 ]; then exit 1; fi
  fi
}

function handle_disconnect {
  CLIENTFILE=/etc/openvpn/connection_files/$username
  if [ -e "$CLIENTFILE" ]; then
     NUMCONN=$(cat $CLIENTFILE)
     NEWCONN=$(expr $NUMCONN - 1)
     echo $NEWCONN >$CLIENTFILE
  fi
}

case "$script_type" in
  up)
        ;;
  client-connect)
        "handle_connect"
        ;;
  client-disconnect)
        "handle_disconnect"
        ;;
esac

Then add these lines to your server.conf files or whatever you named your server conf files….has to be in all of them in order to work.

script-security 3
client-connect /etc/openvpn/connectScript.sh