是否可以设置脚本以在用户通过 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/