如何从命令行判断 OS X 是否已连接到 VPN 网络?

如何从命令行判断 OS X 是否已连接到 VPN 网络?

如何从命令行判断 OS X 是否已连接到 VPN 网络?

当我连接时,不带任何参数运行ifconfig,我看到有一个utun0接口,看起来像是 VPN 连接。当我断开连接时,它就消失了。

我相信我可以使用类似这样的方法来检查字符串utun0并计算出现次数:

ifconfig | grep -c utun0

但是有没有更简单或更有效的方法来检查这一点?如果utun0是一个设备,甚至是伪设备,我是否应该能够使用以下方法检查它是否存在:

if [ -a '/dev/utun0' ]

不幸的是,在连接和断开连接时我没有看到该目录下的任何变化,我只是看到/dev/tun0/dev/tun15,但即使有我也看不到cat它们sudo......

有没有更简单的方法来判断我是否有 VPN 连接?

答案1

从 Mountain Lion 1开始,您还可以使用 scutil 命令。

例如:

$ scutil --nc list | grep Connected

如需更详细的帮助,您可以查看手册页,或者运行:

$ scutil --nc help

脚注:

  1. 我不知道这个命令是否存在于 Mountain Lion 之前的 OSX 版本中,但我可能是错的。

答案2

由于您是通过“系统偏好设置”定义界面的,因此,一种简单的方法是使用 AppleScript。以下代码片段将执行您想要执行的操作:

# 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

将其作为脚本保存在某处(并确保将其保存为脚本文件!)。

任何时候想要运行它,请使用以下命令: osascript /path/to/script.scpt

或者创建一个执行该操作的别名。

相关内容