【问题标题】:System call in RubyRuby 中的系统调用
【发布时间】:2010-04-09 09:29:14
【问题描述】:

我是 ruby​​ 和编程方面的初学者,需要系统调用方面的帮助才能将文件从源移动到目标,如下所示:

system(mv "#{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file}")

在 Ruby 中可以做到这一点吗?如果是这样,正确的语法是什么?

【问题讨论】:

    标签: ruby system


    【解决方案1】:

    system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})

    可以替换为

    system("mv", "#{@SOURCE_DIR}/#{my_file}", "#{@DEST_DIR}/#{file}")

    这减少了命令行注入攻击的机会。

    【讨论】:

      【解决方案2】:

      两种方式

      推荐方式

      您可以使用 File Utils 库中的函数(参见here)来移动您的文件,例如

      mv(src, dest, options = {})
      
      
      Options: force noop verbose
      
      Moves file(s) src to dest. If file and dest exist on the different disk 
      partition, the file is copied instead.
      
      FileUtils.mv 'badname.rb', 'goodname.rb'
      FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true  # no error
      
      FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
      FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
      


      淘气的方式

      使用反引号方法(将任何字符串作为命令运行)

      result = `mv "#{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file}"`
      

      好的,这只是调用 system 命令的一种变体,但看起来更调皮!

      【讨论】:

      • 好的,谢谢您的所有回答。如果我通过 NFS 文件系统移动和重命名文件,在 File.rename 之后会发生什么? File.rename 是否将文件拉到我的本地文件系统并重命名并将其推送(移动)回目标或在目标上执行重命名操作?
      • 远程 NFS 服务器负责处理重命名。就所有本地程序而言,该文件是本地的,但 NFS 驱动程序的工作是使其看起来好像是本地的。文件永远不会在本地复制以进行重命名或移动操作。
      【解决方案3】:
      system("mv #{@SOURCE_DIR}/#{my_file} #{@DEST_DIR}/#{file})
      

      应该是正确的调用

      【讨论】:

        【解决方案4】:

        我推荐你使用Tanaka akira's escape library 这是我的一个应用程序的示例:

        cmd = Escape.shell_command(['python', Rails::Configuration.new.root_path + '/script/grab.py']).to_s
        system cmd
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-11
          • 2019-01-05
          • 2011-10-28
          • 2014-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-18
          相关资源
          最近更新 更多