简体   繁体   中英

Execute terminal command as root from Swift Code

The below code allows me to create the ui and run the terminal command without root permission. My goal is to run the shutdown command from my swift code which is required to have root permission. Can anyone help me with this issue please?

//
//  ContentView.swift
//  Created by laughinggg on 8/27/20.
//  Copyright © 2020 laughinggg. All rights reserved.
//

import SwiftUI

struct windowSize {
let minWidth : CGFloat = 500
let minHeight : CGFloat = 200
let maxWidth : CGFloat = 200
let maxHeight : CGFloat = 250
}

struct ContentView: View {
    @State var message = "+"
    @State var isRunning = false
    var body: some View {
        VStack {
            Text("HELLO World!!!")
                .font(.largeTitle)
            .padding()
            HStack {
                TextField("Message", text: $message)
                    .padding(.leading)
                Button(action: {
                    let exe = URL(fileURLWithPath: "/sbin/shutdown")
                    self.isRunning = true
                    try! Process.run(exe,
                                     arguments: [self.message],
                                     terminationHandler: { _ in self.isRunning = false })
                }) {
                    Text("Say")
                }.disabled(isRunning)
                    .padding(.trailing)
            }
        }.frame(maxWidth:500, maxHeight: 500)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


Take a look at this project: https://github.com/sveinbjornt/STPrivilegedTask

There is a function called AuthorizationExecuteWithPrivileges that has been long deprecated but still works.

Apple's documentation: https://developer.apple.com/documentation/security/1540038-authorizationexecutewithprivileg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM