In a previous post, I explained how to set up Mikrotik Routerboards as a VPN gateway.

This post is about how to remotely switch the VPN on and off via Smart Home visualization OpenHAB 2, so it affects your whole LAN. You can even switch to other VPN servers, conveniently via phone or browser interface.

Basic procedure: User starts a command via OpenHAB interface -> SSH commands are executed via shell -> RouterOS accepts the commands.

SSH preparation

First we need to establish a simple and secure connection between your server (e.g. Ubuntu, running OpenHAB) and your routerboard, which can be used in scripts without passwords.

On your OH server, execute:

Copy the file /ssh-mikrotik/id_rsa.pub to your Mikrotik device, e.g. via WinSCP and RouterOS WinBox (or FTP / terminal).

Then open WinBox -> System -> Users and create a user “openhab” with full permissions. If you want, restrict it to a certain IP address.

In “SSH keys” tab, import the file id_rsa.pub you copied before, and assign it to Mikrotik user “openhab”.

Test the SSH connection on your OH server:

 

Scripts

You need some scripts on your OH server to get the VPN state and be able to control it.

 

Make both scripts executable by the openhab user:

You can later extend these scripts e.g. to be able to switch to another VPN host. Use the commands like in WinBox terminal, e.g. “/interface pptp-client set myvpn connect-to=example.com”.

Execute the scripts in your OH server’s shell manually to see if they work (they must be able to run under user openhab).

OpenHAB2 configuration

The last step is to configure OH visualization.

We use the Exec binding for OH2, so make sure it is enabled in runtime.cfg (or in your preferred OH admin interface).

You should now be able to control your VPN interface via OpenHAB:

  [email protected]