Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to alter/modify windows host file as administrator using python

What I have tried:

import ctypes, subprocess,shutil ,sys
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
subprocess.call(['C:\\Windows\\notepad.exe', 'C:\Windows\System32\drivers\etc\hosts'])
append = open('C:\Windows\System32\drivers\etc\hosts','a').write("127.0.0.1      www.google.com")
print(append.read())
Posted
Updated 21-Apr-22 7:09am
Comments
Richard MacCutchan 20-Apr-22 10:36am    
And what happens when you run this code?
mahabir das 21-Apr-22 3:00am    
IOError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\drivers\\etc\\hosts'
getting error for this line
append = open('C:\Windows\System32\drivers\etc\hosts','a').write("127.0.0.1 www.google.com")
Richard MacCutchan 21-Apr-22 3:47am    
That suggests that your code is not running as administrator.
mahabir das 22-Apr-22 1:41am    
okay tring

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900