ruby - 如何在 Ruby 中创建 root 拥有的文本文件?

标签 ruby file unix

在 Ruby 中,使用 File.write 作为当前用户创建一个文本文件非常简单,但如果我希望该文件由 root 拥有,它就会变得更加复杂。

我意识到我可以使用 sudo 运行 Ruby 脚本本身,但我不想这样做。

我该怎么做?

最佳答案

文件可以首先以当前用户身份创建,然后拥有其所有权和权限,而不是尝试以 root 身份创建或打开文件(我相信如果 Ruby 脚本已作为非 root 用户启动,这是不可能的)改变了。

作为一个实际问题,使用 Ruby 的 Tempfile 功能来创建初始文件可能是有意义的,因为它不需要确定唯一的文件名,并且不需要当前目录可写。这是我想出的代码(它也发布在 https://gist.github.com/keithrbennett/2c6f53351bf9cdb0bbbfd3f7f97dc91c )。该模块已定义,对其的调用位于最后一行。我做了一些假设,例如该文件应该是世界可读的:

#!/usr/bin/env ruby

require 'tempfile'

module SudoFileWriter

  module_function

  # Writes passed text to a temp file.
  # @return the filespec of the temp file.
  def write_to_temp_file(text)
    filespec = nil
    Tempfile.open do |file|
      file.write(text)
      filespec = file.path
    end
    filespec
  end


  def write_to_root_file(filespec, text)
    temp_filespec = write_to_temp_file(text)
    commands = [
        "sudo chown root:wheel #{temp_filespec}",
        "sudo mv #{temp_filespec} #{filespec}",
        "sudo chmod +r #{filespec}"
    ]
    puts "Running commands for file #{filespec}:\n\n"; puts commands
    `#{commands.join(' && ')}`
  end


  def call(filespec, object_to_write)
    write_to_root_file(filespec, object_to_write.to_s)
  end
end

# .() is shorthand for .call().
# `module_function` above results in all methods being both module level
# and instance level methods, so we can call directly on the module object.

SudoFileWriter.('root-owned-file.txt', "The time is now #{Time.now}.\n")

输出如下:

Running commands for file root-owned-file.txt:

sudo chown root:wheel /var/folders/bk/8y3jvjs53qs9wlqtpzqq6_080000gn/T/20180810-9981-124bxcl
sudo mv /var/folders/bk/8y3jvjs53qs9wlqtpzqq6_080000gn/T/20180810-9981-124bxcl root-owned-file.txt
sudo chmod +r root-owned-file.txt
Password:
The time is now 2018-08-10 16:01:05 +0700.

关于ruby - 如何在 Ruby 中创建 root 拥有的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51782816/

相关文章:

Java ZK WebContent/img 的完整路径

windows - 如何将 QueryPerformanceCounter 转换为 Unix 纳秒(纪元)

Unix 排序仅对一列进行排序

ruby - 哪个更好?在 Ruby 中创建实例变量或传递局部变量?

通过 ssh 调用 write()

ruby-on-rails - 使用迁移或模型创建连接表?

c - fopen 的文件字符串错误?

linux - 将 ls -R 输出解析为 Unix 中的变量

ruby-on-rails - 无法运行 Rails 服务器,找不到 Gem 'rails(4.2.5.1) x86-mingw32'

ruby - 清除实例变量的方法的命名约定