Home > other >  Asking for admin permissions in Windows using bash script
Asking for admin permissions in Windows using bash script

Time:07-01

I'm trying to alter my hosts file in Windows using a bash script.

It looks like this:

echo "<ip_address>  <replacement>" >> C:\\Windows\\System32\\drivers\\etc\\hosts

It looks like I need admin permissions, how can I get those? I tried this, but it didn't work either.

cd C:\\Windows\\System32\\drivers\\etc

chmod  x hosts

echo "<ip_address>  <replacement>" >> C:\\Windows\\System32\\drivers\\etc\\hosts

Result

chmod: changing permissions of 'hosts': Permission denied
bin/exec.sh: line 5: C:\Windows\System32\drivers\etc\hosts: Permission denied

Having to accept a pop-up that asks for permissions is acceptable!

CodePudding user response:

It is unfortunately very complicated to achieve this without external tools.

I recommend this very useful tool: https://github.com/gerardog/gsudo - it works like sudo but for Windows.

Note however that gsudo echo .. >> .. won't be enough because the >> .. part is done by the shell which is not elevated and gsudo probably can't run echo since that's a builtin, but gsudo 'bash -c echo .. >> ..' should work:

gsudo 'bash -c echo "<ip_address>  <replacement>" >> C:\\Windows\\System32\\drivers\\etc\\hosts'

Note: If this doesn't work because either your bash.exe is not in your Windows PATH or because despite this being MINGW bash you also have WSL installed and gsudo would start that instead, then you can always use cmd instead of bash:

gsudo 'cmd /c echo "<ip_address> <replacement>" >> C:\Windows\System32\drivers\etc\hosts'
  • Related