gpt4 book ai didi

ruby - 无法将控制台输出保存为 Ruby 变量

转载 作者:太空宇宙 更新时间:2023-11-03 16:29:57 25 4
gpt4 key购买 nike

我无法将控制台中命令的输出作为变量保存到 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.
}

没有用。任何可以引导我朝着正确方向前进的指针?非常感谢。

最佳答案

你错过了一些东西。一个是 popen3 接受一个字符串参数,反引号导致外部 shell 调用恰好返回一个字符串。

反引号约定来自 bash shell,它用于内联命令的结果:

ls -l `which ls`

这可以扩展为:

ls -l '/bin/ls'

考虑到这一点,你应该拥有的是:

Open3.popen3('openssl pkcs12 -in bad_certificate.p12 -info -noout -passin pass:""') do |stdin, stdout, stderr, wait_thr|
# stderr is a standard IO filehandle
p12_info = stderr.read
end

关于ruby - 无法将控制台输出保存为 Ruby 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17814058/

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