NSTask在命令中添加额外的单引号

时间:2015-12-18 00:03:56

标签: swift macos openssl nstask

我正在编写一个访问OpenSSL二进制文件的任务。如果我复制/粘贴没有单引号的命令,那么它在终端中完美运行。

我一直把报价粘贴到命令中。这是代码/错误......

let keySizeValue = keySizes[keySizeChoice.indexOfSelectedItem]

task.launchPath = "/usr/bin/openssl"
task.arguments = ["req -new -newkey \(keySizeValue) -out ~/Desktop/Certs/MyNew.csr -keyout ~/Desktop/Certs/\(privateKeyText.stringValue).key -subj \"/C=US/ST=\(stateText.stringValue)/L=\(cityText.stringValue)/O=\(organizationText.stringValue)/OU=\(departmentText.stringValue)/CN=\(commonNameText.stringValue)\"", "\(privateKeyPassword)", "\(passwordVerify)"]

task.launch()
task.waitUntilExit()

我已经在上面定义了我的任务和keySizes数组,但错误是 Openssl:错误: req -new -newkey rsa:2048 -out ~/Desktop/Certs/MyNew.csr -keyout ~/Desktop/Certs/a.key -subj "/C=US/ST=a/L=a/O=a/OU=a/CN=a"' is an invalid command

可能是我正在使用NSTask不正确,但我觉得这看起来是正确的。任何人都有一个很好的建议:D

2 个答案:

答案 0 :(得分:1)

如果要为NSTask提供多个参数,必须将它们作为由逗号分隔的唯一项添加到arguments数组

let keySizeValue = keySizes[keySizeChoice.indexOfSelectedItem]

task.launchPath = "/usr/bin/openssl"
task.arguments = ["req", "-new", "-newkey", "\(keySizeValue)", "-out", "~/Desktop/Certs/MyNew.csr", "-keyout", "~/Desktop/Certs/\(privateKeyText.stringValue).key", "-subj", "\"/C=US/ST=\(stateText.stringValue)/L=\(cityText.stringValue)/O=\(organizationText.stringValue)/OU=\(departmentText.stringValue)/CN=\(commonNameText.stringValue)\"", "\(privateKeyPassword)", "\(passwordVerify)"]

task.launch()
task.waitUntilExit()

答案 1 :(得分:0)

如果还有人在看这个,我就能找到解决方案。我不得不将我的NSTask的参数分开,然后通过NSPipe传递参数并使用stdin使参数正确进入终端

mainTask.launchPath = "/usr/bin/openssl"
mainTask.arguments = ["req", "-new", "-nodes", "-newkey", "\(keySizeValue)", "-passout", "pass:\(privateKeyPassword.stringValue)", "-out", "/Users/\(userName)/Desktop/Certs/MyNew.csr", "-keyout", "/Users/\(userName)/Desktop/Certs/\(privateKeyText.stringValue).key", "-subj", "\"/C=US/ST=\(stateText.stringValue)/L=\(cityText.stringValue)/O=\(organizationText.stringValue)/OU=\(departmentText.stringValue)/CN=\(commonNameText.stringValue)\""]

let pipe = NSPipe()
mainTask.standardInput = pipe
mainTask.launch()
mainTask.waitUntilExit()

修复了我的错误。谢谢你的帮助