2011-07-15 7 views
0

Windowsマシン(Windows 7を実行中、x86-64)でsystem32/drivers/etcにある 'etc/hosts'ファイルを開き、それを修正してrubyからセーブすることができます?ルビーの管理者権限でファイルを開く

私は「(例外IOError)を作成するための開かれていません」を取得エラー コードは非常に簡単です

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

+0

Windows保護ファイルなのですか?ホストファイルのためにこれをオフにする必要があるかもしれません。 –

+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はあなたが権限で実行したい任意のコマンドすることができます。ホストファイルを編集するには、

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}" 
関連する問題