【问题标题】:SwiftUI: How to access terminal with MacOS app?SwiftUI:如何使用 MacOS 应用程序访问终端?
【发布时间】:2021-07-12 23:09:31
【问题描述】:

所以我有了这个按钮,可以让我在终端中运行 /usr/bin/say,效果很好。但是当我尝试更改 executableURL 变量时,我运行 sudo nano /private/etc/hosts 代替,我收到此错误 所以我的问题是,如何通过我的 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 行),但由于某种原因,当我尝试像以前一样做同样的事情时,什么都没有附加。这是一个大问题。我想我必须在附加一些东西后创建一个新行。关于如何做到这一点的任何想法?

【问题讨论】:

    标签: ios macos terminal localhost


    【解决方案1】:

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

    编辑:

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

    【讨论】:

    • 感谢您的回复,请问这个有什么用? @techrisdev
    • 当您禁用应用沙箱时,您可以访问系统上的所有文件(并使用 Accessibility API 之类的东西)。禁用它的问题是您无法将您的应用程序发布到 App Store。苹果不会接受。
    • 你也可以看看Security-Scoped Bookmarks
    • 好吧,如果禁用 App Sandbox 会禁止我发布我的项目,那么我认为我不会这样做。我试着研究一下安全范围的书签,但不能真正理解它,你能解释一下它的作用吗? @techrisdev
    • 老实说,我从来没有真正研究过安全范围的书签。我认为你可以向用户展示一个 NSOpenPanel,让他选择一个路径,然后将打开的路径保存为书签,以后可以访问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2021-09-21
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多