2011-07-15 58 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}"