在Windows機器上(Windows 7正在運行,x86-64)可以打開system32/drivers/etc中的'etc/hosts'文件,修改它並從ruby保存?使用管理員權限在ruby中打開文件
我得到錯誤 的代碼非常簡單
file = File.open("C:/Windows/System32/drivers/etc/hosts")
file << "new line"
在Windows機器上(Windows 7正在運行,x86-64)可以打開system32/drivers/etc中的'etc/hosts'文件,修改它並從ruby保存?使用管理員權限在ruby中打開文件
我得到錯誤 的代碼非常簡單
file = File.open("C:/Windows/System32/drivers/etc/hosts")
file << "new line"
Instead of trying to acquire privileges from code (which maybe won't be portable across different windows OS'es), do like this:
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.
yeap,我試過了,但它仍然顯示「沒有打開寫入(IO錯誤)」 – Sergey
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}"
是因爲Windows受保護的文件?也許你必須關閉hosts文件。 –
你必須在寫入模式下打開你的文件。對不起,我一開始沒有看到這個:) – Senthess
如果你想追加某些東西到文件中,用'a +'模式打開它,請閱讀File.open文檔。 –