Skip to content

Instantly share code, notes, and snippets.

@dilames
Created January 14, 2020 21:14
Show Gist options
  • Save dilames/b4fe31ef7a318ef5c99479b913280a75 to your computer and use it in GitHub Desktop.
Save dilames/b4fe31ef7a318ef5c99479b913280a75 to your computer and use it in GitHub Desktop.
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