在Ruby中正确转义shell参数

Wil*_*ken 1 ruby rake rakefile

这是代码:

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
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*oel 5

使用require 'shellwords'和Shellwords.escape 你可以在" shellescape "和" Shellwords "中找到更多关于这些的信息