Ruby 转义 ARGV 参数或字符串作为 shell 命令的参数
好吧,这让我发疯:
`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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
require 'shellwords'
和Shellwords.escape
,这将为您解决此类问题:http://apidock.com/ruby/Shellwords/shellescape
Use
require 'shellwords'
andShellwords.escape
, which will fix this sort of stuff for you:http://apidock.com/ruby/Shellwords/shellescape
远离构建 shell 字符串
这是任意代码执行的良好向量。
在这种情况下,您可以使用
popen
,它会为您进行转义,例如:输出:
就像我们在终端上运行一样:
If
a b
had not被转义后,我们不会得到预期的a 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.:This outputs:
just as if we had run on the terminal:
If
a b
hadn't been escaped, we wouldn't geta b
as expected, because running an unquoted:in the terminal gives:
Tested in Ubuntu 20.02, Ruby 2.6.
双引号也有效:
或
Double quotes also works:
or