How to check if VPN is connected before deciding what to do

Hi all. I’ve been using Tasker for simple activities for quite a while, but now I need to do something a little more advanced for my level.

I use OpenVPN and the OpenVPN plugin to connect to different VPNs in different situations, each one triggered by a simple built-in Tasker feature such as which wifi network I’m connected to.

However, now I need to do the following, which I assume should be simple but I don’t know where to start:

Is any VPN connected? If yes, reconnect. If not, connect to VPN X. VPN X is always the same.

Thanks.

You could use AutoNotification to query current notifications and see if your which VPN (if any) your connected to.

Without plug-ins, you could use this task to see if you are connected to a VPN (without identifying the VPN):

Task: getVPNStatus

A1: Run Shell [
     Command: ifconfig
     Timeout (Seconds): 0
     Store Output In: %ifconfig_out
     Use Global Namespace: On ]

A2: If [ %ifconfig_out ~R (?m)^tun[0-9] ]

    A3: Return [
         Value: true
         Stop: On ]

A4: Else

    A5: Return [
         Value: false
         Stop: On ]

A6: End If

It returns true if you’re connected to a VPN, and false if not.

How can I test the state and run a task depending on the result?

Hi u/UnkleMike. Thanks for your reply. Very helpful. I don’t need to identify the VPN because the OpenVPN plugin has a simple action of reconnection which will reconnect whatever is connected, and that’s exactly what I want.

A very basic question, though: how do I get to the point where I can input this script?

Then how do I save the result? I’d assumed it needed to go on a variable somewhere which I could test on both connection and reconnection tasks: connection only runs if false, reconnection only runs if true.

Am I thinking in the right way?

I was in the process of giving you an example, and discovered it doesn’t work on my phone. I’m not sure if this is due to a change in Tasker, or the fact that my phone has android 12 now. I’ll have to check this out later and get back to you.

Thank you so much. Yes please if you find out. I’m still trying a few things, but I think I’m quite far from the actual solution.

For some reason I’m getting a “permission denied” error from the shell command. This is happening on my phone with Android 12, and my tablet with Android 10. Unfortunately, I don’t have an alternative right now.

No worries. Thanks for looking into this for me.

The task posted above works for me on a11, it does require root however. (Action fails if root is not checked in the options)

I don’t have root access so I guess it’s a non starter anyway. I’m going to play with the VPN connected state as proposed in another thread but I haven’t had the chance yet.