import ctypes
import subprocess

vpnName = 'MYVPN'  # change name if required
server = '200.200.200.200'  # change to valid ip address


class disable_file_system_redirection:
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection

    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))

    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)


def ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        return out, err


ConfigVpn = r'Add-VpnConnection -Name "' + vpnName + r'" -ServerAddress "' + server + \
            r'" -TunnelType "L2tp" -EncryptionLevel "Required" -AuthenticationMethod Eap -PassThru '
#print ConfigVpn

checkVPN = ExecuteCmd('Get-VpnConnection -Name ' + vpnName)[0]
if checkVPN == '':
    if ExecuteCmd(ConfigVpn)[0] != '':
        print 'VPN connection configured successfully'
    else:
        print 'VPN configuration failed'
else:
    print 'VPN connection already exits'
