【问题标题】:Execute terminal command as root from Swift Code从 Swift Code 以 root 身份执行终端命令
【发布时间】:2020-12-16 16:02:58
【问题描述】:

下面的代码允许我创建 ui 并在没有 root 权限的情况下运行终端命令。 我的目标是从我的 swift 代码中运行关闭命令,该代码需要具有 root 权限。 谁能帮我解决这个问题?

//
//  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()
    }
}


【问题讨论】:

    标签: swift xcode macos terminal command


    【解决方案1】:

    看看这个项目:https://github.com/sveinbjornt/STPrivilegedTask

    有一个名为AuthorizationExecuteWithPrivileges 的函数早已被弃用,但仍然有效。

    Apple 的文档:https://developer.apple.com/documentation/security/1540038-authorizationexecutewithprivileg

    【讨论】:

    • 我也检查了这些。那些是贬值的。还是谢谢。
    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多