Created
January 14, 2020 21:14
-
-
Save dilames/b4fe31ef7a318ef5c99479b913280a75 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SecurityFoundation | |
import ServiceManagement | |
final class BashService { | |
// MARK: Private | |
private var connection: NSXPCConnection? | |
private var authorization: SFAuthorization? | |
private var remoteProxy: ServiceProtocol? | |
private func connect() throws { | |
guard connection == nil else { return } | |
if authorization == nil { | |
authorization = try SFAuthorization.withAdminPrivileges( | |
prompt: "Application requesting permission to execute bash task" | |
) | |
} | |
guard let authorization = authorization else { return } | |
try ServiceManagment.JobBless(domain: kSMDomainSystemLaunchd, | |
executable: Keys.machServiceName, | |
authorization: authorization) | |
connection = NSXPCConnection(machServiceName: Keys.machServiceName, options: .privileged) | |
connection?.remoteObjectInterface = NSXPCInterface(with: ServiceProtocol.self) | |
connection?.resume() | |
remoteProxy = connection?.remoteObjectProxy as? ServiceProtocol | |
} | |
public func execute(_ bash: String, completion: @escaping (String) -> Void) { | |
do { | |
try connect() | |
let arguments = bash.split(separator: " ").map { String($0) } | |
remoteProxy?.bash(arguments, completion: completion) | |
} | |
catch { completion("Error: \(error) \n") } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment