【问题标题】:Properly escaping shell arguments in Ruby在 Ruby 中正确转义 shell 参数
【发布时间】:2015-02-03 19:37:32
【问题描述】:

代码如下:

desc "Find 301 errors on production servers"
task :find301 do
  command = "grep 'HTTP/1.1\" 301' /var/log/httpd/*ssl-access.log | grep -v 'gclid' | awk '{print \$7}' | sort | uniq -c | sort -nr"

  production_servers.each do |server|
    sh "ssh root@#{server} #{command}"
  end
end

有没有更好的方法来转义 shell 命令,最好是允许sh "ssh root@#{server} #{command}" 与任意commands 一起使用的格式?

【问题讨论】:

  • 不要构建带有字符串操作的命令行,使用systemOpen3的多参数形式,完全绕过shell。

标签: ruby rake rakefile


【解决方案1】:

使用require 'shellwords'Shellwords.escape 您可以在“shellescape”和“Shellwords”中找到更多信息

【讨论】:

  • shellwords 猴子补丁字符串,我喜欢:"foo bar".shellescape == "foo\\ bar"
【解决方案2】:

您可以使用%q%Q 版本,但仍需要指定分隔符。

%Q|these don't need to be escaped /\"'"'{}[]-_+=()!@#$%^&*`~;:<>.,|

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多