C удивлением, правда небольшим, обнаружил, что в Windows, начиная с версии 8 и в Windows Server, начиная с 2008, Microsoft слегка «доработал напильником» диалог настроек VPN соединения. Точнее, урезал настраиваемые параметры на вкладке Options. Вместо того, что было привычно в Windows 7 и выглядело как:
Теперь убрали практически все и оставили только:
И возник закономерный вопрос– а как теперь настроить автоматическое переподключение и количество попыток повтора соединения если связь прервется?
Методов несколько. Давайте по порядку. По мере возрастания, так сказать, сложности.
Метод 1 — используем Notepad:
Установить нужные параметры вручную. Для этого необходимо перейти в папку
То есть опять “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 соединения выглядит так
<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>
Название лога: Microsoft-Windows-NetworkProfile/Operational
Источник : NetworkProfile
Event ID: 10000
В качестве запускаемой программы, выбираем rasdial.exe с параметрами vpn-name username password
Дополнительно, на вкладке Conditions, можно доопределить следующие параметры
Примечание: Чтобы убедиться заработает такая задача или нет, создайте еще один триггер с Event ID = 10001. Этoт Event появляется при ручном отключении (disconnet) VPN. После этого попробуйте вручную отключить VPN. Соединение сразу же будет восстановлено.
Ну вот, собственно и все.
Примечание Все описанное работает и в Windows 7
Далее под спойлером привожу, без перевода, длинное, подробное и нудное описание Метода 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 😉
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
Click Windows8 Start and type Schedule Task (open it under Settings)
Click Create Task
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 <QueryList> to </QueryList>
<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>
Click OK
Ensure Enabled is checked Check it if it’s not checked to make sure the job will be enabled
Click Ok
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
Click Ok
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
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.
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.
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’]]</Select>
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.
Ё-моё…. А нет способа вернуть визуальные настройки в окно диалога настроек VPN соединения? Что то уж совсем M$ людей за лохов держит.
Ответить
Alex Kornev29.01.2016
Я не нашел такого способа. Рыл сеть долго. Видимо никто не нашел. Расчет M$ на то, что связь не должна рваться, в нормальной ситуации. Я бы еще «доработочку» ввел. Пока не знаю как. При создании нового VPN соединения снимать галку в Networking -> IPv4 Properties -> Advanced -> Use default gateway on remote network. Очень мешает. Приходится _каждый_ раз ходить и снимать эту «галку». https://winitpro.ru/index.php/2020/04/09/net-dostupa-v-internet-pri-aktivnom-vpn/
Ответить
therealman™11.09.2017
Будь проклят Microsoft! 1й способ не работает!
Ответить
therealman™11.09.2017
Будь проклят Microsoft! 1й способ не работает!
Ответить
Adept17.04.2018
IdleDisconnectSeconds=0
это сколько секунд должно работать подклчение. Поставите 60 — будет каждую минуту отключаться
Ответить
Alex Kornev17.04.2018
Вы плохо поняли, что написано и не правильно прокомментировали Этот параметр — «Сколько ждать, прежде чем решить, что VPN отвалился».
Ответить
Гена21.05.2018
The IdleDisconnectSeconds key specifies the number of seconds after which the demand-dial connection is terminated due to inactivity. This key is optional. If the key is present, the value SHOULD be a number in the range 0 to 4294967296.
VPN будет автоматически ОТКЛЮЧАТЬСЯ через заданное в этом параметре время.
Ответить
Alex Kornev24.05.2018
Google переводчмк вам в помощь ….. там же все англйским по белому написано просто и четко
Ответить
Гена21.05.2018
0 — не будет отключаться, то есть, не надо его трогать.
Ё-моё….
А нет способа вернуть визуальные настройки в окно диалога настроек VPN соединения? Что то уж совсем M$ людей за лохов держит.
Я не нашел такого способа. Рыл сеть долго. Видимо никто не нашел. Расчет M$ на то, что связь не должна рваться, в нормальной ситуации.
Я бы еще «доработочку» ввел. Пока не знаю как. При создании нового VPN соединения снимать галку в Networking -> IPv4 Properties -> Advanced -> Use default gateway on remote network. Очень мешает. Приходится _каждый_ раз ходить и снимать эту «галку».
https://winitpro.ru/index.php/2020/04/09/net-dostupa-v-internet-pri-aktivnom-vpn/
Будь проклят Microsoft! 1й способ не работает!
Будь проклят Microsoft! 1й способ не работает!
IdleDisconnectSeconds=0
это сколько секунд должно работать подклчение. Поставите 60 — будет каждую минуту отключаться
Вы плохо поняли, что написано и не правильно прокомментировали
Этот параметр — «Сколько ждать, прежде чем решить, что VPN отвалился».
The IdleDisconnectSeconds key specifies the number of seconds after which the demand-dial connection is terminated due to inactivity. This key is optional. If the key is present, the value SHOULD be a number in the range 0 to 4294967296.
VPN будет автоматически ОТКЛЮЧАТЬСЯ через заданное в этом параметре время.
Google переводчмк вам в помощь ….. там же все англйским по белому написано просто и четко
0 — не будет отключаться, то есть, не надо его трогать.