xcode - 如何使用 osascript 在 SwiftUI 中以管理员权限运行 shell 脚本

标签 xcode macos swiftui

我正在尝试制作一个简单的 macOS 应用程序,当按下特定按钮时,它会以管理员权限运行 shell 脚本。为了在终端中运行 shell 脚本,我成功测试了此命令:

osascript -e '使用管理员权限执行 shell 脚本“/Users/andreas/checkertool.sh”'

不幸的是,按下按钮时我无法执行此命令。出现以下错误消息:

0:2:执行错误:变量“do”未定义。 (-2753)

这就是我的代码到目前为止的样子。任何帮助将不胜感激!

import SwiftUI

struct ContentView: View {
    @State var script = "/Users/andreas/checkertool.sh"
    @State var isRunning = false

    var body: some View {
        VStack {
            Text("Checker Tool")
                .font(.largeTitle)
                .padding()
            HStack {
                Button(action: {
                    let process = Process()
                    process.launchPath = "/usr/bin/osascript"
                    process.arguments = ["-e", "do", "shell script", "/Users/andreas/checkertool.sh", "with administrator privileges"]
                    process.launch()
                    process.waitUntilExit()
                }) {
                    Text("Check")
                }.disabled(isRunning)
                    .padding(.trailing)
            }
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}


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

最佳答案

正确的终端命令应该是(如果您在脚本中使用特定的 shell,则应相应地替换 sh,例如 bash)

$ osascript -e 'do shell script "sh /Users/andreas/checkertool.sh" with administrator privileges'

所以你的论点应该如下:

process.arguments = ["-e", "do shell script \"sh /Users/andreas/checkertool.sh\" with administrator privileges"]

附注假设您在没有沙箱的情况下执行此操作,因为我怀疑它是否允许这样做。

关于xcode - 如何使用 osascript 在 SwiftUI 中以管理员权限运行 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554711/

相关文章:

ios - 让用户暂时禁用它后如何重新安排重复间隔通知?

SwiftUI: fatal error :在 View.body 之外访问 State<String>”

ios - 是否可以将 ViewController 分配给 SwiftUI View ?

ios - 如何在 iOS 应用程序中以编程方式检测 SwiftUI 的使用情况

ios - swift 代码在 Xcode 7 中不起作用(setCategory、AVFormatIDKey、AVAudioRecorder)

iphone - Objective C 单一特定字符串替换方法

ios - 类在目标中被多次链接

objective-c - NSDateFormatter doesRelativeDateFormatting 返回意外的相对日期值

objective-c - 监控沙盒应用程序中的文件夹

javascript - 如何在 JavaScript 中检测 Mac OS X 版本