gpt4 book ai didi

swift - 从 MacOS App Swift 启动 sudo 命令

转载 作者:行者123 更新时间:2023-11-28 15:49:38 25 4
gpt4 key购买 nike

我需要向 xcode 启动终端命令。这是命令:

sudo xattr -d -r com.test.exemple /Desktop/file.extension

我试过了

   let task = Process()
task.launchPath = "/usr/sbin/xattr"
task.arguments = ["-d","-r", "com.test.exemple"," /Desktop/file.extension"]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output : String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
print(output)

最佳答案

这是一种在命令之间使用管道的方法。我验证了当我在注释掉的行中使用参数时,该文件是由 super 用户创建的。

它的作用是这样的:

echo 'password' | sudo -S /usr/bin/xattr -d -r com.test.exemple /Desktop/file.extension

func doTask(_ password:String) {
let taskOne = Process()
taskOne.launchPath = "/bin/echo"
taskOne.arguments = [password]

let taskTwo = Process()
taskTwo.launchPath = "/usr/bin/sudo"
taskTwo.arguments = ["-S", "/usr/bin/xattr", "-d", "-r", "com.test.exemple", " /Desktop/file.extension"]
//taskTwo.arguments = ["-S", "/usr/bin/touch", "/tmp/foo.bar.baz"]

let pipeBetween:Pipe = Pipe()
taskOne.standardOutput = pipeBetween
taskTwo.standardInput = pipeBetween

let pipeToMe = Pipe()
taskTwo.standardOutput = pipeToMe
taskTwo.standardError = pipeToMe

taskOne.launch()
taskTwo.launch()

let data = pipeToMe.fileHandleForReading.readDataToEndOfFile()
let output : String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
print(output)
}

关于swift - 从 MacOS App Swift 启动 sudo 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42493290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com