I'm writing a python script that will append a line in C:\Windows\System32\drivers\etc\hosts
. How do I append a line in this file with administrator permission?
Asked
Active
Viewed 4,149 times
2

Rikas
- 187
- 7
- 15
-
@bimsapi i learn this from the same link. – dsgdfg Aug 22 '15 at 14:17
1 Answers
0
You append to a file by opening it in append mode:
with open('C:/Windows/System32/drivers/etc/hosts', 'a') as f:
f.write('127.127.127.127 static.ak.connect.facebook.com\n')
note: backslash is an escape character, so I use forward slashes, which the msvcrt.dll functions accept just as well
Finally, run your program as administrator in order to have write privileges. My knowledge of this is right-clicking in Windows explorer and choosing 'Run as Administrator'. You could run a command shell (cmd.exe) as administrator and run your python program from there. As far as Windows-specific UAC stuff, you'll need someone who is a Windows system programmer to help with that.

dsh
- 12,037
- 3
- 33
- 51