【发布时间】:2013-07-23 15:08:25
【问题描述】:
我无法将控制台中的命令输出作为变量保存到 Ruby 中。我正在尝试将 .p12 文件的信息保存为变量p12_info。这是我到目前为止所尝试的。
file = File.read("certificate.p12")
p12 = OpenSSL::PKCS12.new(file, "")
p12_info = `openssl pkcs12 -in #{p} -info -noout -passin pass:""`
print "Info: "
puts p12_info
这是我得到的输出:
File name: certificate.p12
MAC Iteration 1
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Certificate bag
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
Info:
当我尝试设置变量 p_12 时,控制台命令似乎正在运行,但实际上并没有保存到 p12_info 中。
或者,如果我尝试这个:
p12_info = `echo "foo`
print "Info: "
puts p12_info
然后我得到这个输出,这就是我想要的:
File name: certificate.p12
Info: foo
任何关于为什么会发生这种情况的想法将不胜感激。
编辑:
@tadman - 非常感谢您的帮助。你是对的,该命令实际上输出了附加的> /dev/null。不幸的是,我无法弄清楚如何使用 popen3。我对这一切都很不熟悉..我试过了:
Open3.popen3(`openssl pkcs12 -in bad_certificate.p12 -info -noout -passin pass:""`) {|stdin, stdout, stderr, wait_thr|
pid = wait_thr.pid # pid of the started process.
p12_info = wait_thr.stderr # Process::Status object returned.
}
无济于事。任何可以引导我走向正确方向的指针?非常感谢。
【问题讨论】:
-
你确定输出是标准输出吗?您可以使用
openssl ... > /dev/null在 shell 上进行测试,如果您仍然看到输出,那么它正在写入 STDERR。然后你必须使用popen3。 -
我在上面的编辑中做出了回应。谢谢!
-
这就是您为
popen3调用所做的吗?它应该在常规引号中,而不是反引号。 -
@mbratch 是的,那是个错误。 tadman 为我指明了正确的方向,但非常感谢您的意见
标签: ruby bash variables input console