通过AppleScript连接后检查VPN连接是否成功

时间:2017-03-24 02:42:50

标签: xcode macos applescript vpn

我有一个将您连接到VPN的脚本,但我无法判断用户是否已成功连接。脚本运行时,将提示用户输入密码。但是如果用户点击取消,我的脚本仍然认为他们已经连接。

    tell application "System Events"
        tell current location of network preferences
            set VPNService to service "MyVPN"
            if exists VPNService then
                try
                    connect VPNService
                    set VPNFailed to "false"
                on error
                    set VPNFailed to "true"
                end try
            else


            end if

        end tell
    end tell
            delay 11

    if VPNFailed is "true" then
        set image1 to current application's NSImage's imageNamed_("NSStatusUnavailable")
        UIVPNStatus's setImage_(image1)
        display dialog "Server is down, please try again later." buttons {"OK"}
        else
        set image1 to current application's NSImage's imageNamed_("NSStatusAvailable")
        UIVPNStatus's setImage_(image1)
        display notification "" with title "Connection Successful!" subtitle "You may now browse the internet privatley and securley"
        set image2 to current application's NSImage's imageNamed_("VPNLocked.png")
        UIVPNLock's setImage_(image2)
    end if
    else
    display dialog "Cannot connect to server." buttons {"OK"} with icon 2
    set volume 7
    beep
    tell VPNProgress to stopAnimation_(sender)
   end if

    tell VPNProgress to stopAnimation_(sender)

`

1 个答案:

答案 0 :(得分:1)

解决这个问题的一种方法是建立一个计时器,它可以持续ping连接状态,直到它返回true或超时。这是对它的抨击(我简化了你的代码,以切入问题的核心)。请注意,此代码假设您使用的是Mac的内置VPN。

set myVPNServiceName to "Your VPN connection name" --update with real name
set timer to 20 -- update to whatever time (in seconds) you feel is acceptable
set isVPNConnected to false

tell application "System Events"

    tell current location of network preferences

        set VPNService to null
        set vpnConnectionInProgress to false

        -- Try to connect to VPN service
        try
            set VPNService to service myVPNServiceName
            connect VPNService
            set vpnConnectionInProgress to true
        end try

        if vpnConnectionInProgress is true then

            -- keep checking until timer expires or connection is confirmed
            repeat while timer > 0 and isVPNConnected is false

                if current configuration of VPNService is connected then
                    set isVPNConnected to true
                end if

                log isVPNConnected

                set timer to timer - 1
                delay 1

            end repeat

        end if

    end tell

end tell

if isVPNConnected is true then
    display notification "" with title "Connection Successful!" subtitle "You may now browse the internet privately and securely"
else
    display dialog "Cannot connect to " & myVPNServiceName buttons {"OK"}
end if