SwiftUI:如何使用 MacOS 应用程序访问终端?

问题描述

所以我有这个按钮可以让我在终端中运行 /usr/bin/say,它工作得很好。但是当我尝试更改 executableuRL 变量时,我改为运行 sudo nano /private/etc/hosts,我收到此错误

enter image description here

所以我的问题是,如何通过我的 macOS 应用程序访问终端并运行 sudo nano /private/etc/hosts

 Button(action: {
          let executableuRL = URL(fileURLWithPath: "/usr/bin/say")
    //    let executableuRL = URL(fileURLWithPath: "sudo nano /private/etc/hosts")
    
           self.isRunning = true
           do {
               try Process.run(executableuRL,arguments: ["Hello World"],terminationHandler: { _ in self.isRunning = false })
               } catch{
                     print(error)
               }
                    
            }) {
                Text("Say")
            }

编辑:

通过使用这个参数 arguments: ["-c","echo myPassword | sudo -S -- sh -c \"echo \"127.0.0.1www.apple.com \" >> /etc/hosts\""] 行和此路径 URL(fileURLWithPath: "/bin/zsh") 我能够附加到主机文件

我遇到的一个问题是,我能够附加您在图片中看到的内容(不是第 1 行),但由于某种原因,当我尝试像以前一样做时,没有再附加任何内容。这是一个大问题。我想我必须在添加一些东西后创建一个新行。关于如何做到这一点的任何想法?

enter image description here

解决方法

尝试禁用应用沙盒。那么它应该可以工作。

编辑:

    let executableURL = URL(fileURLWithPath: "/bin/zsh")

    self.isRunning = true
    do {
        try Process.run(executableURL,// Replace userpassword with the user's password and yourline with the line you want to append to the file. (If you really want to use nano,you can replace echo... >> ... with nano /private/etc/hosts)
                        arguments: ["-c","echo password | sudo -S -- sh -c \"echo test >> /etc/hosts\""],terminationHandler: { _ in self.isRunning = false })
    } catch {
        print(error)
    }