Windows 10 vpn переподключение при разрыве

C удивлением, правда небольшим, обнаружил, что в Windows, начиная с версии 8 и в Windows Server, начиная с 2008, Microsoft слегка «доработал напильником» диалог настроек VPN соединения. Точнее, урезал настраиваемые параметры на вкладке Options. Вместо того, что было привычно в Windows 7 и выглядело как:

Окно свойств VPN подключения в Windows 7 Теперь убрали практически все и оставили только:

Параметры VPN соединения в WIndows Server 2012И возник закономерный вопрос– а как теперь настроить автоматическое переподключение и количество попыток повтора соединения если связь прервется?

Методов несколько. Давайте по порядку. По мере возрастания, так сказать, сложности.

Метод 1 — используем Notepad:

Установить нужные параметры вручную. Для этого необходимо перейти в папку

C:\Users\[USER]\AppData\Roaming\Microsoft\Network\Connections\Pbk\

Найти там (скорее всего единственный) файлик с именем rasphone.pbk. Это обычный текстовый файл, содерржащий настройки подключения к VPN

Файл можно открыть с помощью notepad.exe (Блокнот)

В общем случае, необходимо отыскать секцию, содержащую ваш VPN – например, такой [PPTP-VPN]

А в ней отыскать строки (TADA!)/ Если ничего не меняли, то выглядеть будет примерно так:

RedialAttempts=3
RedialSeconds=60
IdleDisconnectSeconds=0
RedialOnLinkFailure=1

То есть опять “Microsoft за вас подумали и все решил”.

Но теперь вы знаете, где искать и менять необходимые параметры.

  • RedialAttempts=3 – количество попыток пере-подключиться (максимум 99)
  • RedialSeconds=60 – количество секунд между попытками пере-подключиться
  • IdleDisconnectSeconds=0 — сколько выжидать, чтобы понять что линия оборвалась (0 – не ждать вовсе)
  • RedialOnLinkFailure=1 — Перенабрать, если связь оборвалась? 1 – да, 0 — нет

Чтобы параметры применились, необходимо, как и раньше, переподключить VPN.

А потом верить, что Microsoft Windows все сделает за вас 🙂

Примечание: Замечено, что Windows Server 2012 может, по собственной инициативе, использовать папку C:\Users\[USER]\AppData\Roaming\Microsoft\Network\Connections\Pbk\_hiddenPbk и положить файл rasphone.pbk в эту папку.

Метод 2 – настраиваем простейшую задачу:

Создать в Task Scheduler задачу, которая будет запускать bat-файл со строкой подключения к необходимому VPN и настроить эту задачу, на запуск, скажем, каждые 5 минут.

Напомню, командная строка для подключения VPN соединения выглядит так

C:\windows\system32\rasdial.EXE entryname [username [password|*]] [/DOMAIN:domain]

Там еще параметры есть, но их, если интересно, посмотрите сами.

В задаче не забываем указать, что “запускать всегда”

Задаие планировщика для перезапуска VPN соединенияУказать выполняемый файл, например, такой

rasdial.batИли сказать, чтобы запускался rasdial.exe (VPN User Password – это название вашего VPN-соединения имя_пользователя и ваш_пароль)

rasdial.exeЗапускать, с интервалом 5 минут, каждый день.

repeat task every 5 minutesМетод 3. Настраиваем задачу “с вывертами” :)

  1. Создаем задачу в Task Scheduler
  2. Определяем в задаче два триггера. Один с использованием XML запроса (по аналогии со статьей Запуск задания планировщика после завершения определенного задания)
<QueryList>

<Query Id="0" Path="Application">

<Select Path="Application">*[System[Provider[@Name='RasClient'] and (EventID=20226)]] and *[EventData[Data[4]='829' or '629']]</Select>

</Query>

</QueryList>

Примечание. Коды: 829 — Remote Disconnect, 629 -Client Disconnect

Второй на базе отслеживания события в Event Log’e:

  • Название лога: Microsoft-Windows-NetworkProfile/Operational
  • Источник : NetworkProfile
  • Event ID: 10000
  • В качестве запускаемой программы, выбираем rasdial.exe с параметрами vpn-name username password
  • Дополнительно, на вкладке Conditions, можно доопределить следующие параметры

task-properties

Примечание: Чтобы убедиться заработает такая задача или нет, создайте еще один триггер с Event ID = 10001. Этoт Event появляется при ручном отключении (disconnet) VPN. После этого попробуйте вручную отключить VPN. Соединение сразу же будет восстановлено.

Ну вот, собственно и все.

Примечание Все описанное работает и в Windows 7

Далее под спойлером привожу, без перевода, длинное, подробное и нудное описание Метода 1 и 3 на английском языке, взятое с форума Technet.

This tip is about how to setup a VPN connection and reconnect with the task scheduler. You will learn about activation, connection, disconnection and deactivation of the VPN connection.

  • Download VPNRedial.zip — 2.2 KB

Introduction

During Corona times, home office becomes more and more important. Company’s resources are accessed by Virtual Private Networks (VPN). When using the build-in Windows VPN Client for PPTP, L2TP/IPSec, SSTP or IKEv2, connections are not reestablished automatically if the connection is lost. A VPN interruption might be caused by a change of the network or Internet network error.

In the everyday life of home workers and road warriors, a drop of a VPN connection leads to hectic activity, because remote desktop clients stop at first and then try to reconnect. The file explorer gets stuck and then tries to display server shares desperately. With a quick click, the experienced power user tries to reconnect the VPN before all applications say goodbye with a timeout error message and all programs have to be restarted. However, this does not succeed in all cases…

For these circumstances, Microsoft simply forgot the feature of an automatic reconnection for VPN connections. Probably, there is always somewhere a checkbox which is missing desperately…

Configuration and Script Code

VPN Connection Setup

To configure the automatic reconnection of a VPN, user name and password must be stored in the Windows Credential Manager. This behavior is specified during the setup:

Image 1

If the option «Remember my credentials» is checked, Windows will save the user name and password after the first connection of the VPN.

Reconnection with the Task Scheduler

Then, the reconnect VPN feature can be configured with build-in Windows tools. Starting point are the Windows event logs in which the following events occur:

Event Id Source Description
20226 RasClient ROUTERLOG_CORR_ID = The user %1 () dialled a connection named %2 () which has been terminated. The reason code returned on termination is %3 ().
10000 NetworkProfile Network connected.

Event 2226 occurs when a VPN connection has been terminated. In this case, an attempt is made to reconnect the VPN immediately. If the reconnection fails, the events 10000 and 8001 trigger a reconnection in the case of a new wired or WiFi network connection of the client.

A task can be imported as «My Connection (VPN) Redial.xml» with an XML format into the Task Scheduler and executed with the logged in user account:

  1  ="1.0"="UTF-16"
  2  <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  3    <RegistrationInfo>
  4      <Date>2020-04-11T09:32:43.9830717</Date>
  5      <Author>LOGICLINK\marcus</Author>
  6      <URI>\My Connection (VPN) Redial</URI>
  7    </RegistrationInfo>
  8    <Triggers>
  9      <EventTrigger>
 10        <Enabled>true</Enabled>
 11        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 12         Path="Application"&gt;&lt;Select Path="Application"
 13         &gt;*[System[Provider[@Name='RasClient'] and EventID=20226]]
 14         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 15      </EventTrigger>
 16      <EventTrigger>
 17        <Enabled>true</Enabled>
 18        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 19         Path="Microsoft-Windows-NetworkProfile/Operational"&gt;
 20         &lt;Select Path="Microsoft-Windows-NetworkProfile/Operational"
 21         &gt;*[System[Provider[@Name='NetworkProfile'] and EventID=10000]]
 22         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 23      </EventTrigger>
 24    </Triggers>
 25    <Principals>
 26      <Principal id="Author">
 27        <LogonType>InteractiveToken</LogonType>
 28        <RunLevel>LeastPrivilege</RunLevel>
 29      </Principal>
 30    </Principals>
 31    <Settings>
 32      <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
 33      <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
 34      <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
 35      <AllowHardTerminate>true</AllowHardTerminate>
 36      <StartWhenAvailable>false</StartWhenAvailable>
 37      <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
 38      <IdleSettings>
 39        <StopOnIdleEnd>true</StopOnIdleEnd>
 40        <RestartOnIdle>false</RestartOnIdle>
 41      </IdleSettings>
 42      <AllowStartOnDemand>true</AllowStartOnDemand>
 43      <Enabled>false</Enabled>
 44      <Hidden>false</Hidden>
 45      <RunOnlyIfIdle>false</RunOnlyIfIdle>
 46      <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
 47      <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
 48      <WakeToRun>false</WakeToRun>
 49      <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
 50      <Priority>7</Priority>
 51    </Settings>
 52    <Actions Context="Author">
 53      <Exec>
 54        <Command>%SystemRoot%\System32\rasdial.exe</Command>
 55        <Arguments>"My Connection (VPN)"</Arguments>
 56      </Exec>
 57    </Actions>
 58  </Task>

In line 55, the name of the VPN connection must be changed to the name of your VPN connection. The VPN connection should have been established manually with user and password before the first use. Thus, credentials do not have to be entered as parameters for rasdial.exe and stored in the task.

Furthermore, the task should be deactivated by default and only activated when the VPN is needed, thereby it does not establish VPN connections and consume bandwidth unnecessarily.

Activation and Connection of the VPN

The activation and deactivation are done by two batch programs:

The batch file «Enable My Connection (VPN).cmd» activates the task for automatic reconnection and then connects the VPN:

  1  @echo off
  2  
  3  
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /ENABLE
 16  runas /trustlevel:0x20000 "rasdial.exe \"%VPN%\""

In lines 4 and 5, the two variables VPN and TASK identify the VPN connection and the task of the Task Scheduler and must be changed to your individual names accordingly. Using these variables, you can configure multiple batch files for several VPNs.

In the next step, the batch file checks if it was started with administrative rights. The administrative rights are required for the activation of tasks in Task Scheduler. If the batch file was not “Run as administrator”, an error message is displayed and the batch file terminates.

Next, the task TASK is activated in the Task Scheduler. For the connection of the VPN with stored credentials, administrative rights have to be returned. Thus, rasdial.exe is called via runas.exe with user rights by the trustlevel 0x20000.

Disconnection and Deactivation of the VPN Connection

The deactivation and disconnection is done in the batch file «DisableMy Connection (VPN).cmd» by the same commands:

  1  @echo off
  2  
  3  
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /DISABLE
 16  rasdial "%VPN%" /DISCONNECT

The two variables VPN and TASK in lines 4 and 5 must be changed according to your names also. During the termination of the VPN connection, the administrative rights do not interfere and therefore, rasdial.exe can be called directly.

References

  • RasClient 20226 event
  • Auto Reconnect VPN on Disconnection due to any reason – Persistent VPN

History

  • 4th May, 2020: Initial version

C удивлением, правда небольшим, обнаружил, что в Windows, начиная с версии 8 и в Windows Server, начиная с 2008, Microsoft слегка «доработал напильником» диалог настроек VPN соединения. Точнее, урезал настраиваемые параметры на вкладке Options. Вместо того, что было привычно в Windows 7 и выглядело как:

Окно свойств VPN подключения в Windows 7 Теперь убрали практически все и оставили только:

Параметры VPN соединения в WIndows Server 2012И возник закономерный вопрос– а как теперь настроить автоматическое переподключение и количество попыток повтора соединения если связь прервется?

Методов несколько. Давайте по порядку. По мере возрастания, так сказать, сложности.

Метод 1 — используем Notepad:

Установить нужные параметры вручную. Для этого необходимо перейти в папку

C:Users[USER]AppDataRoamingMicrosoftNetworkConnectionsPbk

Найти там (скорее всего единственный) файлик с именем rasphone.pbk. Это обычный текстовый файл, содерржащий настройки подключения к VPN

Файл можно открыть с помощью notepad.exe (Блокнот)

В общем случае, необходимо отыскать секцию, содержащую ваш VPN – например, такой [PPTP-VPN]

А в ней отыскать строки (TADA!)/ Если ничего не меняли, то выглядеть будет примерно так:

RedialAttempts=3
RedialSeconds=60
IdleDisconnectSeconds=0
RedialOnLinkFailure=1

То есть опять “Microsoft за вас подумали и все решил”.

Но теперь вы знаете, где искать и менять необходимые параметры.

  • RedialAttempts=3 – количество попыток пере-подключиться (максимум 99)
  • RedialSeconds=60 – количество секунд между попытками пере-подключиться
  • IdleDisconnectSeconds=0 — сколько выжидать, чтобы понять что линия оборвалась (0 – не ждать вовсе)
  • RedialOnLinkFailure=1 — Перенабрать, если связь оборвалась? 1 – да, 0 — нет

Чтобы параметры применились, необходимо, как и раньше, переподключить VPN.

А потом верить, что Microsoft Windows все сделает за вас 🙂

Примечание: Замечено, что Windows Server 2012 может, по собственной инициативе, использовать папку C:Users[USER]AppDataRoamingMicrosoftNetworkConnectionsPbk_hiddenPbk и положить файл rasphone.pbk в эту папку.

Метод 2 – настраиваем простейшую задачу:

Создать в Task Scheduler задачу, которая будет запускать bat-файл со строкой подключения к необходимому VPN и настроить эту задачу, на запуск, скажем, каждые 5 минут.

Напомню, командная строка для подключения VPN соединения выглядит так

C:windowssystem32rasdial.EXE entryname [username [password|*]] [/DOMAIN:domain]

Там еще параметры есть, но их, если интересно, посмотрите сами.

В задаче не забываем указать, что “запускать всегда”

Задаие планировщика для перезапуска VPN соединенияУказать выполняемый файл, например, такой

rasdial.batИли сказать, чтобы запускался rasdial.exe (VPN User Password – это название вашего VPN-соединения имя_пользователя и ваш_пароль)

rasdial.exeЗапускать, с интервалом 5 минут, каждый день.

repeat task every 5 minutesМетод 3. Настраиваем задачу “с вывертами” :)

  1. Создаем задачу в Task Scheduler
  2. Определяем в задаче два триггера. Один с использованием XML запроса (по аналогии со статьей Запуск задания планировщика после завершения определенного задания)
<QueryList>

<Query Id="0" Path="Application">

<Select Path="Application">*[System[Provider[@Name='RasClient'] and (EventID=20226)]] and *[EventData[Data[4]='829' or '629']]</Select>

</Query>

</QueryList>

Примечание. Коды: 829 — Remote Disconnect, 629 -Client Disconnect

Второй на базе отслеживания события в Event Log’e:

  • Название лога: Microsoft-Windows-NetworkProfile/Operational
  • Источник : NetworkProfile
  • Event ID: 10000
  • В качестве запускаемой программы, выбираем rasdial.exe с параметрами vpn-name username password
  • Дополнительно, на вкладке Conditions, можно доопределить следующие параметры

task-properties

Примечание: Чтобы убедиться заработает такая задача или нет, создайте еще один триггер с Event ID = 10001. Этoт Event появляется при ручном отключении (disconnet) VPN. После этого попробуйте вручную отключить VPN. Соединение сразу же будет восстановлено.

Ну вот, собственно и все.

Примечание Все описанное работает и в Windows 7

Далее под спойлером привожу, без перевода, длинное, подробное и нудное описание Метода 1 и 3 на английском языке, взятое с форума Technet.

Содержание

  1. Windows 10: нет подключения к Интернету после подключения к VPN-серверу (РЕШЕНО)
  2. Авто переподключение VPN на Windows 10
  3. Автоматически инициируемые параметры профиля VPN VPN auto-triggered profile options
  4. Триггер приложений App trigger
  5. Триггер на основе имени Name-based trigger
  6. Режим «Всегда включен» Always On
  7. Сохранение пользователя Всегда на предпочтении Preserving user Always On preference
  8. Обнаружение доверенной сети Trusted network detection
  9. Настройка VPN-подключения, инициируемого приложением Configure app-triggered VPN

При подключении из дома к корпоративному серверу VPN (AlwaysOnVPN, Windows Server RRAS или OpenVPN) пользователи жалуются, что у них нет доступа в Интернет на своём компьютере с активным подключением VPN. В этой статье мы обсудим, почему вы не можете получить доступ к Интернету в Windows 10 при подключении к VPN и как решить эту проблему.

При создании нового VPN-соединения в Windows (все версии) опция Use default gateway on remote network (Использовать шлюз по умолчанию в удалённой сети) включена по умолчанию. Это означает, что весь трафик с вашего компьютера проходит через VPN-туннель. Если на сервере VPN удаленным клиентам разрешён доступ только к локальным корпоративным ресурсам, а доступ в Интернет ограничен, удалённый пользователь не сможет получить доступ к внешним веб-сайтам и другим Интернет-ресурсам со своего компьютера. После отключения от VPN весь пользовательский трафик будет проходить через обычную сеть и появится доступ в Интернет.

Режим, когда часть трафика (доступ к корпоративным ресурсам) отправляется через VPN-туннель, а остальной трафик (доступ в Интернет) проходит через подключение к локальной сети, называется split tunneling (раздельным туннелированием).

В Windows 10 вы можете включить разделённое туннелирование (отключить маршрутизацию интернет-трафика через VPN-туннель) тремя способами:

  • В настройках TCP/IP VPN-подключения
  • В файле rasphone.pbk
  • Использование командлета Set-VpnConnection с параметром SplitTunneling в PowerShell

Самый простой способ — изменить настройки TCP/IP вашего VPN-соединения через панель управления.

  1. Откройте список сетевых подключений в Панели управления (Панель управленияСеть и ИнтернетСетевые подключения) и перейдите в свойства вашего VPN-подключения;
  2. Откройте вкладку «Сеть», выберите «IP версии 4 (TCP/IPv4)» и нажмите «Свойства».
  3. На вкладки «Общие» нажмите кнопку «Дополнительно».
  4. Убедитесь, что на вкладке «Параметры IP» установлен флажок «Использовать шлюз по умолчанию в удаленной сети».

После того как вы снимите флажок «Использовать шлюз по умолчанию в удаленной сети» (“Use default gateway on remote network”) и повторно подключитесь к шлюзу VPN, вы получите доступ в Интернет на своём компьютере через подключение к Интернет-провайдеру. Однако в некоторых сборках Windows 10 эта опция недоступна по некоторым причинам (есть разные проблемы: вы не можете редактировать поле, настройка не сохраняется или форма настройки не открывается при нажатии на свойства «IP версии 4 (TCP/IPv4)»), поэтому возможно, вам придётся использовать другие способы решения проблемы.

Файл rasphone.pbk находится в папке C:ProgramDataMicrosoftNetworkConnectionspbk (если вы создали VPN-соединение для всех пользователей компьютера) или в каталоге профиля пользователя C:UsersusernameAppDataRoamingMicrosoftNetworkConnectionsPbk (если VPN-соединение доступно только вашему пользователю).

Откройте rasphone.pbk в любом текстовом редакторе (подойдёт даже notepad.exe). В этом файле хранятся настройки всех настроенных VPN-подключений. Найдите параметр IpPrioritizeRemote. По умолчанию его значение равно 1. Измените его на , сохраните rasphone.pbk и перезапустите VPN-соединение.

Вы можете использовать rasphone.pbk для развёртывания правильно настроенного VPN-подключения к компьютерам пользователей.

Также вы можете настроить раздельное туннелирование VPN через PowerShell. Отобразите список всех доступных VPN-подключений:

Убедитесь, что SplitTunneling для подключения отключён (SplitTunneling: False).

Чтобы включить SplitTunneling, укажите имя вашего VPN-соединения:

Повторно подключитесь к своему VPN-серверу и убедитесь, что у вас есть доступ к Интернету на вашем компьютере и доступ к корпоративным ресурсам за VPN-шлюзом. Включение SplitTunneling делает то же самое, что и при снятии флажка «Использовать шлюз по умолчанию в удаленной сети» в настройках TCP/IPv4 вашего VPN-соединения. (Если вы запустите команду, показанную выше, этот параметр не будет изменён).

Ещё одна типичная проблема с активным VPN-соединением — проблема с разрешением имени DNS. Имя ресурсов в вашей локальной сети перестаёт распознаваться, поскольку по умолчанию используются DNS-серверы, указанные в настройках VPN-подключения. Проблема описана здесь: «Невозможно разрешить локальные записи DNS при подключении к VPN».

Авто переподключение VPN на Windows 10

В настоящее время я подключаюсь к Интернету через привязанное соединение с моей мобильной сетью передачи данных. Чтобы обойти провайдеров мобильной сети, настаивая на том, чтобы я платил им за использование той же услуги через другое устройство, я также использую VPN для фактического подключения к Интернету. Естественно, сетевой сигнал может легко пропадать и прерывать соединение, и это отключает VPN, даже если само привязанное соединение никогда не отключается.

По иронии судьбы отличный пример моей проблемы можно найти на следующей странице Microsoft Technet, посвященной замечательному решению для Windows 7 / Windows Server 2008 R2:https://technet.microsoft.com/en-us/library/dd637830(v= ws.10).aspx

Например, рассмотрим пользователя, едущего на работу в поезде. Чтобы максимально использовать свое время, она использует беспроводную мобильную широкополосную карту для подключения к Интернету, а затем устанавливает VPN-подключение к сети своей компании. Когда поезд проходит через туннель, она теряет подключение к Интернету. После выхода из туннеля беспроводная мобильная широкополосная карта автоматически подключается к Интернету. Однако в более ранних версиях Windows VPN не переподключается, и ей необходимо повторить многоэтапный процесс подключения к VPN. Это может быстро занять много времени для мобильных пользователей с прерывистой связью.

Однако я не могу найти ни следа этой функции в Windows 10, ни чего-либо подобного. Есть ли способ, чтобы VPN-соединение всегда пыталось переподключиться до тех пор, пока я не отключу явно (например, опция «Автоматически подключаться» в обычных сетях), или просто оставалось в живых, чтобы оно могло возобновиться после восстановления сетевого подключения?

Автоматически инициируемые параметры профиля VPN VPN auto-triggered profile options

Относится к: Applies to

  • Windows 10 Windows 10
  • Windows 10 Mobile Windows 10 Mobile

В Windows 10 были добавлены ряд функций для автоматической активации VPN, чтобы пользователям не приходилось вручную подключаться, если для доступа к необходимым ресурсам требуется VPN. In Windows 10, a number of features were added to auto-trigger VPN so users won’t have to manually connect when VPN is needed to access necessary resources. Существует три типа правил автоматически инициируемых правил. There are three different types of auto-trigger rules:

  • Триггер приложений App trigger
  • Триггер на основе имени Name-based trigger
  • Режим «Всегда включен» Always On

Триггер приложений App trigger

Можно настроить автоматическое подключение профилей VPN в Windows 10 при запуске указанного набора приложений. VPN profiles in Windows 10 can be configured to connect automatically on the launch of a specified set of applications. Вы можете настроить классические приложения и приложения универсальной платформы Windows (UWP) для активации VPN-подключения. You can configure desktop or Universal Windows Platform (UWP) apps to trigger a VPN connection. Можно также настроить VPN для отдельного приложения и указать правила трафика для каждого приложения. You can also configure per-app VPN and specify traffic rules for each app. Дополнительные сведения см. в разделе Фильтры трафика. See Traffic filters for more details.

Идентификатор классического приложения — это путь к файлу. The app identifier for a desktop app is a file path. Идентификатор приложения UWP — это имя семейства пакетов. The app identifier for a UWP app is a package family name.

Триггер на основе имени Name-based trigger

Вы можете настроить правило на основе имени домена, чтобы определенное имя домена активировало VPN-подключение. You can configure a domain name-based rule so that a specific domain name triggers the VPN connection.

Автоматический триггер на основе имени можно настроить с помощью параметра VPNv2/имя_профиля/DomainNameInformationList/dniRowId/AutoTrigger в разделе Поставщик службы конфигурации (CSP) VPNv2. Name-based auto-trigger can be configured using the VPNv2/ProfileName/DomainNameInformationList/dniRowId/AutoTrigger setting in the VPNv2 Configuration Service Provider (CSP).

Существует четыре типа триггеров на основе имени. There are four types of name-based triggers:

  • Короткое имя: например, если HRweb настроен как триггер и стек видит запрос на разрешение DNS для HRweb, активируется VPN-подключение. Short name: for example, if HRweb is configured as a trigger and the stack sees a DNS resolution request for HRweb, the VPN will be triggered.
  • Полное доменное имя (FQDN): например, если HRweb.corp.contoso.com настроен как триггер и стек видит запрос на разрешение DNS для HRweb.corp.contoso.com, активируется VPN-подключение. Fully-qualified domain name (FQDN): for example, if HRweb.corp.contoso.com is configured as a trigger and the stack sees a DNS resolution request for HRweb.corp.contoso.com, the VPN will be triggered.
  • Суффикс: например, если суффикс . corp.contoso.com настроен как триггер и стек видит запрос на разрешение DNS с соответствующим суффиксом (например, HRweb.corp.contoso.com), активируется VPN-подключение. Suffix: for example, if .corp.contoso.com is configured as a trigger and the stack sees a DNS resolution request with a matching suffix (such as HRweb.corp.contoso.com), the VPN will be triggered. VPN активируется для любого сопоставления короткого имени, а у DNS-сервера запрашивается короткое_имя.corp.contoso.com. For any short name resolution, VPN will be triggered and the DNS server will be queried for the ShortName.corp.contoso.com.
  • Все: если используется, любое разрешение DNS активирует VPN. All: if used, all DNS resolution should trigger VPN.

Режим «Всегда включен» Always On

Режим «Всегда включен» — это функция Windows 10, которая позволяет активному профилю VPN автоматически подключаться в следующих случаях (триггеры). Always On is a feature in Windows 10 which enables the active VPN profile to connect automatically on the following triggers:

  • Вход пользователя в систему. User sign-in
  • Изменение в сети. Network change
  • Включение экрана устройства. Device screen on

При активации триггер выполняется попытка подключения к VPN. When the trigger occurs, VPN tries to connect. Если возникает ошибка или требуется ввод пользователя, отображается всплывающее уведомление. If an error occurs or any user input is needed, the user is shown a toast notification for additional interaction.

Если на устройстве несколько профилей с триггерами «Всегда включен», пользователь может задать активный профиль в разделе Параметры > Сеть и Интернет > VPN > Профиль VPN, установив флажок Разрешить приложениям автоматически использовать это VPN-подключение. When a device has multiple profiles with Always On triggers, the user can specify the active profile in Settings > Network & Internet > VPN > VPN profile by selecting the Let apps automatically use this VPN connection checkbox. По умолчанию первый профиль, настроенный в MDM, отмечен как активный. By default, the first MDM-configured profile is marked as Active. Устройства с несколькими пользователями имеют одно и то же ограничение: только один профиль и, следовательно, только один пользователь сможет использовать триггеры Always On. Devices with multiple users have the same restriction: only one profile and therefore only one user will be able to use the Always On triggers.

Сохранение пользователя Всегда на предпочтении Preserving user Always On preference

Windows имеет функцию для сохранения предпочтений пользователя AlwaysOn. Windows has a feature to preserve a user’s AlwaysOn preference. В случае, если пользователь вручную отключает контрольный ящик «Подключение автоматически», Windows запомнит это предпочтение пользователя для этого имени профиля, добавив имя профиля к значению AutoTriggerDisabledProfilesList. In the event that a user manually unchecks the “Connect automatically” checkbox, Windows will remember this user preference for this profile name by adding the profile name to the value AutoTriggerDisabledProfilesList.

Если средство управления удаляет или добавляет одно и то же имя профиля и задает Значение AlwaysOn значение true, Windows не будет проверять поле, существует ли имя профиля в следующем значении реестра, чтобы сохранить предпочтения пользователей. Should a management tool remove or add the same profile name back and set AlwaysOn to true, Windows will not check the box if the profile name exists in the following registry value in order to preserve user preference.

Клавиша: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesRasManConfig Key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesRasManConfig
Значение: AutoTriggerDisabledProfilesList Value: AutoTriggerDisabledProfilesList
Тип: REG_MULTI_SZ Type: REG_MULTI_SZ

Обнаружение доверенной сети Trusted network detection

Эта функция настраивает VPN таким образом, чтобы подключение не активировалось, если пользователь находится в доверенной корпоративной сети. This feature configures the VPN such that it would not get triggered if a user is on a trusted corporate network. Значение этого параметра — список суффиксов DNS. The value of this setting is a list of DNS suffices. Стек VPN изучает DNS-суффикс на физическом интерфейсе и, если он соответствует любому из настроенных в списке, и сеть является частной или настроена MDM, VPN не активируется. The VPN stack will look at the DNS suffix on the physical interface and if it matches any in the configured list and the network is private or provisioned by MDM, then VPN will not get triggered.

Обнаружение доверенной сети можно настроить с помощью параметра VPNv2/имя_профиля/TrustedNetworkDetection в разделе VPNv2 CSP. Trusted network detection can be configured using the VPNv2/ProfileName/TrustedNetworkDetection setting in the VPNv2 CSP.

Настройка VPN-подключения, инициируемого приложением Configure app-triggered VPN

Сведения о настройке XML см. в разделе Параметры профиля VPN и VPNv2 CSP. See VPN profile options and VPNv2 CSP for XML configuration.

На следующем рисунке показано связывание приложения с VPN-подключением в политике конфигурации VPN-профиля с помощью Microsoft Intune. The following image shows associating an app to a VPN connection in a VPN Profile configuration policy using Microsoft Intune.

Если после добавления связанного приложения установить флажок Только эти приложения могут использовать это VPN-подключение (VPN для отдельных приложений), приложение станет доступным в корпоративных границах, где можно настроить правила для приложения. After you add an associated app, if you select the Only these apps can use this VPN connection (per-app VPN) checkbox, the app becomes available in Corporate Boundaries, where you can configure rules for the app. Дополнительные сведения см. в разделе Фильтры трафика. See Traffic filters for more details.

This tip is about how to setup a VPN connection and reconnect with the task scheduler. You will learn about activation, connection, disconnection and deactivation of the VPN connection.

  • Download VPNRedial.zip — 2.2 KB

Introduction

During Corona times, home office becomes more and more important. Company’s resources are accessed by Virtual Private Networks (VPN). When using the build-in Windows VPN Client for PPTP, L2TP/IPSec, SSTP or IKEv2, connections are not reestablished automatically if the connection is lost. A VPN interruption might be caused by a change of the network or Internet network error.

In the everyday life of home workers and road warriors, a drop of a VPN connection leads to hectic activity, because remote desktop clients stop at first and then try to reconnect. The file explorer gets stuck and then tries to display server shares desperately. With a quick click, the experienced power user tries to reconnect the VPN before all applications say goodbye with a timeout error message and all programs have to be restarted. However, this does not succeed in all cases…

For these circumstances, Microsoft simply forgot the feature of an automatic reconnection for VPN connections. Probably, there is always somewhere a checkbox which is missing desperately…

Configuration and Script Code

VPN Connection Setup

To configure the automatic reconnection of a VPN, user name and password must be stored in the Windows Credential Manager. This behavior is specified during the setup:

Image 1

If the option «Remember my credentials» is checked, Windows will save the user name and password after the first connection of the VPN.

Reconnection with the Task Scheduler

Then, the reconnect VPN feature can be configured with build-in Windows tools. Starting point are the Windows event logs in which the following events occur:

Event Id Source Description
20226 RasClient ROUTERLOG_CORR_ID = The user %1 () dialled a connection named %2 () which has been terminated. The reason code returned on termination is %3 ().
10000 NetworkProfile Network connected.

Event 2226 occurs when a VPN connection has been terminated. In this case, an attempt is made to reconnect the VPN immediately. If the reconnection fails, the events 10000 and 8001 trigger a reconnection in the case of a new wired or WiFi network connection of the client.

A task can be imported as «My Connection (VPN) Redial.xml» with an XML format into the Task Scheduler and executed with the logged in user account:

  1  ="1.0"="UTF-16"
  2  <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  3    <RegistrationInfo>
  4      <Date>2020-04-11T09:32:43.9830717</Date>
  5      <Author>LOGICLINKmarcus</Author>
  6      <URI>My Connection (VPN) Redial</URI>
  7    </RegistrationInfo>
  8    <Triggers>
  9      <EventTrigger>
 10        <Enabled>true</Enabled>
 11        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 12         Path="Application"&gt;&lt;Select Path="Application"
 13         &gt;*[System[Provider[@Name='RasClient'] and EventID=20226]]
 14         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 15      </EventTrigger>
 16      <EventTrigger>
 17        <Enabled>true</Enabled>
 18        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 19         Path="Microsoft-Windows-NetworkProfile/Operational"&gt;
 20         &lt;Select Path="Microsoft-Windows-NetworkProfile/Operational"
 21         &gt;*[System[Provider[@Name='NetworkProfile'] and EventID=10000]]
 22         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 23      </EventTrigger>
 24    </Triggers>
 25    <Principals>
 26      <Principal id="Author">
 27        <LogonType>InteractiveToken</LogonType>
 28        <RunLevel>LeastPrivilege</RunLevel>
 29      </Principal>
 30    </Principals>
 31    <Settings>
 32      <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
 33      <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
 34      <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
 35      <AllowHardTerminate>true</AllowHardTerminate>
 36      <StartWhenAvailable>false</StartWhenAvailable>
 37      <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
 38      <IdleSettings>
 39        <StopOnIdleEnd>true</StopOnIdleEnd>
 40        <RestartOnIdle>false</RestartOnIdle>
 41      </IdleSettings>
 42      <AllowStartOnDemand>true</AllowStartOnDemand>
 43      <Enabled>false</Enabled>
 44      <Hidden>false</Hidden>
 45      <RunOnlyIfIdle>false</RunOnlyIfIdle>
 46      <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
 47      <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
 48      <WakeToRun>false</WakeToRun>
 49      <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
 50      <Priority>7</Priority>
 51    </Settings>
 52    <Actions Context="Author">
 53      <Exec>
 54        <Command>%SystemRoot%System32rasdial.exe</Command>
 55        <Arguments>"My Connection (VPN)"</Arguments>
 56      </Exec>
 57    </Actions>
 58  </Task>

In line 55, the name of the VPN connection must be changed to the name of your VPN connection. The VPN connection should have been established manually with user and password before the first use. Thus, credentials do not have to be entered as parameters for rasdial.exe and stored in the task.

Furthermore, the task should be deactivated by default and only activated when the VPN is needed, thereby it does not establish VPN connections and consume bandwidth unnecessarily.

Activation and Connection of the VPN

The activation and deactivation are done by two batch programs:

The batch file «Enable My Connection (VPN).cmd» activates the task for automatic reconnection and then connects the VPN:

  1  @echo off
  2  
  3  
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /ENABLE
 16  runas /trustlevel:0x20000 "rasdial.exe "%VPN%""

In lines 4 and 5, the two variables VPN and TASK identify the VPN connection and the task of the Task Scheduler and must be changed to your individual names accordingly. Using these variables, you can configure multiple batch files for several VPNs.

In the next step, the batch file checks if it was started with administrative rights. The administrative rights are required for the activation of tasks in Task Scheduler. If the batch file was not “Run as administrator”, an error message is displayed and the batch file terminates.

Next, the task TASK is activated in the Task Scheduler. For the connection of the VPN with stored credentials, administrative rights have to be returned. Thus, rasdial.exe is called via runas.exe with user rights by the trustlevel 0x20000.

Disconnection and Deactivation of the VPN Connection

The deactivation and disconnection is done in the batch file «DisableMy Connection (VPN).cmd» by the same commands:

  1  @echo off
  2  
  3  
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /DISABLE
 16  rasdial "%VPN%" /DISCONNECT

The two variables VPN and TASK in lines 4 and 5 must be changed according to your names also. During the termination of the VPN connection, the administrative rights do not interfere and therefore, rasdial.exe can be called directly.

References

  • RasClient 20226 event
  • Auto Reconnect VPN on Disconnection due to any reason – Persistent VPN

History

  • 4th May, 2020: Initial version

This tip is about how to setup a VPN connection and reconnect with the task scheduler. You will learn about activation, connection, disconnection and deactivation of the VPN connection.

  • Download VPNRedial.zip — 2.2 KB

Introduction

During Corona times, home office becomes more and more important. Company’s resources are accessed by Virtual Private Networks (VPN). When using the build-in Windows VPN Client for PPTP, L2TP/IPSec, SSTP or IKEv2, connections are not reestablished automatically if the connection is lost. A VPN interruption might be caused by a change of the network or Internet network error.

In the everyday life of home workers and road warriors, a drop of a VPN connection leads to hectic activity, because remote desktop clients stop at first and then try to reconnect. The file explorer gets stuck and then tries to display server shares desperately. With a quick click, the experienced power user tries to reconnect the VPN before all applications say goodbye with a timeout error message and all programs have to be restarted. However, this does not succeed in all cases…

For these circumstances, Microsoft simply forgot the feature of an automatic reconnection for VPN connections. Probably, there is always somewhere a checkbox which is missing desperately…

Configuration and Script Code

VPN Connection Setup

To configure the automatic reconnection of a VPN, user name and password must be stored in the Windows Credential Manager. This behavior is specified during the setup:

Image 1

If the option «Remember my credentials» is checked, Windows will save the user name and password after the first connection of the VPN.

Reconnection with the Task Scheduler

Then, the reconnect VPN feature can be configured with build-in Windows tools. Starting point are the Windows event logs in which the following events occur:

Event Id Source Description
20226 RasClient ROUTERLOG_CORR_ID = The user %1 () dialled a connection named %2 () which has been terminated. The reason code returned on termination is %3 ().
10000 NetworkProfile Network connected.

Event 2226 occurs when a VPN connection has been terminated. In this case, an attempt is made to reconnect the VPN immediately. If the reconnection fails, the events 10000 and 8001 trigger a reconnection in the case of a new wired or WiFi network connection of the client.

A task can be imported as «My Connection (VPN) Redial.xml» with an XML format into the Task Scheduler and executed with the logged in user account:

  1  ="1.0"="UTF-16"
  2  <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  3    <RegistrationInfo>
  4      <Date>2020-04-11T09:32:43.9830717</Date>
  5      <Author>LOGICLINKmarcus</Author>
  6      <URI>My Connection (VPN) Redial</URI>
  7    </RegistrationInfo>
  8    <Triggers>
  9      <EventTrigger>
 10        <Enabled>true</Enabled>
 11        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 12         Path="Application"&gt;&lt;Select Path="Application"
 13         &gt;*[System[Provider[@Name='RasClient'] and EventID=20226]]
 14         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 15      </EventTrigger>
 16      <EventTrigger>
 17        <Enabled>true</Enabled>
 18        <Subscription>&lt;QueryList&gt;&lt;Query Id="0" 
 19         Path="Microsoft-Windows-NetworkProfile/Operational"&gt;
 20         &lt;Select Path="Microsoft-Windows-NetworkProfile/Operational"
 21         &gt;*[System[Provider[@Name='NetworkProfile'] and EventID=10000]]
 22         &lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;</Subscription>
 23      </EventTrigger>
 24    </Triggers>
 25    <Principals>
 26      <Principal id="Author">
 27        <LogonType>InteractiveToken</LogonType>
 28        <RunLevel>LeastPrivilege</RunLevel>
 29      </Principal>
 30    </Principals>
 31    <Settings>
 32      <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
 33      <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
 34      <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
 35      <AllowHardTerminate>true</AllowHardTerminate>
 36      <StartWhenAvailable>false</StartWhenAvailable>
 37      <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
 38      <IdleSettings>
 39        <StopOnIdleEnd>true</StopOnIdleEnd>
 40        <RestartOnIdle>false</RestartOnIdle>
 41      </IdleSettings>
 42      <AllowStartOnDemand>true</AllowStartOnDemand>
 43      <Enabled>false</Enabled>
 44      <Hidden>false</Hidden>
 45      <RunOnlyIfIdle>false</RunOnlyIfIdle>
 46      <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
 47      <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
 48      <WakeToRun>false</WakeToRun>
 49      <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
 50      <Priority>7</Priority>
 51    </Settings>
 52    <Actions Context="Author">
 53      <Exec>
 54        <Command>%SystemRoot%System32rasdial.exe</Command>
 55        <Arguments>"My Connection (VPN)"</Arguments>
 56      </Exec>
 57    </Actions>
 58  </Task>

In line 55, the name of the VPN connection must be changed to the name of your VPN connection. The VPN connection should have been established manually with user and password before the first use. Thus, credentials do not have to be entered as parameters for rasdial.exe and stored in the task.

Furthermore, the task should be deactivated by default and only activated when the VPN is needed, thereby it does not establish VPN connections and consume bandwidth unnecessarily.

Activation and Connection of the VPN

The activation and deactivation are done by two batch programs:

The batch file «Enable My Connection (VPN).cmd» activates the task for automatic reconnection and then connects the VPN:

  1  @echo off
  2  
  3  
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /ENABLE
 16  runas /trustlevel:0x20000 "rasdial.exe "%VPN%""

In lines 4 and 5, the two variables VPN and TASK identify the VPN connection and the task of the Task Scheduler and must be changed to your individual names accordingly. Using these variables, you can configure multiple batch files for several VPNs.

In the next step, the batch file checks if it was started with administrative rights. The administrative rights are required for the activation of tasks in Task Scheduler. If the batch file was not “Run as administrator”, an error message is displayed and the batch file terminates.

Next, the task TASK is activated in the Task Scheduler. For the connection of the VPN with stored credentials, administrative rights have to be returned. Thus, rasdial.exe is called via runas.exe with user rights by the trustlevel 0x20000.

Disconnection and Deactivation of the VPN Connection

The deactivation and disconnection is done in the batch file «DisableMy Connection (VPN).cmd» by the same commands:

  1  @echo off
  2  
  3  
  4  set VPN=My Connection (VPN)
  5  set TASK="My Connection (VPN) Redial"
  6  
  7  
  8  net session >nul 2>&1
  9  if NOT %errorLevel% == 0 (
 10  	echo Current permissions insufficient. Run script as administrator.
 11  	pause
 12  	exit 1
 13  )
 14  
 15  schtasks /Change /TN %TASK% /DISABLE
 16  rasdial "%VPN%" /DISCONNECT

The two variables VPN and TASK in lines 4 and 5 must be changed according to your names also. During the termination of the VPN connection, the administrative rights do not interfere and therefore, rasdial.exe can be called directly.

References

  • RasClient 20226 event
  • Auto Reconnect VPN on Disconnection due to any reason – Persistent VPN

History

  • 4th May, 2020: Initial version

Как известно, в Windows из коробки напрочь отсутствует способ автоматического дозвона, в частности установления надёжного соединения по VPN, чтобы оно не разрывалось никогда, и всегда восстанавливалось в случаях временного исчезновения интернета. Такая возможность давно есть в роутерах, например Mikrotik, но что делать, если в сети такого роутера нет и соединение необходимо поднять на Windows, причём исключительно средствами системы? Для этого нам на помощь приходит планировщик заданий и команда бесконечного дозвона из командной строки.

Первое, что нужно сделать — создать само VPN-соединение с нужными нам настройками, назовём его SmartVPN. По ходу мастера настройки обязательно нужно отметить «Разрешить использовать это подключение другим пользователям», так как дозваниваться мы будем от имени системы.

В параметрах соединения убираем галочки:

  • Отображать ход подключения
  • Запрашивать имя, пароль, сертификат и т. д.
  • Включать домен входа в Windows
  • Перезвонить при разрыве связи

При необходимости убираем использование основного шлюза в удалённой сети и корректируем другие настройки.

Второй этап состоит из создания задачи по запуску бесконечного цикла, который будет проверять и восстанавливать соединение, если оно не подключено. Для этого в планировщике создаём задачу, которая будет запускаться при включении компьютера и запускаться от имени системы, а действием указываем запуск программы:

cmd /c "for /l %x in (0,0,0) do (rasdial SmartVPN Login Pass & timeout 5)"

Где cmd — программа командной строки, а остальное — её параметры, при этом SmartVPN — название соединения, Login и Pass — логин и пароль для дозвона соответственно.

Команда timeout делает паузу в 5 секунд перед следующей попыткой дозвона, при этом если соединение уже установлено, то ничего не произойдёт. Также timeout не существует на WinXP/2003, так что если вы где-то её используете, нужно будет городить замену через ping. Запуск от имени системы позволяет скрыть консольные окна и дозвон можно будет увидеть разве что в процессах и по запущенной задаче в планировщике. Существует не консольная программа дозвона rasphone, где пароль указывать не нужно (будет использован сохранённый в системе для этого соединения), но пользоваться ей никак нельзя — при ошибках она будет выводить графические сообщения и дозвон прекратится.

P. S. Если вы хотите сделать так, чтобы задача не висела в планировщике в статусе работы, замените «cmd /c» в начале команды на «cmd /c start cmd /c», таким образом процесс дозвона дальше не будет зависеть от планировщика.

Готовый xml-файл задачи для импорта: SmartVPN.xml [3 KB]

В настоящее время я подключаюсь к Интернету через привязанное соединение с моей мобильной сетью передачи данных. Чтобы обойти провайдеров мобильной сети, настаивая на том, чтобы я платил им за использование той же услуги через другое устройство, я также использую VPN для фактического подключения к Интернету. Естественно, сетевой сигнал может легко пропадать и прерывать соединение, и это отключает VPN, даже если само привязанное соединение никогда не отключается.

По иронии судьбы отличный пример моей проблемы можно найти на следующей странице Microsoft Technet, посвященной замечательному решению для Windows 7 / Windows Server 2008 R2:https://technet.microsoft.com/en-us/library/dd637830(v= ws.10).aspx

Например, рассмотрим пользователя, едущего на работу в поезде. Чтобы максимально использовать свое время, она использует беспроводную мобильную широкополосную карту для подключения к Интернету, а затем устанавливает VPN-подключение к сети своей компании. Когда поезд проходит через туннель, она теряет подключение к Интернету. После выхода из туннеля беспроводная мобильная широкополосная карта автоматически подключается к Интернету. Однако в более ранних версиях Windows VPN не переподключается, и ей необходимо повторить многоэтапный процесс подключения к VPN. Это может быстро занять много времени для мобильных пользователей с прерывистой связью.

Однако я не могу найти ни следа этой функции в Windows 10, ни чего-либо подобного. Есть ли способ, чтобы VPN-соединение всегда пыталось переподключиться до тех пор, пока я не отключу явно (например, опция «Автоматически подключаться» в обычных сетях), или просто оставалось в живых, чтобы оно могло возобновиться после восстановления сетевого подключения?

Время на прочтение
2 мин

Количество просмотров 9.2K

Мой компьютер включен почти всегда. Редкое исключение — длительные поездки далеко за пределы ДС.
Включен почти всегда, потому что очень часто, когда я нахожусь вне дома (на работе, в гостях, просто летом на даче), возникает необходимость зайти на него (по http или же через Remote Desktop) за какими-либо данными.

Всё бы ничего, но доступ в интернет обеспечивается через VPN-соединение.
Которое иногда обрывается. Из-за проблем у провайдера, из-за перезагрузки системы после установки критичных апдейтов или еще по каким-либо причинам.

До недавнего времени каждый такой обрыв связи приводил к тому, что находясь вне дома, я терял возможность подсоединиться к компьютеру до возвращения домой и запуску VPN-соединения вручную. Пока однажды не решил разобраться в проблеме и сделать решение, которое позволило бы забыть про подобные неприятные ситуации.

Покопавшись в интернете, обнаружил, что запустить соединение можно, используя программу rasdial.exe, входящую в стандартный набор Windows:

C:Windowssystem32rasdial.exe элемент [пользователь [пароль|*]] [/DOMAIN:домен]
[/PHONE:номерТелефона] [/CALLBACK:ответныйНомер]
[/PHONEBOOK:файлАдреснойКниги] [/PREFIXSUFFIX]

Ну а дальше запустить соединение по расписанию — дело техники.
Кому-то ближе Планировщик задач + bat-файлы, мне ближе cron + perl.
Как и отношение к цвету и вкусу фломастеров, сложность скрипта — личное дело каждого.

Можно даже так:

c:windowssystem32rasdial.exe "имя_vpn_соединения" имя_юзера пароль_юзера

А можно чуть сложнее.
Например, у меня сначала идет проверка доступности канала (пингом на определенные адреса), а потом запуск одного из VPN-соединений. В случае его недоступности — запуск другого и так далее.

Еще один интересный случай (хотя реже нужный кому-либо) применения автозапуска VPN — переключение между несколькими соединениями по расписанию, например, для использования ночью одного, а днем другого. В этом случае поможет опция «разорвать соединение»:

C:Windowssystem32rasdial.exe [элемент] /DISCONNECT

Единственный нюанс, на который нужно обратить внимание — под каким пользователем будет выполняться скрипт, управляющий соединениями. Если VPN-соединение не расшарено между всеми пользователями системы, при запуске скрипта по расписанию система может не найти соединение, поскольку по умолчанию задачи запускаются с правами системного пользователя, а не того, под которым шла отладка.

If you’re attempting to get some semblance of stability using Windows built-in VPN networking and finding that there really is none, here’s a quick little setup that can at least keep you connected to wherever your VPN tunnel leads.

This assumes you’re using Windows 10 built-in VPN and probably something equally lacking in features on the other side, such as if you’ve had to rig up a software VPN with no budget and minimal time, or you just hate working software. This probably will work with older versions of Windows, but here are two parts of it that work in Windows 10 and screenshots.

This also assumes security is not something you’re really considering as you’re going to be putting a password in plain text in a task. I’ll assume you work for whatever major company got caught not storing their passwords hashed this week, that or you’re just rigging something for an offsite backup.

The first is the command line to connect your VPN. You’ll need to know what you named it, you’ll need to know your user name, and you’ll need to know your password.

So check that one of the following commands actually will connect you by opening a command prompt and typing them out.

c:\Windows\System32\rasdial.exe connection_name user_name password

If you’re logging in with a domain name it’s more in the format

c:\Windows\System32\rasdial.exe connection_name user_name password /DOMAIN:domainname

If neither of those work, stop, nothing to be gained by going forward

Create a reconnect task

Your VPN gets disconnected a lot, you can schedule a reconnect every X minutes. Alternately you can create a triggered task that looks for a disconnect. Your RasClient disconnect task event ID is 20226 from Application log, source RasClient.

Below are the three task manager screens you’ll be working on to create your VPN reconnect task.

Task Scheduler general

Task Scheduler action

Trigger warning

Security warning

You just saved your VPN password in plain text in a task scheduler. While probably not a big deal if you’re dealing with having to use the built-in networking components with your work, might be aware that you’re really throwing security right out the window if anyone managed to get access to your computer.

If you’re worried about saving the password and just want a prompt to reconnect you could just create a triggered task to open Notepad with a text document telling you you’ve been disconnected again.

Groundhog day warning

You’ve created a task that automatically reconnects you if you’ve been disconnected. This does not stop when you click disconnect, nope, 30 seconds or whatever you put in later you’re reconnected. While it’s easy enough to kill or pause the task, it’ll be just about as inconvenient as standard Windows 10 VPN is in the first place.

Seriously, why is there no option to redial in 2018?

Alternate useful command

If you’re just connecting and disconnecting for remote syncing or something after connecting and doing your business another useful command is rasdial [entryname] /DISCONNECT. You can omit the entryname if you’re only dealing with one VPN.

Pocketables does not accept targeted advertising, phony guest posts, paid reviews, etc. Help us keep this way with support on Patreon!

Become a patron at Patreon!

windows

  • Windows

  • VPN

Есть настроенное VPN соединение в Windows 10. Оно периодически рвётся. Вопрос, как сделать проверку соединения и если оно отсутствует запускать?


  • Вопрос задан

  • 630 просмотров


Комментировать


Решения вопроса 2

tsklab

vpn-connection-options-windows-7.jpg

  • bag05

    @bag05 Автор вопроса

    У меня таких опций нет 5dd774dba0d0e197381984.png

PrAw

@remzalp

Программер чего попало на чем попало

В Windows 10 простого варианта не осталось.

https://www.pocketables.com/2018/06/how-to-automat…
Жестокая последовательность. Делается через планировщик задач
Суть — использовать консольную программу rasdial для восстановления в случае, если в журнале событий появится событие RasClient event ID 20226


Комментировать

Пригласить эксперта


Похожие вопросы


  • Показать ещё
    Загружается…

09 окт. 2023, в 10:05

30000 руб./за проект

09 окт. 2023, в 10:04

60000 руб./за проект

09 окт. 2023, в 10:01

10000 руб./за проект

Минуточку внимания

  • Windows 10 vpn выполняется подключение
  • Windows 10 vpn отключается сам
  • Windows 10 vpn настройка маршрутизации
  • Windows 10 vpn l2tp без ipsec
  • Windows 10 vpn error 809