How can I tell if OS X is connected to a VPN network from the command line?

12

3

How can I tell if OS X is connected to a VPN network from the command line?

By running ifconfig without any arguments when I am connected, I see that there is a utun0 interface which appears to be the VPN connection. When I disconnect it goes away.

I believe I could use something like this to check for the string utun0 and count the occurrences:

ifconfig | grep -c utun0

But is there an easier or more effective way to check for this? If utun0 is a device, or even a pseudo device, shouldn't I be able to check if it exists with something like:

if [ -a '/dev/utun0' ]

Unfortunately I don't see any changes in that directory when connecting and disconnecting, I just see /dev/tun0 through /dev/tun15 and I can't cat them even with sudo...

Is there a simpler way to tell if I have a VPN connection?

cwd

Posted 2013-04-02T23:30:53.553

Reputation: 13 508

What kind of VPN? The built-in you configure in System Preferences? – Daniel Beck – 2013-05-07T05:12:00.697

@DanielBeck -yes – cwd – 2013-05-07T18:55:54.160

Answers

10

You can also, as of Mountain Lion1, use the scutil command.

For example:

$ scutil --nc list | grep Connected

For more detailed help, you can see the man page, or run:

$ scutil --nc help

Footnotes:

  1. I'm not aware of this command existing in versions of OSX previous to Mountain Lion, but I could be wrong.

encoded

Posted 2013-04-02T23:30:53.553

Reputation: 796

0

Since you're defining the interface through System Preferences, an easy way to go about doing this would be to use AppleScript. Here's a snippet that will do what you want to do:

# Get the major version number. Mavericks changes the way things are done.
set osversion to do shell script "sw_vers 2>/dev/null | awk '/ProductVersion/ { print $2    }' | cut -f 2 -d ."
if osversion is less than 9 then
    set vpntype to 10
else
    set vpntype to 11
end if
try
    tell application "System Events"
        tell current location of network preferences
            set vpnservice to (name of first service whose kind is vpntype) as string
            set myConnection to the service vpnservice
            if myConnection is not null then
                if current configuration of myConnection is not connected then
                    return "Not Connected"
                else
                    return "Connected"
                end if
            end if
        end tell
    end tell
on error error_message
    return error_message
    error number -128
end try

Save this as a script somewhere (and make sure you save it as a script file!).

Any time you want to run it, use the command: osascript /path/to/script.scpt

Or make an alias that performs that.

Alex Plumb

Posted 2013-04-02T23:30:53.553

Reputation: 1 616