2011-07-15 60 views
0

在Windows机器上(Windows 7正在运行,x86-64)可以打开system32/drivers/etc中的'etc/hosts'文件,修改它并从ruby保存?使用管理员权限在ruby中打开文件

我得到错误 的代码非常简单

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

+0

是因为Windows受保护的文件?也许你必须关闭hosts文件。 –

+0

你必须在写入模式下打开你的文件。对不起,我一开始没有看到这个:) – Senthess

+0

如果你想追加某些东西到文件中,用'a +'模式打开它,请阅读File.open文档。 –

回答

2

Instead of trying to acquire privileges from code (which maybe won't be portable across different windows OS'es), do like this:

  • open a command prompt as an administrator
  • run your script from there

By doing like this, all the programs you're executing will have administrative privileges as well.

EDIT: This is your problem:

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

You have to open the file in write mode.

+0

yeap,我试过了,但它仍然显示“没有打开写入(IO错误)” – Sergey

0

My best work around is have ruby open an elevated command prompt when necessary. It will prompt the user for a password, but it is better than nothing.

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

cmd可以是要与权限运行任何命令,“不写(IO错误)打开”。我所做的编辑主机文件是:

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}"