在ruby中使用admin权限打开文件

时间:2011-07-15 12:00:47

标签: ruby hosts

在Windows机器上(运行Windows 7,x86-64)是否可以打开system32 / drivers / etc中的'etc / hosts'文件,修改它并从ruby中保存?

我得到“没有打开写入(IOError)”错误 代码很简单

file = File.open("C:/Windows/System32/drivers/etc/hosts")
file << "new line"

2 个答案:

答案 0 :(得分:2)

不要试图从代码中获取权限(可能无法通过不同的Windows操作系统移植),请执行以下操作:

  • 以管理员身份打开命令提示符
  • 从那里运行你的脚本

通过这样做,您正在执行的所有程序也将具有管理权限。

编辑:这是你的问题:

file = File.open("C:/Windows/System32/drivers/etc/hosts","w")
file << "new line"

您必须以写入模式打开文件。

答案 1 :(得分:0)

我最好的解决方法是在必要时让ruby打开一个提升的命令提示符。它会提示用户输入密码,但总比没有好。

username = `whoami`.chomp
run = "runas /noprofile /user:#{username} \"cmd /C #{cmd}\""
system(run)

cmd可以是您想要使用权限运行的任何命令。我编辑主机文件的方法是:

hosts_path = 'C:\windows\System32\drivers\etc\hosts'
hosts_file = File.open(host_path,'r') {|f| f.read}
...
    --edit the hosts_file here--
...
cmd = "echo \"#{hosts_file}\" > #{hosts_path}"
相关问题