I decided to automate a back up task that had been completed manually for quite some time. The process was initiated manually because the server is located on a network that could only be accessed via OpenVPN connection.
The first task was figure out how to initiate the connection via command line. After digging through some documentation, I found out that you can call the ‘openvpn.exe’ file from command line and pass it’s configuration via *.ovpn file and the ‘–config’ parameter. Shown here on Stackoverflow in C# code.
This lead to my next problem – disconnect from the client at the end of the operation. The OpenVPN client has a telnet server that can receive a disconnect command. It can be enabled by adding the ‘management’ parameter to the *.ovpn configuration file. For example, if you want to open the telnet server on port 7000, add the following line:
management localhost 7000
After enabling the server, you need to use a telnet client to connect to the OpenVPN client. Once connected to the VPN client, disconnecting from the VPN connection can be done via the telnet command: SIGHUP
The last problem is reinitializing the localhosts’s network interface. Because disconnecting from the VPN connection from telnet does not reinitialize your primary network interface, you need to set it manually via command line. This can be done by sending the following command:
netsh interface ipv4 set address name="Local Area Connection" source=dhcp gateway=192.168.0.1
You can find more details on this issue here in the section that references the ‘EnableLocalNet.bat’ file.
In the end, I ended up creating something similar to a Rube Goldberg Machine that used a combination of a .NET Console Application, BAT files, Unison, and AutoIt to get the backup operation working. The .NET console program was responsible for starting and disconnecting the OpenVPN connection and initiating Unison to transfer the files. AutoIt executed the console application and used a BAT file to re-initiate the local host’s network interface after disconnecting.
Source for programs is available upon request.