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.

Читайте также:  Msdart для всех windows

Сохранение пользователя Всегда на предпочтении 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_MACHINE\SYSTEM\CurrentControlSet\Services\RasMan\Config Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\RasMan\Config
Значение: 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.

Авто переподключение 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-соединение всегда пыталось переподключиться до тех пор, пока я не отключу явно (например, опция «Автоматически подключаться» в обычных сетях), или просто оставалось в живых, чтобы оно могло возобновиться после восстановления сетевого подключения?

Читайте также:  Total commander windows flash

AutoRedial для VPN соединений Windows 8/2008/10/2012

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

Теперь убрали практически все и оставили только:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Указать выполняемый файл, например, такой

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

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

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

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

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

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

Had this problem for a few weeks but finally got a chance to spend some time on it last night. Came across this thread….My guess is that with Microsoft making the VPN connection RT-Like, they missed part of the dialog or put it that way for RT Tablets with the thought that you wouldn’t want the VPN reconnecting and using up data/battery. Of course they missed the point of keeping it for desktops…..

Anyways I was hoping that the dialogs info was missed by the actual code wasn’t as is the case sometimes. Looked promising when I checked the VPN config and found the settings generated in a Windows 8 connection. Unfortunately while the settings are enabled for redial, the redial function doesn’t work. I tried establishing a VPN connection with rasdial though dos but still no luck. Just occurred to me as I’m typing this email that I may try renaming the rasdial.pbk and loading it with the Rasdial comment to establish a VPN connection, maybe it will use the settings. Will give it a try later.

The C:\Users\Joe\AppData\Roaming\Microsoft\Network\Connections\Pbk\rasphone.pbk actually has the redial settings enabled in it…

RedialAttempts=3
RedialSeconds=60
IdleDisconnectSeconds=0
RedialOnLinkFailure=1 (This is set to one in Windows 7 when you enable the Redial checkbox)

In case anyone is interested, came up with a fairly good workaround last night until MS releases an update to put the settings back. I like this solution better than running a 3rd party solution to try to keep the VPN up. You can setup a Task Schedule job to trigger on a disconnect. I gave it a try last night and the VPN immediately reconnected. I’m checking for client/remote disconnect error codes excluding the «user disconnect» code to avoid it reconnecting when you actually want to disconnect. These are just two error codes I noted in the event log, MS lists a lot more error codes but I haven’t experienced them on disconnects though they could be added. If anyone uses this and thinks more codes should be added please update the xml query or let me know and I’ll update it. Forgive the XML query, not something I usually do so if it can be formatted better, let me know…for learning 😉

Читайте также:  Linux рассказать про систему

Here is a list of some error codes (this is not complete for Win8 but I didn’t spend much time searching)

How to setup a Scheduled Task to Trigger on a VPN Disconnect

  1. Click Windows8 Start and type Schedule Task (open it under Settings)
  2. Click Create Task
  3. Apply the following settings in the specified Tabs (italics describes each setting)

General Tab

Name: VPN Redial
For descriptive use, you can use any name you want like My Company VPN Redial….whatever…..

Select: Run whether user is logged on or not
Provided you have a password associated to your login account, this option will prevent the dos window from opening everytime the job runs. If you don’t have a password, leave it and see the notes below these steps.
Triggers Tab

Click New button
To create a new trigger we will use to activate the job when the VPN connect disconnects

Begin the task: On an Event
The job will be triggered by an Application event log entry

Select: Custom
Custom gives us the flexibility of creating a more detailed query

Click New Event Filter… button
Here is where we build the query for the trigger

Click the XML tab
This tab allows us to write our own query (even more flexible)

Check Edit query manually
To start a manual edit

Copy the following query
This query will trigger on an Application Event for RasClient with an EventID of 20226 and error codes 829 (Remote Disconnect), 629 (Client Disconnect). Copy from and including to

Ensure Enabled is checked
Check it if it’s not checked to make sure the job will be enabled

Actions Tab

Click New
To create an action to be performed when the job is triggered

Action: Start a program
Selection this option will allow us to start rasdial to reestablish the VPN connection

Program/script: rasdial
Should already be in path so just enter rasdial command

Add arguments (optional): «VPN Name» username password
VPN name is the name you defined for your dialup connection. Example, when you click the network icon in the system tray, the name that’s listed for your VPN, make sure you enter it in exactly as displayed. Following the connect would be your username and password. Example, «MY VPN Connection» username password

Conditions Tab (not required unless you are using a laptop)

Uncheck: Stop if the computer switches to battery power

Settings TAB

Enable: If the task fails, restart every: 1 minute
In case there is a temporary issue re-establishing the VPN connection. You can specify whatever value you want instead of 1 minute

Attempt to restart up to: 7 times
Again in case there is a temporary issue re-establishing the VPN connection. You can specify whatever value you want instead of 7 times

Click Ok
Notes

  1. Haven’t really tested this much but I had configured it last night, woke up this morning to find the Event log showing 4 disconnects, and the job redialed all 4 times, VPN connection was still active.
  2. In the General Tab we enabled «Run whether user is logged on or not. This is a non issue since there won’t be a VPN connection when you’re not logged in. What this option does since we are running a dos (rasdial) command, it prevent a dos window from opening every time the job runs so you won’t be distracted if you’re in the middle of something. This option only works if you have a password (which you should) associated with your account. If you don’t and just allow your computer to boot to desktop, the option won’t work. What I’ve done for people in these situations is created a little VBScript wrapper to launch the dos command to avoid the dos prompt. Not really an issue unless you’re anal about it like me, you could simply deal with the Dos window opening up.
  3. Again the query checks the event log for a new Entry for RasClient with an event id of 20226 containing error codes 820 or 620. you can add additional error codes by repeating the pattern. Example to also trigger on 222 and 333 you would modify the relevant part of the line as such *[EventData[Data[4]=’829′ or ‘629’ or ‘222’ or ‘333’]]

4. I’m checking error codes because I don’t want the job to be reconnected if I purposely disconnect the VPN which generates a 631 code under Event ID 20226.

Оцените статью