The lack of standards in this area means that most OSes have a different way of configuring daemons/services for autostart on boot. The best way to have this functionality configured by default is to install OpenVPN as a package, such as via RPM on Linux or using the Windows installer.
Linux
If you install OpenVPN via an RPM or DEB package on Linux, the installer will set up an initscript. When executed, the initscript will scan for .conf configuration files in /etc/openvpn, and if found, will start up a separate OpenVPN daemon for each file.
Windows
The Windows installer will set up a Service Wrapper, but leave it turned off by default. To activate it, go to Control Panel / Administrative Tools / Services, select the OpenVPN service, right-click on properties, and set the Startup Type to Automatic. This will configure the service for automatic start on the next reboot.
When started, the OpenVPN Service Wrapper will scan the \Program Files\OpenVPN\config-auto folder for .ovpn configuration files, starting a separate OpenVPN process on each file.
Note: on older versions of OpenVPN GUI, the ‘config’ directory used to be a store for all configurations, and the service would just start all configurations there. As of version 2.5.0, the ‘config’ directory is for configs for the GUI component, and the ‘config-auto’ directory is for the service wrapper to auto-start configurations from.
В этой статье мы рассмотрим, как настроить автоматическое подключение к OpenVPN серверу при входе пользователя в Windows с помощью ярлыка в автозапуске и с помощью службы Windows.
Автозапуск клиента OpenVPN при входе в Windows
Скопируйте ваш *.ovpn файл с настройками вашего VPN подключения в каталог C:\Users\YourUsernName\OpenVPN\config
или в C:\Program Files\OpenVPN\config
.
Теперь вам нужно открыть каталог автозапуска в Windows. Для этого нажмите сочетание клавиш Win+R и выполните команду shell:startup
. Перед вами откроется папка в профиле текущего пользователя ((%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup). Windows при входе пользователя в систему автоматически запускает все программы из этой папки.
Если у вас используется клиент openvpn-gui.exe (OpenVPN 2.5), то для автоматического подключения с помощью указанного профиля из файла *.ovpn используется команда:
"C:\Program Files\OpenVPN\bin\openvpn-gui.exe" --connect your_vpn_connection.ovpn
Просто скопируйте ярлык OpenVPN GUI в каталог Startup и настройках ярлыка добавьте параметр --connect your_vpn_connection.ovpn
.
Если вы хотите скрыть окно состояния клиента OpenVPN при подключении, добавьте в строку параметр --silent_connection 1
.
Теперь запустите клиент OpenVPN и отключите автоматический запуск при загрузке Windows (вкладка General -> Launch on Windows startup). Это позволит предотвратить конфликт с командой автозагрузки, которую мы создали ранее.
Теперь Windows будет автоматически устанавливать подключение с OpenVPN сервером при входе пользователя.
Если у вас используется клиент OpenVPNConnect.exe (3.3.x) от OpenVPN вместо комьюнити клиента, имейте в виду, что в нем пока нет опций командной строки для подключения к серверу с помощью настроенного профиля.
В настройках клиента OpenVPN Connect можно включить опцию Lauhch options -> Connect latest. В этом случае клиент будет автоматически подключаться с помощью последнего используемого ovpn профиля.
Эту же опцию можно включить из командной строки:
C:\Program Files\OpenVPN Connect\OpenVPNConnect.exe --set-setting launch-options:connect-latest
В этом примере мы показали, как настроить автоматическое OpenVPN подключение для одного пользователя Windows. Если вам нужно настроить автоподключение для всех пользователей, можно создать аналогичное задание в Task Scheduler или настроить службу OpenVPN.
Запуск клиента OpenVPN как службы Windows
Вы можете настроить автоматическое подключение с помощью службы OpenVPN Service, которая позволит автоматически поднимать VPN подключение до входа пользователя в Windows.
Если у вас используется клиент OpenVPN Connect 3.2+, вы можете запустить службу OpenVPN, которая будет автоматически подключаться к OpenVPN серверу после загрузки Windows.
- Откройте командную строку с правами администратора и перейдите в каталог:
cd "c:\Program Files\OpenVPN Connect"
- Установите службуOVPNConnectorService:
ovpnconnector.exe install
- Задайте полный путь к конфигурационному файлу OVPN, который нужно использовать для подключения:
ovpnconnector.exe set-config profile "C:\OpenVPN\client.ovpn"
- Укажите имя файла, куда нужно записыват логи VPN подключения:
ovpnconnector.exe set-config log "C:\OpenVPN\client.log"
Логи OpenVPN также доступны в стандартном Event Viewer в разделе Windows Logs -> Applications -> включите фильтр по Event Source OVPNConnectorService.
- Запустите службу OpenVPN:
ovpnconnector.exe start
Проверьте, что клиент успешно подключится в OpenVPN серверу. В логе должно появится сообщение:
Wed Feb 1 23:25:39 2023 Connected via TUN_WIN Wed Feb 1 23:25:39 2023 EVENT: CONNECTED YourOpenVPNProfile via /UDPv4 on TUN_WIN/10.24.1.10/ gw=[10.24.1.9/]
И ваш виртуальный адаптер WinTUN получил IP адрес от сервера OpenVPN
- Теперь настройте автоматический запуск для службы OVPNConnectorService из консоли управления services.msc или с помощью команды:
sc config OVPNConnectorService start=auto
- Теперь после перезагрузки Windows служба OpenVPN будет автоматически подключаться к серверу.
Если вы хотите отключить и удалить службу OVPNConnectorService, выполните команды:
ovpnconnector.exe stop
ovpnconnector.exe remove
Если у вас используется аутентификация OpenVPN ерез Active Directory, вы можете сохранить имя пользователя и пароль в текстовый файл и использовать его для автоматического подключения.
Создайте текстовый файл login.txt в каталоге C:\Program Files\OpenVPN\config.
И добавьте в конфигурационный файл ovpn строки:
auth-user-pass login.txt auth-retry nointeract auth-nocache
Если у вас используется клиент OpenVPN GUI, вы также можете настроить службу для автоматического подключения. Для этого:
- При установке клиента обязательно выберите дополнительно службу OpenVPN Service
- Скопируйте ваши профили OpenVPN (файлы с расширением .ovpn) в каталог
"C:\Program Files\OpenVPN\config\"
- Служба OpenVPN будет автоматически запускать VPN туннель для каждого конфигурационного ovpn файла из этого каталога)
Если на компьютере должны быть одновременно активны несколько OpenVPN подключений, убедитесь, что в Windows создано достаточное количество виртуальных сетевых адаптеров TUN/TAP. Иначе в логах появится ошибка All TAP-Windows adapters on this system are currently in use. Также рекомендуется привязать OpenVPN подключение к конкретному сетевому интерфейсу с помощью следующей строки в .ovpn:
dev-node 'OpenVPN TAP-Windows2'
(указывается имя сетевого адаптера в Window) - Проверьте что для службы OpenVPNService (
C:\Program Files\OpenVPN\bin\openvpnserv2.exe
) настроен автоматический запуск.
В Linux вы можете подключиться к VPN серверу из командной строки или автоматически с помощью стандартного сервиса openvpn@client.service.
Данные демон автоматически создает VPN подключения для всех конфигурационных файлов .conf в каталоге /etc/openvpn (просто переименуйте ваши *.ovpn файлы в *.conf). И запустите сервис:
$ sudo systemctl enable openvpn@client.service
$ sudo systemctl start openvpn@client.service
This is a guide explaining how you can set your OpenVPN client to run automatically when you start your computer. The guide is specific to Windows.
1. Task Scheduler
Click the Start button and go to Programs » Accessories » System. Then run Task Scheduler.
If you don’t have the Start button, just search for Task Scheduler.
Click Create basic task on the Actions menu on the right-hand side.
{<1>}
2. Create a basic task
Enter OpenVPN as the name for the new activity and click Next.
{<2>}
3. Set the trigger
It’s now time to set the trigger. Choose When I log on, and click Next.
{<3>}
4. Choose action
Under Action, choose Start a program, and click Next.
{<4>}
5. Choose an application to run
It’s time to choose the program that should be opened when you log in. Click Browse, and look up openvpn-gui.exe. Usually you can find the program in:
C:\Program Files\OpenVPN\bin
or
C:\Program Files (x86)\OpenVPN\bin
In the field Add arguments (optional ), type:
—connect «OVPN — Sverige.ovpn»
IF the configuration file you are using is named OVPN — Sverige.ovpn. If the name of your file is different, enter that name instead
{<5>}
6. Finishing up
Check the box Open the Properties dialog for this task when I click Finish.
Then click Finish.
{<6>}
7. Set user privileges
A new window should now open called Properties for OpenVPN (Local Computer). On the opened tab, check **Run with highest privileges **, and click OK.
{<7>}
Further configurations
If you’ve followed the steps in the guide, OpenVPN will now be run when you log in.
To automatically connect to OVPN, you need to make a few more configurations. This requires you to enter your username and password in a text file and save it on your computer.
If you are not comfortable with having a text file with your credentials saved, there is, unfortunately, no other way to automatically connect to OVPN on computer startup.
1 – Create a text file
Go to the configuration directory where you keep the configuration files for OVPN. Usually, they can be found in:
C:\Program Files\OpenVPN\config
or
C:\Program Files (x86)\OpenVPN\config
Create a file called password.txt. On the first line, write your username and on the second line your password.
Edit the configuration file that you are using to connect to OVPN by opening the file with a text editor such as Notepad++.
Find the command auth-user-pass and change it to auth-user-pass password.txt.
Then save the configuration file.
3. Done
You’re done! You can test it by logging out and in again. If you automatically connect to OVPN when you log in, it’s working!
In this article, we’ll look at how to automatically connect to an OpenVPN server when a user logs into Windows using a startup shortcut or using a Windows Service.
Autostart OpenVPN Client at Windows Startup
Copy your *.ovpn profile file with your VPN settings to C:\Users\YourUsernName\OpenVPN\config
or to C:\Program Files\OpenVPN\config
folder.
Now you need to open the Windows startup folder. To do this, press Win+R
and run the shell:startup
command. This will open the current user’s startup folder (%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
). Windows automatically runs all programs in this folder when the user logs on.
If you are using the openvpn-gui.exe
client (OpenVPN 2.5), then the following command is used to automatically connect using the specified profile in the *.ovpn file:
"C:\Program Files\OpenVPN\bin\openvpn-gui.exe" --connect your_vpn_connection.ovpn
Just copy the OpenVPN GUI shortcut to the Startup directory and add the --connect your_vpn_connection.ovpn
parameter in the shortcut settings. Or create a new shortcut, specify the full path to the openvpn-gui.exe
file, and add the --connect *.ovpn
parameter.
If you want to hide the OpenVPN status window when connecting to the server, add the --silent_connection 1
option to the startup command.
Now run the OpenVPN client and disable automatic launch at Windows startup (General tab -> Launch on Windows startup). This will prevent a conflict with the auto-connect command we created earlier.
Now Windows will automatically establish a connection with the OpenVPN server when the user signs in.
If you are using the OpenVPNConnect.exe
(3.3.x) client from OpenVPN instead of the community client, be aware that it doesn’t yet have command line options to connect to a VPN server using a configured profile file.
In the OpenVPN Connect client settings, you can enable the Connect latest option (under Launch options). In this case, the OpenVPN client will automatically connect using the last used ovpn profile.
Also, you can enable this option from the command prompt:
C:\Program Files\OpenVPN Connect\OpenVPNConnect.exe --set-setting launch-options:connect-latest
In this example, we have shown how to configure an automatic OpenVPN connection for a single Windows user. If you need to enable an automatic OpenVPN connection for all users, you can create a task in the Task Scheduler or enable the OpenVPN service.
Run the OpenVPN Client as a Windows Service to Connect Automatically
You can set up an automatic connection using the OpenVPN service, which will automatically establish the VPN connection before the user logs in to Windows. Using the OpenVPN Connect 3.2+ client, you can run the OpenVPN service that automatically connects to the OpenVPN server when Windows starts.
- Open a command prompt as an administrator and go to the directory:
cd "c:\Program Files\OpenVPN Connect"
- Install the OVPNConnectorService:
ovpnconnector.exe install
- Specify the full path to the OVPN configuration file to be used for the connection:
ovpnconnector.exe set-config profile "C:\OpenVPN\client.ovpn"
- Specify the file name where to write OpenVPN client connection logs:
ovpnconnector.exe set-config log "C:\OpenVPN\client.log"
OpenVPN logs are also available in the Event Viewer under Windows Logs -> Applications. Enable the filter by the Event Source OVPNConnectorService.
- Start the OpenVPN service:
ovpnconnector.exe start
Check that the client successfully connects to the OpenVPN server. The following message should appear in the log:
Wed Feb 1 11:13:29 2023 Connected via TUN_WIN
Wed Feb 1 11:13:29 2023 EVENT: CONNECTED YourOpenVPNProfile via /UDPv4 on TUN_WIN/10.1.2.10/ gw=[10.1.2.8/]
And your WinTUN virtual adapter got an IP address from the OpenVPN server. - Now configure automatic startup for the OVPNConnectorService using the
services.msc
console or with the command:sc config OVPNConnectorService start=auto
- The OpenVPN service will now automatically connect to the server after Windows is restarted.
If you want to disable and remove the OVPNConnectorService service, run the following commands:
ovpnconnector.exe stop
ovpnconnector.exe remove
If you are using OpenVPN authentication via Active Directory, you can save the username and password to a plain text file and use it to automatically connect.
Create a text file login.txt in the C:\Program Files\OpenVPN\config
directory.
And add the following options to the ovpn configuration file:
auth-user-pass login.txt
auth-retry nointeract
auth-nocache
If you are using the OpenVPN GUI client, you can also configure the system service to connect automatically.
- Be sure to select the OpenVPN Service when installing the OpenVPN client;
- Copy your OpenVPN profiles (.ovpn files) to the directory “
C:\Program Files\OpenVPN\config\
“ - The OpenVPN service will automatically start a VPN tunnel for each *.ovpn configuration file from this directory.
If you want more than one OpenVPN connection to be active on your computer at the same time, make sure that a sufficient number of TUN/TAP virtual network adapters have been created in Windows. Otherwise, the error All TAP-Windows adapters on this system are currently in use will appear in the logs. It is also recommended to bind an OpenVPN connection to a specific network interface using the following option in .ovpn:
dev-node 'OpenVPN TAP-Windows2'
(specify your OpenVPN network adapter name in Windows). - Check that the OpenVPNService service (
C:\Program Files\OpenVPN\bin\openvpnserv2.exe
) is configured to start automatically.
On Linux, you can connect to the VPN server from the command line or enable autoconnect using the openvpn@client.service
daemon.
This daemon automatically establishes VPN connections for all .conf configuration files in the /etc/openvpn directory (just rename your *.ovpn files to *.conf). And enable the service:
$ sudo systemctl enable openvpn@client.service
$ sudo systemctl start openvpn@client.service
In order to get OpenVPN GUI to auto-start and auto-connect on boot,
we need to pick a single configuration for a particular location that we
wish to connect on every boot.
For the purpose of this guide, I am going to use PrivateVPN’s OpenVPN-TUN-UDP configuration for India.
Step 1 — Editing your OpenVPN client configuration
Open .ovpn file in Notepad application, look for # Crypto section and make the following changes as seen in the image below:
auth-user-pass user.auth
auth-retry nointeract
auth-nocache
Save and close the .ovpn file.
Step 2 — Storing your PrivateVPN.com credentials in a file
Open Notepad application and type your PrivateVPN username in first line and password in second, save the file as user.auth.
Step 3 — Import edited .ovpn file and user.auth file to OpenVPN config folder
Navigate to Program files — OpenVPN — config folder of your main
Windows installation. Copy your edited .ovpn file and user.auth there.
When prompted for Administrative permission, grant it to Continue.
Step 4 — Configuring OpenVPN service to start automatically on boot
Start Run application from Start Menu or by using keyboard shortcut combination Ctrl+R and input services.msc in the text field there and click OK.
Locate OpenVpnService (Not OpenVPN Legacy Service or OpenVPN Interactive Service) and double-click on it.
A dialog box appears, change Startup type to Automatic, and click Apply followed by OK. That is all. OpenVPN configuration file should connect right away and on every boot automatically.
Note: You are not required to use OpenVPN GUI client any more.
‘OpenVpnService’ would automatically connect you to respective
PrivateVPN OpenVPN server on boot.
You are now done configuring OpenVPN client as service on Windows OS. Navigate to PrivateVPN.com to check if you are connected to VPN also do a reboot to make sure it persists.
Enjoy!