在进行快速用户切换时在OSX上运行脚本

时间:2016-01-31 21:14:50

标签: macos

当用户在OSX(El Capitan)上切换快速用户切换时,是否可以设置脚本运行? 早些时候,人们可以使用这样的东西:http://www.radiotope.com/content/os-x-how-perform-action-during-fast-user-switch - 但这种方法多年来一直无法实现。

1 个答案:

答案 0 :(得分:0)

经过一些错误的尝试,我想出了一个非常优雅的解决方案。我的目的是仅针对特定Mac用户启动和停止VPN连接。您可以将最终的二进制文件添加到用户的登录项中,也可以在~/Library/LaunchAgents中创建用户代理,详细信息:https://www.launchd.info/

您需要熟悉Swift和Xcode。

在Xcode中创建MacOS命令行工具项目,并将以下内容粘贴到main.swift

import AppKit

class VPNManager {
    init() {
        NSWorkspace.shared.notificationCenter.addObserver(
            self,
            selector: #selector(becameActive),
            name: NSWorkspace.sessionDidBecomeActiveNotification,
            object: nil
        )
        NSWorkspace.shared.notificationCenter.addObserver(
            self,
            selector: #selector(becameInactive),
            name: NSWorkspace.sessionDidResignActiveNotification,
            object: nil
        )
    }

    @objc func becameActive() {
        print("Workspace became active... starting VPN")
        let task = Process()
        task.launchPath = "/usr/sbin/networksetup"
        task.arguments = ["-connectpppoeservice","PrivateVPN (L2TP)"]
        let pipe = Pipe()
        task.standardOutput = pipe
        task.standardError = pipe
        task.launch()
        task.waitUntilExit()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)
        print("start result:", output ?? "empty")
    }

    @objc func becameInactive() {
        print("Workspace became inactive... stopping VPN")
        let task = Process()
        task.launchPath = "/usr/sbin/networksetup"
        task.arguments = ["-disconnectpppoeservice","PrivateVPN (L2TP)"]
        let pipe = Pipe()
        task.standardOutput = pipe
        task.standardError = pipe
        task.launch()
        task.waitUntilExit()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        let output = String(data: data, encoding: .utf8)
        print("stop result:", output ?? "empty")
    }
}

let vpnManager = VPNManager()

print("VPNManager initialized")
RunLoop.current.run()
print("VPNManager exiting")