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

标签 macos

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

最佳答案

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

您需要熟悉 Swift 和 Xcode。

在 Xcode 中创建 MacOS、Command line Tool 项目并将以下内容粘贴到 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")

关于macos - 进行快速用户切换时在 OSX 上运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35119549/

相关文章:

xcode - macOS 应用程序不能分发 "developer ID"(选项不显示)

MacOS Kitematic 如何配置卷

ios - Darwin /引用手册页丢失

ios - 强制 WKWebView 显示桌面版本

php - 未定义的 mysql 函数使用 macports 在 mac os x 下安装的 mySql5 + php5 + apache2

c++ - Mac + xcode 6.4 - header 包含路径

css - 在 OS X 中使用 USB 鼠标与无线/触控板时滚动条的外观不同

image - cocoa mac osx 网格显示不同尺寸的图像

macos - Swift 4 NSTreeController @objc 动态 var 节点 = [Node]() 在启动时导致应用程序崩溃

java - 调试历史记录的 Eclipse OS X 快捷方式