Skip to content

Commit 75f4823

Browse files
committed
Windows cmd scripts to change hosts permissions
Two windows cmd scripts that can work together to change permissions for the current user to modify the hosts file. win-hosts-check.cmd check if the permissions on the file are sufficient. If not it will call win-hosts-set.cmd which will trigger the windows permission dialog asking for enough rights to midify the permissions on the hosts file for the current user. See issue agiledivider#40
1 parent bb1a495 commit 75f4823

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

cmd/win-hosts-check.cmd

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
@ECHO off
2+
SETLOCAL ENABLEEXTENSIONS
3+
REM modify hosts access rights current user can change the file contents
4+
5+
call :hostfileperms _perms
6+
echo Permissins on hosts for user %USERNAME%: %_perms%
7+
8+
If "%_perms%" == "F" goto :PERM_OK
9+
If "%_perms%" == "M" goto :PERM_OK
10+
If "%_perms%" == "RX,W" goto :PERM_OK
11+
If "%_perms%" == "R,W" goto :PERM_OK
12+
If "%_perms%" == "W" goto :PERM_OK
13+
14+
If "%_perms%" == ":" goto :PERM_INSUFFICIENT
15+
If "%_perms%" == "R" goto :PERM_INSUFFICIENT
16+
If "%_perms%" == "RX" goto :PERM_INSUFFICIENT
17+
18+
echo Unhandled "%_perms%", raising.
19+
goto :PERM_INSUFFICIENT
20+
21+
:PERM_INSUFFICIENT
22+
echo|set /p=Raising permissions...
23+
call win-hosts-set.cmd
24+
echo|set /p=done.
25+
call :hostfileperms _perms_new
26+
echo New permissins are: %_perms_new%
27+
IF "%_perms%" == "%_perms_new%" (
28+
echo Changing permissions failed. Exiting.
29+
exit /b 1
30+
)
31+
32+
:PERM_OK
33+
echo Suffice. Exiting.
34+
goto :EOF
35+
36+
:hostfileperms
37+
setlocal
38+
set _icacls_cmd=Icacls %SystemRoot%\system32\drivers\etc\hosts /T
39+
FOR /f "tokens=2" %%G IN ('%_icacls_cmd% ^|find "%USERNAME%"') DO set _permission_info=%%G
40+
set "_permission_perms=%_permission_info:*:=%"
41+
set _permission=%_permission_perms:~1,-1%
42+
43+
( endlocal
44+
set "%1=%_permission%"
45+
)
46+
exit /b

cmd/win-hosts-set.cmd

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
@if (1==1) @if(1==0) @ELSE
2+
@echo off&SETLOCAL ENABLEEXTENSIONS
3+
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
4+
cscript //E:JScript //nologo "%~f0"
5+
@goto :EOF
6+
)
7+
CACLS %SystemRoot%\system32\drivers\etc\hosts /E /G %USERNAME%:W
8+
@goto :EOF
9+
@end @ELSE
10+
ShA=new ActiveXObject("Shell.Application")
11+
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
12+
WScript.Sleep(500)
13+
@end

0 commit comments

Comments
 (0)