Ruby 转义 ARGV 参数或字符串作为 shell 命令的参数

发布于 2024-11-28 00:26:55 字数 325 浏览 0 评论 0原文

好吧,这让我发疯:

`ls #{"/media/music/Miles Davis"}`

由于“Miles”和“Davis”之间的空格而失败

假设我编写了一个 ruby​​ 脚本,并且用户将文件路径作为参数传递。我如何转义它并提供给 shell-out 命令。是的,是的,我知道,应该避免花钱。但这是一个人为的例子,我仍然需要这个。

我会执行 system("ls", ARGV[0]) ,但它不会将 ls 的 stdout 输出作为字符串返回,而这正是反引号所擅长的。

如何转义在 shellout 中插入的任何内容?

Ok this is driving me crazy:

`ls #{"/media/music/Miles Davis"}`

fails because of the space between "Miles" and "Davis"

Say I write a ruby script and a user passes file path as an argument. How do I escape it and feed to a shell-out command. Yes, yes, I know, shelling out should be avoided. But this is a contrived example, I still need this.

I would do system("ls", ARGV[0]), but it doesn't return the stdout output of ls as a string, which is what backticks do well.

How do escape whatever you insert in a shellout?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沙与沫 2024-12-05 00:26:56

使用 require 'shellwords'Shellwords.escape,这将为您解决此类问题:

http://apidock.com/ruby/Shellwords/shellescape

Use require 'shellwords' and Shellwords.escape, which will fix this sort of stuff for you:

http://apidock.com/ruby/Shellwords/shellescape

揽月 2024-12-05 00:26:56

远离构建 shell 字符串

这是任意代码执行的良好向量。

在这种情况下,您可以使用 popen,它会为您进行转义,例如:

#!/usr/bin/env ruby
IO.popen(['printf', 'a b']) do |f|
  puts f.read
end

输出:

a b

就像我们在终端上运行一样:

/usr/bin/printf 'a b'

If a b had not被转义后,我们不会得到预期的 a b ,因为

/usr/bin/printf a b

在终端中运行一个不带引号的:会给出:

a/usr/bin/printf: warning: ignoring excess arguments, starting with ‘b’

Tested in Ubuntu 20.02, Ruby 2.6。

Stay away from building shell strings

This is a fine vector for arbitrary code execution.

In this case, you could use popen, which does the escaping for you, e.g.:

#!/usr/bin/env ruby
IO.popen(['printf', 'a b']) do |f|
  puts f.read
end

This outputs:

a b

just as if we had run on the terminal:

/usr/bin/printf 'a b'

If a b hadn't been escaped, we wouldn't get a b as expected, because running an unquoted:

/usr/bin/printf a b

in the terminal gives:

a/usr/bin/printf: warning: ignoring excess arguments, starting with ‘b’

Tested in Ubuntu 20.02, Ruby 2.6.

一个人的旅程 2024-12-05 00:26:56

双引号也有效:

`ls "#{'/media/music/Miles Davis'}"`

`ls "#{ARGV[0]}"`

Double quotes also works:

`ls "#{'/media/music/Miles Davis'}"`

or

`ls "#{ARGV[0]}"`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文