Detection VPN connection ASUS Merlin Router  [Solved]

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Detection VPN connection ASUS Merlin Router

Post by Chris12 »

Hi,

I want to monitor if my internet connection is connected with a VPN or not. So when the VPN is down I want to see that, and get an alarm/message etc.
The VPN provider I have got rotates my VPN connection several times per day/week to get the best/fastest connection available all the time.
Sometimes the VPN connection fails, and I want to know when it does (without looking in my router to see if the VPN is (dis)connected).

My VPN connection is setup in my ASUS RT-AC86U router (running asuswrt-merlin firmware) using openVPN, so all my internet traffic is always routed via this VPN.

I did some google searching, and found out that there's a possibility to use commands via ssh to configure the VPN on/off.

Status of the VPN connection: nvram get vpn_client1_state
Set VPN connection ON: service start_vpnclient1
Set VPN connection OFF: service stop_vpnclient1

But how to get this into a dzVents script? I want something that gives me a status change whenever the VPN is OFF (so I can use this status change of an IDX to make it visible in dashticz), and maybe whenever the VPN status is detected as OFF that automatically the VPN service is started again after like 10 seconds. And have an IDX to switch ON/OFF the VPN connection manually without logging into the router to do so.

I looked at a script which does setup a SSH connection to a ASUS router, but I cannot manage to reform that script with the functionality I need.
viewtopic.php?f=59&t=30755

edit:
I tried the above commands directly via putty logged into the ASUS router and they work OK, I could see the (dis)connecting of the VPN Client in the GUI of the router.

Connected state:
Admin@RT-AC86U-6B08:/tmp/home/root# nvram get vpn_client1_state
2


VPN Service Stop:
Admin@RT-AC86U-6B08:/tmp/home/root# service stop_vpnclient1
Done.


VPN Service Start:
Admin@RT-AC86U-6B08:/tmp/home/root# service start_vpnclient1
Done.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
erem
Posts: 230
Joined: Tuesday 27 March 2018 12:11
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Location: Amsterdam/netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by erem »

why do you want this from dzVents?

two simple shell scripts will do this for you
1 script to get status from router and update a switch in domoticz thru http/json via curl.
a second switch in domoticz to switch the vpn on/off
2 a script to turn the vpn on/off to be called from the switch

see: https://www.linuxtechi.com/execute-linu ... -over-ssh/

that will get you started
Regards,

Rob
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

I'm a total noob with programming and scripts/linux, and found the mentioned post with the dzvents example.
So that's why I thaught maybe that's the way to go.

Even your link is mostly abracadabra for me.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
erem
Posts: 230
Joined: Tuesday 27 March 2018 12:11
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Location: Amsterdam/netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by erem »

that makes it more challenging, specially as i do not have an asus router.

all scripting solutions ( dzVents, bash, etc) will require passswordless ssh access to the router.

here is a way to do that. ( google is my friend )
https://www.htpcguides.com/enable-ssh-a ... -ssh-keys/

if you can use ssh without having to enter a passsword we can take the next step.
Regards,

Rob
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by waaren »

Chris12 wrote: Tuesday 23 March 2021 9:28 I want to monitor if my internet connection is connected with a VPN or not. So when the VPN is down I want to see that, and get an alarm/message
When you have passwordless ssh between the system with domoticz and the ASUS router, a dzVents script could check the status and restart the VPN service.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

I will look and figure out the passwordless part today. Maybe running domoticz on my Synology NAS will give me some struggles to get the passwordless to work.
I prefer the dzVents script as I allready have 2 other of those running for other stuff.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

OK, I have enabled the SSH access using this guide:
https://www.htpcguides.com/enable-ssh-a ... -ssh-keys/

But when using Putty I still have to login with a username/password.

Next step I did is generating a public key with puttgen, and placing this public key int the ASUS Autohrizated key part of the config.
After rebooting the router and using Putty I still have to login with a username/password.

I can see that the key is stored in the authorized_keys file located in /root/.ssh, and that one is the same as configured in the webGUI.

What are the next steps to do?
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by waaren »

Chris12 wrote: Wednesday 24 March 2021 9:47 What are the next steps to do?
Did you also created the keyset on your domoticz server and copied the public key to the ASUS Router?

A howto can be found here
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

The keygen command does not work, but I found another interesting post:
https://www.snbforums.com/threads/dropb ... ord.21070/
and followed those steps.

But run into some issues when the creation of the directory step is not OK. I think that's maybe due to restrictions on my Synology Nas?
The step:
Admin@RT-AC86U-6B08:/jffs/.ssh# ssh [email protected] mkdir -p ~/.ssh
[email protected]'s password:
mkdir: cannot create directory '/root': Permission denied

Maybe my user account does not have enough R/W rights?


The next step after that:
cat /jffs/.ssh/id_rsa.pub | ssh [email protected] 'cat >> ~/.ssh/authorized_keys'
puts the file in the /volume1/homes/Chris/.ssh directory

When now trying to login from my NAS to the ASUS router:
ssh -i /jffs/.ssh/id_rsa [email protected] -p 2211
Warning: Identity file /jffs/.ssh/id_rsa not accessible: No such file or directory.

Looking at the directory on the NAS I can see the copied authorized_keys file.
Looking in the routers directory I see the id_rsa.pub file and the authorized_keys file. The content of the last one matches the contents of the file on the NAS.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
erem
Posts: 230
Joined: Tuesday 27 March 2018 12:11
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Location: Amsterdam/netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by erem »

you are trying to get ssh working from the router to the nas, where you should go from nas to router
ssh is not bidirectional.
on your nas generate a key pair.

Code: Select all

ssh-keygen -t rsa
leave passphrase empty.
then paste the contents of <home>/.ssh/id_rsa.pub into your router as in the link i sent previously
then, from your nas open a terminal session and ssh into the router.
you should get a question about unknown host, answer yes. (this is one time only)
subsequent logins should now be password free.
Regards,

Rob
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

Aha, that's the sollution!

It now works fine (had to change the file permissions of the genereated id_rsa to 600 as well)
So now passwordless login from my NAS to the ASUS router works!

ssh [email protected] -p 2211

ASUSWRT-Merlin RT-AC86U 386.1_2 Fri Feb 12 22:48:22 UTC 2021
Admin@RT-AC86U-6B08:/tmp/home/root#
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
erem
Posts: 230
Joined: Tuesday 27 March 2018 12:11
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Location: Amsterdam/netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by erem »

ok, so you can now use the script ( modified) from your initial post in dzVents on your domoticz from your nas.
if you need help with dzVents, post your questions.

suc6
Regards,

Rob
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

Hi Rob, I think that's a little bridge to far for me... but I will give it a try this evening to figure out that script and rebuild it with the commands I need.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
erem
Posts: 230
Joined: Tuesday 27 March 2018 12:11
Target OS: Raspberry Pi / ODroid
Domoticz version: 2021.1
Location: Amsterdam/netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by erem »

]Chris,

i am no that good with dzVents, but here is something to visualize the VPN state in domoticz if you are up for it.

you need a virtual switch in domoticz, and remember it's idx number

then create this script

Code: Select all

#!/bin/bash

# user setup area
routerIP=" 192.168.1.1"
domIPPort="127.0.0.1:8080"  #domoticz ip:port
connState="2"        # output of VPN connected
dzIdx=17  # change to idx of virtual switch
cmd="nvram get vpn_client1_state"

# NO changes below this line

state=$(ssh Admin@$routerIP -p 2211 $cmd)
echo "VPN state is $state"

if [[ $state -eq $connState ]]
then
    echo $state
    echo $connState
    curl -s "http://$domIPPort/json.htm?type=command&param=switchlight&idx=$dzIdx&switchcmd=On" >/dev/null
else
    echo false
    curl  -s "http://$domIPPort/json.htm?type=command&param=switchlight&idx=$dzIdx&switchcmd=Off" >/dev/null
fi

name it getstate.sh and make it executable (chmod +x ./getstate.sh)
update the switch index and domoticz port number in the script to your values

then if you run the script the virtual switch will be updated with the state of the VPN.
Regards,

Rob
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

Hi Rob, thanks for the script example. I added a dummy hardware and a virtual switch device (idx 1155)

I tried your script but I get a lot of errors because of the used # and $ signs, I think this is a different scripting language you created the script in.

Maybe @waaren can help me out, he has created a lot of scripts and the example posted earlier is made by him as well.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by waaren »

Chris12 wrote: Wednesday 24 March 2021 19:05 Maybe @waaren can help me out, he has created a lot of scripts and the example posted earlier is made by him as well.
Happy to help. What is your domoticz version?
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

Version: 2020.2 (build 12731)
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by waaren »

Chris12 wrote: Wednesday 24 March 2021 20:57 Version: 2020.2 (build 12731)
A first version

Code: Select all

local scriptVersion = '0.20210324'
local scriptVar  =  'SSH_' .. scriptVersion

--[[ 

This dzVents script is used to monitor open VPN state of a ASUS RT-AC86U router loaded with asuswrt-merlin firmware

The script use io.popen to trigger a nvram and when required do a service restart command on a remote system via ssh 
(the router must be accessible by the user that is running the domoticz service, via password-less 
SSH (with public / private key setup)

Before activating the script:
    Read the GETTING STARTED section of the dzVents wiki. 
    Change the values in the script to reflect your setup
   
]]--

return
{
    on = 
    { 
        timer = 
        {
            'every minute', -- change to required frequency
        },
    },

    logging =   
    {
        level = domoticz.LOG_DEBUG, -- set to LOG_ERROR when tested and OK
        marker = scriptVar,
    },
    
    execute = function(dz, item)
        
        remoteHost = '192.168.1.1'   -- change to router IP
        message = 'OpenVPN not connected. Check it out' 
        
        -- =======================================================================
        --               NO changes required below this line
        -- =======================================================================

        --commands to execute remote
        local commands = 
        {
            status = 'nvram get vpn_client1_state ',
            stop = 'service stop_vpnclient1 ',
            start = 'service start_vpnclient1 ',
        }
        commands.restart = commands.stop .. '; ' .. commands.start
        
        local function osCommand(cmd)
            dz.log('Executing Command: ' .. cmd,dz.LOG_DEBUG)

            local fileHandle = assert(io.popen(cmd .. ' 2>&1 || echo ::ERROR::', 'r'))
            local commandOutput = assert(fileHandle:read('*a'))
            local returnTable = {fileHandle:close()}

            if commandOutput:find '::ERROR::' then     -- something went wrong
            dz.log('Error ==>> ' .. tostring(commandOutput:match('^(.*)%s+::ERROR::') or ' ... but no error message ' ) ,dz.LOG_DEBUG)
            else -- all is fine!!
                dz.log('ReturnCode: ' .. returnTable[3] .. '\ncommandOutput:\n' .. commandOutput, dz.LOG_DEBUG)
            end
            return commandOutput,returnTable[3] -- rc[3] contains returnCode
        end
        
        local function buildSSHCommand(cmd)
            local sshBOL = "sudo ssh "  .. remoteHost .. " \'"   
            local sshEOL = ";\'" 
            
            local cmd = sshBOL .. cmd .. sshEOL
            return cmd 
        end
        
        -- Main
        local result, rc = osCommand(buildSSHCommand(commands.status))
        dz.log(result,dz.LOG_DEBUG)
        if result ~= 2 then 
            dz.log(message, dz.LOG_ERROR)
             dz.notify(scriptVar, message, dz.PRIORITY_HIGH)
            osCommand(buildSSHCommand(commands.restart))
        end    
    end
}

Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Chris12
Posts: 238
Joined: Tuesday 18 August 2020 8:41
Target OS: NAS (Synology & others)
Domoticz version: 2021.1
Location: NL
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by Chris12 »

@waaren, thanks for creating such a script!

I loaded/installed it in domoticz, and after saving checked the logfile that shows (after 1 minute)

Code: Select all

2021-03-24 22:09:00.390 Status: dzVents: Info: SSH_0.20210324: ------ Start internal script: VPN Status:, trigger: "every minute"
2021-03-24 22:09:00.390 Status: dzVents: Debug: SSH_0.20210324: Executing Command: sudo ssh 192.168.1.1 'nvram get vpn_client1_state ;'
2021-03-24 22:09:00.537 Status: dzVents: Debug: SSH_0.20210324: Error ==>> ssh: connect to host 192.168.1.1 port 22: Connection refused
2021-03-24 22:09:00.537 Status: dzVents: Debug: SSH_0.20210324: ssh: connect to host 192.168.1.1 port 22: Connection refused
2021-03-24 22:09:00.537 ::ERROR::
2021-03-24 22:09:00.537
2021-03-24 22:09:00.537 Status: dzVents: Debug: SSH_0.20210324: Executing Command: sudo ssh 192.168.1.1 'service stop_vpnclient1 ; service start_vpnclient1 ;'
2021-03-24 22:09:00.681 Status: dzVents: Debug: SSH_0.20210324: Error ==>> ssh: connect to host 192.168.1.1 port 22: Connection refused
2021-03-24 22:09:00.681 Status: dzVents: Info: SSH_0.20210324: ------ Finished VPN Status
2021-03-24 22:09:00.682 Status: EventSystem: Script event triggered: /usr/local/domoticz/dzVents/runtime/dzVents.lua
2021-03-24 22:09:00.795 Status: Notification: SSH_0.20210324
2021-03-24 22:09:00.537 Error: dzVents: Error: (3.0.18) SSH_0.20210324: OpenVPN not connected. Check it out 
I think this is because ssh is running on port 2211 on my ASUS router.
So maybe add a port parameter so the script is more general for other users as well (if needed).

I tried to add it to the script but then it gives some errors:

Code: Select all

 2021-03-24 22:22:00.832 ...icz/var/scripts/dzVents/generated_scripts/VPN Status.lua:68: unexpected symbol near '" -p 2211"'
2021-03-24 22:22:00.908 Error: dzVents: Error: (3.0.18) error loading module 'VPN Status' from file '/usr/local/domoticz/var/scripts/dzVents/generated_scripts/VPN Status.lua':
2021-03-24 22:22:00.908 ...icz/var/scripts/dzVents/generated_scripts/VPN Status.lua:68: unexpected symbol near '" -p 2211"'

Can you add another thing as well: adding the status of the VPN to an device in domoticz (I already created a virtaul switch with id 1155) ?
So I can have a visual of the VPN is on/off, and can see how many times it had to be resetted.
Domoticz beta | Dashticz beta | Synology DS415+ | Wall tablet Teclast 11.6inch (Android) | TADO v3 controlled heating
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Detection VPN connection ASUS Merlin Router

Post by waaren »

Chris12 wrote: Wednesday 24 March 2021 22:26 I think this is because ssh is running on port 2211 on my ASUS router.
So maybe add a port parameter so the script is more general for other users as well (if needed).

Can you add another thing as well: adding the status of the VPN to an device in domoticz (I already created a virtaul switch with id 1155) ?
So I can have a visual of the VPN is on/off, and can see how many times it had to be resetted.
Added port and VPNStatus switch in below version

Code: Select all

local scriptVersion = '0.20210324'
local scriptVar  =  'SSH_' .. scriptVersion

--[[

This dzVents script is used to monitor open VPN state of a ASUS RT-AC86U router loaded with asuswrt-merlin firmware

The script use io.popen to trigger a nvram and when required do a service restart command on a remote system via ssh
(the router must be accessible by the user that is running the domoticz service, via password-less
SSH (with public / private key setup)

Before activating the script:
    Read the GETTING STARTED section of the dzVents wiki.
    Change the values in the script to reflect your setup

]]--

return
{
    on =
    {
        timer =
        {
            'every minute', -- change to required frequency
        },
    },

    logging =
    {
        level = domoticz.LOG_DEBUG, -- set to LOG_ERROR when tested and OK
        marker = scriptVar,
    },

    execute = function(dz, item)

        local remoteHost = '192.168.192.1'   -- change to router IP
        local message = 'OpenVPN not connected. Check it out'
        local port = 2211
        local VPNStatus = dz.devices(1155)
        -- =======================================================================
        --               NO changes required below this line
        -- =======================================================================

        --commands to execute remote
        local commands =
        {
            status = ' /usr/local/ashscripts/nvram get vpn_client1_state ',
            stop = 'service stop_vpnclient1 ',
            start = 'service start_vpnclient1 ',
        }
        commands.restart = commands.stop .. '; ' .. commands.start

        local function osCommand(cmd)
            dz.log('Executing Command: ' .. cmd,dz.LOG_DEBUG)

            local fileHandle = assert(io.popen(cmd .. ' 2>&1 || echo ::ERROR::', 'r'))
            local commandOutput = assert(fileHandle:read('*a'))
            local returnTable = {fileHandle:close()}

            if commandOutput:find '::ERROR::' then     -- something went wrong
            dz.log('Error ==>> ' .. tostring(commandOutput:match('^(.*)%s+::ERROR::') or ' ... but no error message ' ) ,dz.LOG_DEBUG)
            else -- all is fine!!
                dz.log('ReturnCode: ' .. returnTable[3] .. '\ncommandOutput:\n' .. commandOutput, dz.LOG_DEBUG)
            end
            return commandOutput,returnTable[3] -- rc[3] contains returnCode
        end

        local function buildSSHCommand(cmd)
            local sshBOL = "sudo ssh -p " .. port .. ' '  .. remoteHost .. " \'"
            local sshEOL = ";\'"

            local cmd = sshBOL .. cmd .. sshEOL
            return cmd
        end

        -- Main
        local result, rc = osCommand(buildSSHCommand(commands.status))
        dz.log(result,dz.LOG_DEBUG)
        if tonumber(result) ~= 2 then
            dz.log('Result: ' .. result .. ': ' .. message, dz.LOG_ERROR)
            dz.notify(scriptVar, message, dz.PRIORITY_HIGH)
            VPNStatus.switchOff().checkFirst()
            osCommand(buildSSHCommand(commands.restart))
        else
            dz.log('openVPN connected', dz.LOG_DEBUG)
            VPNStatus.switchOn().checkFirst()
        end

    end
}

Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 1 guest