macで無料WiFiに接続したら自動でVPNを有効にする

公開日時
更新日時

前回の記事にてiOSのVPN自動接続ができるようになったので、macでも同様に自動接続ができるようにしたい。

Appleスクリプトを書く

方法としては定期的にSSIDをチェックして自宅外の場合はVPNに接続するAppleスクリプトを書けばよいとのこと。

参考記事にあったスクリプトに手を加えて特定のSSIDを除外できるようにした。

[[Your VPN name]]と[[YourHomeSSID1]]、[[YourHomeSSID2]]の部分を各自で使っているものに置き換える。

on idle
    set VPNname to "Your VPN name"
    set waitingSeconds to 30
    set excludedSSIDs to {"YourHomeSSID1", "YourHomeSSID2"}
    
    set mySSID to {do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'"} as string
    
    if mySSID as string is equal to "" then
        return waitingSeconds
    end if
    
    if excludedSSIDs contains mySSID then
        return waitingSeconds
    end if
    
    tell application "System Events"
        tell current location of network preferences
            set myConnection to the service VPNname
            if myConnection is not null then
                if current configuration of myConnection is not connected then
                    display notification {"Connecting VPN: ", VPNname} as string
                    connect myConnection
                end if
            end if
        end tell
    end tell
    return waitingSeconds
end idle

上記のAppleスクリプトを「VPN Auto Connect.scpt」として保存して、「ファイル」=>「書き出す」を選択する。

ファイルフォーマットを「アプリケーション」にし、「ハンドラの実行後に終了しない」と「実行専用」にチェックを入れて保存する。

mac vpn auto

ログイン時に自動起動するように

「システム環境設定」=>「ユーザとグループ」=>「ログイン項目」=>「+」で「VPN Auto Connect.app」を選択。

mac vpn auto setting

これで毎回意識しなくても自動でVPN接続が切り替わるようになった。

参考


Related #vpn

CloudflareのWARPを使う

自前でVPNサーバを立てる必要がないのでお手軽

iOSで無料WiFiに接続したら自動でVPNを有効にする

オンデマンド接続用のプロファイルを作成することで自動VPN切り替えができるようになる

macのVPN接続にSoftEther VPNプロトコルを利用する

L2TPのポートがファイアウォールにブロックされている環境でもVPNが使えるようにした

GCP無料枠を使ってSoftEther VPN Serverを立ち上げる

カフェやコワーキングスペースで作業をする際に無料wifiを使うことがあり、wifiの盗聴防止のために専用VPNが欲しかったのでGCP上にSoftEther VPN Serverを構築した