如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
如果我调用一个命令使用内核#系统在Ruby中,我如何得到它的输出?
system("ls")
当前回答
请注意,所有向系统传递包含用户提供值的字符串的解决方案,%x[]等都是不安全的!不安全实际上意味着:用户可以触发代码在上下文中运行,并具有程序的所有权限。
据我所知,只有系统和Open3。popen3在Ruby 1.8中提供了一个安全/转义的变体。在Ruby 1.9中,IO::popen也接受数组。
只需将每个选项和参数作为数组传递给其中一个调用。
如果你不仅需要退出状态,还需要结果,你可能会使用Open3.popen3:
require 'open3'
stdin, stdout, stderr, wait_thr = Open3.popen3('usermod', '-p', @options['shadow'], @options['username'])
stdout.gets(nil)
stdout.close
stderr.gets(nil)
stderr.close
exit_code = wait_thr.value
注意,块表单将自动关闭stdin, stdout和stderr-否则它们必须显式关闭。
更多信息:在Ruby中形成卫生shell命令或系统调用
其他回答
作为直接系统(…)替代品,您可以使用Open3.popen3(…)
进一步讨论: http://tech.natemurray.com/2007/03/ruby-shell-commands.html
我想扩展和澄清一下混沌的答案。
如果你用反勾号包围命令,那么你根本不需要(显式地)调用system()。反勾号执行命令并以字符串形式返回输出。然后你可以像这样把值赋给一个变量:
output = `ls`
p output
or
printf output # escapes newline chars
puts `date`
puts $?
Mon Mar 7 19:01:15 PST 2016
pid 13093 exit 0
你可以使用一个叫做Frontkick的宝石
Frontkick.exec("echo *")
下面是如何检查和阅读它:
result = Frontkick.exec("echo *")
puts result.successful? #=> true if exit_code is 0
puts result.success? #=> alias to successful?, for compatibility with Process::Status
puts result.stdout #=> stdout output of the command
puts result.stderr #=> stderr output of the command
puts result.exit_code #=> exit_code of the command
puts result.status #=> alias to exit_code
puts result.exitstatus #=> alias to exit_code, for compatibility with Process::Status
puts result.duration #=> the time used to execute the command
Github https://github.com/sonots/frontkick frontkick
创业板页面https://rubygems.org/gems/frontkick
您可以使用system()或%x[],这取决于您需要什么样的结果。
System()如果找到命令并成功运行,则返回true,否则返回false。
>> s = system 'uptime'
10:56 up 3 days, 23:10, 2 users, load averages: 0.17 0.17 0.14
=> true
>> s.class
=> TrueClass
>> $?.class
=> Process::Status
% x [. .]另一方面,将命令的结果保存为字符串:
>> result = %x[uptime]
=> "13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> p result
"13:16 up 4 days, 1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> result.class
=> String
Jay Fields的博客文章详细解释了system、exec和%x[..]]。