2010-01-29 26 views
3

我有一個腳本,可以由不可信用戶調用,我們需要沿着這個線路的呼叫執行由例如:如何解除污染系統命令

system 'somescript ' + data 

我們需要確保,如果data == 'filename; dosomethingelse'那麼;被轉義(或任何其他特殊字符,結果是shell命令運行實際上是somescript filename\;\ dosomethingelsesomescript "filename; dosomethingelse"

有沒有做到這一點的標準方式?

回答

6
system 'somescript', data 

多參數調用system不會傳遞至

+2

在完全不同的說明中,它讓我想起了一些問題,在這些問題中,人們詢問如何轉義字符串,以便它們可以安全地用作SQL字符串文字......正確的答案是「不要」。準備好的陳述是正確的方法。以同樣的方式,使字符串作爲程序參數安全的正確方法是不讓它們靠近shell。 :-P – 2010-01-29 02:09:31

+1

或者如何使用正則表達式解析HTML。 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-01-29 05:02:25

1

的Shellwords模塊(標準庫的一部分)的外殼以進行處理將做相應的轉義外殼命令:

#!/usr/bin/ruby1.8 

require 'shellwords' 

command = ['cat', 'filename with spaces', '"quoted_filename"'].shelljoin 
puts command # => cat filename\ with\ spaces \"quoted_filename\" 
system(command) 
# => this file has spaces in its name 
# => this file has a quoted filename 

shellwords還爲String添加了shellescape方法。這些方法不在online API documentation中。它們部分記錄在1.9鎬中,並且已知存在於MRI 1.8.7中。實際的文件(在我的機器上,在/usr/lib/ruby/1.8/shelljoin.rb)很好的評論。