..

macOS 另类的 Privilege Task 实现

所谓 Privilege Tasks 其实就相当于命令行执行 sudo

0x01 传统实现

Authorization Services

Access restricted areas of the operating system, and control access to particular features of your macOS app.

STPrivilegedTask

An NSTask-like wrapper class around AuthorizationExecuteWithPrivileges() in the macOS Security API to run shell commands with root privileges.

0x02 另类实现

可以通过 Apple Script:

do shell script "some awesome script here" with administrator privileges

Example:

import Foundation

var error: NSDictionary?
let source = "do shell script \"sudo echo 'Hello?'\" with administrator privileges"

NSAppleScript(source: source)?.executeAndReturnError(&error)
if let error = error {
    print(String(describing: error))
} else {
    print("Done!")
}

简单快捷有效,适合不需要 Authorization Ref 持久化的场景,否则还是用 Authorization Services 方案吧!