Discussion:
Win10 network on/off toggle with admin privileges
(too old to reply)
FromTheRafters
2021-02-08 04:11:59 UTC
Permalink
Zaidy & I are working on a Windows 10 network on/off toggle switch
but I'm not a programmer so I'm mixing & matching from what I can find.
Newsgroups: alt.comp.os.windows-10
Subject: Re: A Taskbar shortcut to turn off/on (toggle) the Internet connection?
Date: Mon, 1 Feb 2021 10:51:51 -0500
Message-ID: <rv982m$tc9$***@gioia.aioe.org>

The original goal was to combine these two taskbar shortcuts into one
(OFF) Run as admin to disconnect the Internet connection
%comspec% /c route delete 0.0.0.0 192.168.0.1
(ON) Run as admin to toggle the Internet connection back on
%comspec% /c route add 0.0.0.0 mask 0.0.0.0 192.168.0.1

But we couldn't get a single shortcut to toggle the net on and off.

Based on modifying these sample batch scripts
https://stackoverflow.com/questions/22367173/get-default-gateway-from-batch-file
https://stackoverflow.com/questions/11081735/how-to-use-if-else-structure-in-a-batch-file

We ended up writing this batch script below which toggles the network.

@echo off
;; nettoggle.bat by Zaidy036 20210207 on alt.comp.os.windows-10
;; We still need to get around the need for admin privileges
set defgw=192.168.0.1
set "ip="
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do if not defined ip set ip=%%~a
IF "%ip%"=="%defgw%" ( %comspec% /c %windir%\system32\route.exe delete 0.0.0.0 %defgw%) ELSE ( %comspec% /c %windir%\system32\route.exe add 0.0.0.0 mask 0.0.0.0 %defgw%)
exit

Char Jackson suggested this sample file which somehow
avoids the need to run that script as admin.
https://pastebin.com/x5897YCX

That sample file uses this code I think to become admin

:: GetAdmin
:-------------------------------------
:: Verify permissions
nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
:: On Error No Admin
if '%errorlevel%' NEQ '0' (
echo Getting administrative privileges...
goto DoUAC
) else ( goto getAdmin )

:DoUAC
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B

:getAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------

But when I add that code to the nettoggle.bat script,
it works if I run the script as admin, but it hangs
at the command prompt if I run it as a user with
admin privileges.

@echo off
;; nettoggle.bat by Zaidy036 20210207 on alt.comp.os.windows-10
;; With an attempt to get admin privileges programmatically
:: GetAdmin
:-------------------------------------
:: Verify permissions
nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
:: On Error No Admin
if '%errorlevel%' NEQ '0' (
echo Getting administrative privileges...
goto DoUAC
) else ( goto getAdmin )

:DoUAC
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B

:getAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
set defgw=192.168.0.1
set "ip="
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do if not defined ip set ip=%%~a
IF "%ip%"=="%defgw%" ( %comspec% /c %windir%\system32\route.exe delete 0.0.0.0 %defgw%) ELSE ( %comspec% /c %windir%\system32\route.exe add 0.0.0.0 mask 0.0.0.0 %defgw%)
exit

Can you help us figure out why?
JJ
2021-02-08 07:09:19 UTC
Permalink
Post by FromTheRafters
Zaidy & I are working on a Windows 10 network on/off toggle switch
but I'm not a programmer so I'm mixing & matching from what I can find.
Newsgroups: alt.comp.os.windows-10
Subject: Re: A Taskbar shortcut to turn off/on (toggle) the Internet connection?
Date: Mon, 1 Feb 2021 10:51:51 -0500
[snip]

The problem is because of how the admin access detection is done.

In that code, the detection checks the accessibility of below system file.

%SYSTEMROOT%\system32\config\system

However, that file is only accessible for 64-bit programs. 32-bit programs
only see the 32-bit version Windows system directory - which is at:

%SYSTEMROOT%\syswow64\config\

In that directory, there is no file at all. Only subdirectories.

The system transparently maps "%SYSTEMROOT%\system32\" to
"%SYSTEMROOT%\syswow64\".

So a different, bitness independent admin access detection method needs to
be used. I suggest executing the priviledged AT program like this.

at>nul
if errorlevel 1 (
rem no admin accesss yet. do self elevation
goto :eof
)
rem already got admin access

Executing the AT program would be slower, but it works for both 32-bit and
64-bit programs, because Windows has both 32-bit and 64-bit versions of the
AT program.
FromTheRafters
2021-02-09 10:19:26 UTC
Permalink
Post by JJ
However, that file is only accessible for 64-bit programs. 32-bit programs
only see the 32-bit version Windows system directory
Thank you for trying to help run a batch program with elevated privileges
but without popping up the Windows 10 User Account Control dialog box.

May I ask how I could determine if the nettoggle.bat script is running as a
32-bit or 64-bit program? (I'm on Windows 10 20H2 OS Build 19042.746 64 bit)
Post by JJ
at>nul
I don't understand how that command is supposed to eliminate the UAC prompt.
Besides, my "at.exe" ALWAYS returns "1" (whether the gateway is on or off).

(1) Set errorlevel to 0 (since it's always 1 when I run "at")
C:\Windows\system32> ver
Microsoft Windows [Version 10.0.19042.746]
C:\Windows\system32> cmd /c "exit /b 0"
C:\Windows\system32> %errorlevel%
'0' is not recognized as an internal or external command,
operable program or batch file.
https://stackoverflow.com/questions/1113727/what-is-the-easiest-way-to-reset-errorlevel-to-zero

(2) Make sure the gateway is set & then run the "at test"
C:\Windows\system32> C:\Windows\system32\at.exe > nul
C:\Windows\system32> %errorlevel%
'1' is not recognized as an internal or external command,
operable program or batch file.

(3) Repeat the step above but with the gateway not set.
(On my system, 'at.exe>nul' still outputs an %errorlevel% of '1')
Post by JJ
if errorlevel 1 (
rem no admin accesss yet. do self elevation
goto :eof
)
rem already got admin access
I don't understand how "at>nul" (which sets %errorlevel% to '1') is supposed
to eliminate the UAC prompt?

(It doesn't eliminate the UAC prompt when I use it inside of nettoggle.bat)
Post by JJ
Executing the AT program would be slower, but it works for both 32-bit and
64-bit programs, because Windows has both 32-bit and 64-bit versions of the
AT program.
I don't understand how executing the "at" program gets around the UAC prompt
when the user runs the "nettoggle" program with that "at>nul" code involved?

The desired outcome is:
(1) User runs nettoggle.bat as a user (who has admin privileges)
(2) The script runs with elevated privileges without popping up a UAC prompt
JJ
2021-02-10 13:33:08 UTC
Permalink
Post by FromTheRafters
May I ask how I could determine if the nettoggle.bat script is running as a
32-bit or 64-bit program? (I'm on Windows 10 20H2 OS Build 19042.746 64 bit)
You can check the %PROCESSOR_ARCHITECTURE% variable. Its value is `x86` if
32-bit, or `AMD64` if 64-bit; or `IA64` if Itanium 64-bit.
Post by FromTheRafters
Post by JJ
at>nul
I don't understand how that command is supposed to eliminate the UAC prompt.
Besides, my "at.exe" ALWAYS returns "1" (whether the gateway is on or off).
Oh, sorry. I forgot that the tool is deprecated in Windows 10. In this case,
check the `%windir%\system32\config\journal` directory instead of
`%windir%\system32\config\system` file. FYI, it's applicable for Vista to
Windows 10.
Post by FromTheRafters
(2) The script runs with elevated privileges without popping up a UAC prompt
No program can acquire elevated privileges (admin access) without triggering
the UAC prompt. Unless that program alread has elevated privileges.
FromTheRafters
2021-02-10 16:21:00 UTC
Permalink
Post by JJ
You can check the %PROCESSOR_ARCHITECTURE% variable. Its value is `x86` if
32-bit, or `AMD64` if 64-bit; or `IA64` if Itanium 64-bit.
Thank you for answering my questions.
I apologize that my opening post was fraught with misconceptions on my part.

I must have misunderstood you in that I know that I have a 64-bit machine
%PROCESSOR_ARCHITECTURE% = 'AMD64'

I thought the batch script was "running as if it was 32-bit" versus "running
as if it was 64-bit" that you were telling me to look out for.

I must have misunderstood. My mistake.
Post by JJ
Post by FromTheRafters
Post by JJ
at>nul
I don't understand how that command is supposed to eliminate the UAC prompt.
Besides, my "at.exe" ALWAYS returns "1" (whether the gateway is on or off).
Oh, sorry. I forgot that the tool is deprecated in Windows 10.
So is the cacls deprecated that I was using!
Both return an error message.
The AT command has been deprecated. Please use schtasks.exe instead.
Cacls is now deprecated, please use Icacls.
Post by JJ
In this case,
check the `%windir%\system32\config\journal` directory instead of
`%windir%\system32\config\system` file. FYI, it's applicable for Vista to
Windows 10.
I finally gave up and I now think what I asked for was impossible anyways.

I don't think I was clear enough that the goal was to run a batch script
*WITHOUT* popping up the UAC box which has to be manually clicked.

I had no problem running a batch script as a user which *ASKED* for the UAC
prompt. At this point, I give up as I think I was seeking a unicorn.

What works though is either running the batch script "as administrator"
or (better yet) clicking a shortcut which points to a scheduled task which
is set to run the script "with elevated permissions."
Post by JJ
Post by FromTheRafters
(2) The script runs with elevated privileges without popping up a UAC prompt
No program can acquire elevated privileges (admin access) without triggering
the UAC prompt. Unless that program alread has elevated privileges.
Thank you for confirming that is the problem which I found out the hard way!
That means I was asking for a unicorn (I didn't know it when I had asked).

The good news is the scheduled task runs "with elevated privileges."
I now have a pretty green/red on/off taskbar icon that turns on and off my
gateway.

It has the unexpected added advantage of protecting the VPN connection
should the VPN connection suddenly drop.

I'm told by wasbit there is a ready made program that performs this task
http://crystalrich.com/internetoff/exe/internetoffsetup_3-0-1.exe
But I couldn't get it to work for me when I tested it today.
Murat Senturk
2021-02-08 20:08:12 UTC
Permalink
try this code.

@echo off

:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
:: https://stackoverflow.com/questions/1894967/how-to-request-administrator-access-inside-a-batch-file/10052222#10052222
nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B

:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------

ping -n 1 1.1.1.1 | find "TTL=" >nul
if errorlevel 1 (
netsh interface set interface "Ethernet" admin=enable
) else (
netsh interface set interface "Ethernet" admin=disable
)
FromTheRafters
2021-02-09 10:35:55 UTC
Permalink
Post by Murat Senturk
echo Requesting administrative privileges...
goto UACPrompt
Thanks for that script and especially for that URL to the UAC code.
https://stackoverflow.com/questions/1894967/how-to-request-administrator-access-inside-a-batch-file/10052222
@echo off

:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
IF "%PROCESSOR_ARCHITECTURE%" EQU "amd64" (
Post by Murat Senturk
nul 2>&1 "%SYSTEMROOT%\SysWOW64\cacls.exe" "%SYSTEMROOT%\SysWOW64\config\system"
) ELSE (
Post by Murat Senturk
nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
)

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params= %*
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params:"=""%", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B

:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
<YOUR BATCH SCRIPT HERE>

From reading that, I'm slowly beginning to realize I'm probably doomed.

The desired action is:
(1) The user (who has admin privileges) runs the batch script
(2) The batch script elevates permission to run the "route add" command
(3) *WITHOUT popping up the UAC prompt!*

After reading your suggested link, I'm slowly beginning to realize
there is probably no way to eliminate the UAC prompt
from inside a batch script.

There are other ways to elevate privileges without popping up the UAC prompt
(for example, scheduled tasks) but none that I can find yet that work from
within inside of a batch shell script yet.

I'm probably seeking a unicorn.
Murat Senturk
2021-02-09 14:12:28 UTC
Permalink
You can invoke scheduled task from desktop shortcut like that.
I created a short clip for it :)




example xml file

https://gist.github.com/msenturk/54cbc226b705c1ea94b5a15190c30a3b
FromTheRafters
2021-02-09 21:15:36 UTC
Permalink
Post by Murat Senturk
You can invoke scheduled task from desktop shortcut like that.
I created a short clip for it :)
http://youtu.be/2JOsdTpq3qY
Thank you for all that effort for how to create a scheduled task.

In the end, I was probably seeking a unicorn by trying to elevate
privileges from within a batch file without popping up UAC messages.

Since I give up on that goal of eliminating the UAC popup message from
within the batch file, I added the scheduled task you video taped.

Using the files below I now have a pretty on/off nettoggle icon
in my taskbar which toggles the net either on or off (if the net is on,
it toggles it off - and - if the net is off, it toggles it back on).

(1) This is the batch file I finally ended up with.

@echo off
REM nettoggle.bat (set the default gateway to YOUR router IP address!)
set defgw=192.168.0.1
set "ip="
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do if not defined ip set ip=%%~a
IF "%ip%"=="%defgw%" ( %comspec% /c %windir%\system32\route.exe delete 0.0.0.0 %defgw%) ELSE ( %comspec% /c %windir%\system32\route.exe add 0.0.0.0 mask 0.0.0.0 %defgw%)
exit

I don't know how that network test works as I stole it from here
https://stackoverflow.com/questions/22367173/get-default-gateway-from-batch-file
(where none of the other network tests in that link worked for me).

(2) This is the C:\custom\nettoggle.lnk shortcut target I created
Target: C:\Windows\System32\schtasks.exe /run /TN "NetToggle"

(3) This is a pretty green/red on/off icon I printscreened & edited with
Irfanview to a 45pixel by 45pixel transparent background ico file
(which I placed in the taskbar as my on/off nettoggle switch)
https://www.flaticon.com/premium-icon/icons/svg/2475/2475499.svg

When you left click that pretty green/red on/off icon in the taskbar
the Windows network symbol toggles from the monitor/globe icon
which instantly indicates the status of your network.

(4) This is the taskschd.msc the syntax I copied from elsewhere
Name: NetToggle (Run with highest privileges)
Action: Start a program
Program/script: %comspec%
Add arguments (optional): /c start "" c:\custom\nettoggle.bat

I don't know why the %comspec% has to be broken into two parts
nor do I know why it needs the "TaskName" (which I left empty).

Most articles don't show that two-part %comspec% syntax. I don't know why.
https://www.digitalcitizen.life/use-task-scheduler-launch-programs-without-uac-prompts/
https://www.raymond.cc/blog/task-scheduler-bypass-uac-prompt/

But some do show the two-part %comspec% syntax which worked for me
https://www.download3k.com/articles/How-to-make-an-Elevated-Program-Shortcut-without-a-UAC-Prompt-in-Windows-00805

(5) Most explanations skip this last step which turns the toggle into
a RUN box command which you can pull up using the Windows+R key.
RUN -> nettoggle

Where that command is created using the famous AppPaths registry key
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\nettoggle.exe
@default = C:\custom\nettoggle.lnk

(6) There's a bonus when you're connected to a VPN server.
If you click the nettoggle while connected to a VPN server
it won't affect your VPN connection but if the VPN subsequently
disconnects for whatever reason, the Internet will instantly drop.

I tested it as a failsafe VPN killswitch using this command
%comspec% /k %Windir%\System32\curl.exe icanhazip.com
Where the only flaw is you don't visually see the killswitch
working until the VPN actually drops (then the Windows taskbar
network icon instantly turns to the network off "globe" icon).
Post by Murat Senturk
example xml file
https://gist.github.com/msenturk/54cbc226b705c1ea94b5a15190c30a3b
Thank you for reminding me that we can import & export tasks via xml
https://www.robvanderwoude.com/schtasks.php
(To export this task) schtasks /query /xml /tn "NetToggle" > C:\custom\nettoggle.xml
(To export all tasks) schtasks /query /xml > C:\custom\mytasks.xml
(To import any tasks) schtasks /create /f /xml C:\custom\mytasks.xml

Here is my working C:\custom\nettoggle.xml file by way of example.
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2021-02-07T23:23:26.5482511</Date>
<Author>FTR\x</Author>
<Description>Toggle the network gateway on and off</Description>
<URI>\NetToggle</URI>
</RegistrationInfo>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-1978554282-387915082-910891285-1001</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
</Settings>
<Triggers />
<Actions Context="Author">
<Exec>
<Command>%comspec%</Command>
<Arguments>/c start "" c:\custom\nettoggle.bat</Arguments>
</Exec>
</Actions>
</Task>
--
What I don't understand yet is how that network test works,
and whether it was ever possible to elevate within a batch
file such that the UAC prompt is bypassed (probably not).
Murat Senturk
2021-02-09 22:11:56 UTC
Permalink
Post by FromTheRafters
Post by Murat Senturk
You can invoke scheduled task from desktop shortcut like that.
I created a short clip for it :)
http://youtu.be/2JOsdTpq3qY
Thank you for all that effort for how to create a scheduled task.
In the end, I was probably seeking a unicorn by trying to elevate
privileges from within a batch file without popping up UAC messages.
Since I give up on that goal of eliminating the UAC popup message from
within the batch file, I added the scheduled task you video taped.
Using the files below I now have a pretty on/off nettoggle icon
in my taskbar which toggles the net either on or off (if the net is on,
it toggles it off - and - if the net is off, it toggles it back on).
(1) This is the batch file I finally ended up with.
@echo off
REM nettoggle.bat (set the default gateway to YOUR router IP address!)
set defgw=192.168.0.1
set "ip="
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do if not defined ip set ip=%%~a
IF "%ip%"=="%defgw%" ( %comspec% /c %windir%\system32\route.exe delete 0.0.0.0 %defgw%) ELSE ( %comspec% /c %windir%\system32\route.exe add 0.0.0.0 mask 0.0.0.0 %defgw%)
exit
I don't know how that network test works as I stole it from here
https://stackoverflow.com/questions/22367173/get-default-gateway-from-batch-file
(where none of the other network tests in that link worked for me).
(2) This is the C:\custom\nettoggle.lnk shortcut target I created
Target: C:\Windows\System32\schtasks.exe /run /TN "NetToggle"
(3) This is a pretty green/red on/off icon I printscreened & edited with
Irfanview to a 45pixel by 45pixel transparent background ico file
(which I placed in the taskbar as my on/off nettoggle switch)
https://www.flaticon.com/premium-icon/icons/svg/2475/2475499.svg
When you left click that pretty green/red on/off icon in the taskbar
the Windows network symbol toggles from the monitor/globe icon
which instantly indicates the status of your network.
(4) This is the taskschd.msc the syntax I copied from elsewhere
Name: NetToggle (Run with highest privileges)
Action: Start a program
Program/script: %comspec%
Add arguments (optional): /c start "" c:\custom\nettoggle.bat
I don't know why the %comspec% has to be broken into two parts
nor do I know why it needs the "TaskName" (which I left empty).
Most articles don't show that two-part %comspec% syntax. I don't know why.
https://www.digitalcitizen.life/use-task-scheduler-launch-programs-without-uac-prompts/
https://www.raymond.cc/blog/task-scheduler-bypass-uac-prompt/
But some do show the two-part %comspec% syntax which worked for me
https://www.download3k.com/articles/How-to-make-an-Elevated-Program-Shortcut-without-a-UAC-Prompt-in-Windows-00805
(5) Most explanations skip this last step which turns the toggle into
a RUN box command which you can pull up using the Windows+R key.
RUN -> nettoggle
Where that command is created using the famous AppPaths registry key
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\nettoggle.exe
@default = C:\custom\nettoggle.lnk
(6) There's a bonus when you're connected to a VPN server.
If you click the nettoggle while connected to a VPN server
it won't affect your VPN connection but if the VPN subsequently
disconnects for whatever reason, the Internet will instantly drop.
I tested it as a failsafe VPN killswitch using this command
%comspec% /k %Windir%\System32\curl.exe icanhazip.com
Where the only flaw is you don't visually see the killswitch
working until the VPN actually drops (then the Windows taskbar
network icon instantly turns to the network off "globe" icon).
Post by Murat Senturk
example xml file
https://gist.github.com/msenturk/54cbc226b705c1ea94b5a15190c30a3b
Thank you for reminding me that we can import & export tasks via xml
https://www.robvanderwoude.com/schtasks.php
(To export this task) schtasks /query /xml /tn "NetToggle" > C:\custom\nettoggle.xml
(To export all tasks) schtasks /query /xml > C:\custom\mytasks.xml
(To import any tasks) schtasks /create /f /xml C:\custom\mytasks.xml
Here is my working C:\custom\nettoggle.xml file by way of example.
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2021-02-07T23:23:26.5482511</Date>
<Author>FTR\x</Author>
<Description>Toggle the network gateway on and off</Description>
<URI>\NetToggle</URI>
</RegistrationInfo>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-1978554282-387915082-910891285-1001</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
</Settings>
<Triggers />
<Actions Context="Author">
<Exec>
<Command>%comspec%</Command>
<Arguments>/c start "" c:\custom\nettoggle.bat</Arguments>
</Exec>
</Actions>
</Task>
--
What I don't understand yet is how that network test works,
and whether it was ever possible to elevate within a batch
file such that the UAC prompt is bypassed (probably not).
Actually this script not testing your connection at all.
It just switching between default gateway values 0.0.0.0 to 192.168.0.1
because of this reason your vpn connection works, when vpn up your pc is using vpn client's setted gateway address.
FromTheRafters
2021-02-09 23:23:06 UTC
Permalink
Post by Murat Senturk
Actually this script not testing your connection at all.
It just switching between default gateway values 0.0.0.0 to 192.168.0.1
because of this reason your vpn connection works, when vpn up your pc is using vpn client's setted gateway address.
You just opened my eyes!
I think.

This whole time, I thought I was "dropping" the network connection,
which it "looked" like it was doing. But you're saying all it did
really was drop the LOCAL gateway (which happens to be my router).

Is that correct?

I only tested the VPN connection as I was seeing what could go wrong,
where I was surprised that the VPN connection stayed up even after I
hit the NetToggle icon - but you just explained why that happens.

I don't understand networking well so may I ask if this is what is
happening?

(1) When I am NOT on a VPN server, and the NetToggle is "on",
my packets go from my computer to my router (192.168.0.1)
and then to the Internet.
The Windows 10 network monitor/globe icon shows "monitor".

Network Destination 0.0.0.0
Netmask 0.0.0.0
Gateway 192.168.0.1 (my router's IP address)
Interface 192.168.0.2 (my computer's IP address)
Metric 36 (low)

(2) When I am NOT on a VPN server, and the NetToggle is "off",
my packets go from my computer to (0.0.0.0),
which is nowhere (I guess).
The Windows 10 network monitor/globe icon shows "globe".

Network Destination 127.0.0.1 (localhost)
Netmask 255.0.0.0
Gateway On-link (whatever that means)
Interface 127.0.0.1 (localhost)
Metric 331 (medium)

(3) When I am on a VPN server, and the NetToggle is "on",
now it gets more complicated (for me to unravel).

I think my packets go from my computer to my router (192.168.0.1)
and then to the VPN server (which is on the Internet).
The Windows 10 network monitor/globe icon shows "globe".

But the "route print|more" shows a lot of lines where
the "netmask" rules such that any packets NOT destined
for 192.168.0.1 get routed (it seems in two halves) to
the Internet. (I only sort of know how netmask works.)

If I ignore that the VPN setup seems to split the Internet
into two halves, essentially I think any packet NOT destined
for my local network gets routed from my computer to the VPN
server (but those packets must go through the router first).

Network Destination 0.0.0.0
Netmask 0.0.0.0 (anything destined for my local network)
Gateway 192.168.0.1 (my router)
Interface 192.168.0.2 (my computer)
Metric 36 (low)

Network Destination 0.0.0.0
Netmask 128.0.0.0 (the first half of the Internet)
Gateway 123.123.123.10 (the VPN server IP address)
Interface 123.123.123.9 (minus one of the VPN server IP address)
Metric 35 (lower)

Network Destination 128.0.0.0
Netmask 128.0.0.0 (the second half of the Internet)
Gateway 123.123.123.10 (the VPN server IP address)
Interface 123.123.123.9 (minus one of the VPN server IP address)
Metric 35 (lower)

(4) But then I toggle that NetToggle to "off".
Now when that NetToggle is "off", the VPN connection still
works (and the "monitor/globe" network icon shows "monitor").

My packets must be getting to the VPN server somehow, and
that means they must STILL be going through my router and
then to the VPN server, but how?

Didn't the NetToggle turn the router 192.168.0.1 gateway off?
(a "route print | more" is much more confusing now.)

(5) If the VPN connection suddenly dies (for whatever reason)
my packets go from my computer to nowhere I think.

A "route print" shows EVEWRYTHING as being "On-link",
whatever that means in this context.

Certainly it means the packets are not going to the router.

Even as I know (kind of) how a netmask works, this is all
a bit confusing, but thank you for opening my eyes.

While it doesn't work the way I thought it works, it works
ok because without VPN the NetToggle switch connects and
disconnects me from the router and with VPN it protects
me when the VPN connection unexpectedly suddenly dies.

So it's all good, even as I don't really understand it all.

BTW I found a few more examples where the scheduled task
has to be broken into two parts when the %comspec% is used.

These examples don't use "cmd" so the task fits on one line.
https://www.digitalcitizen.life/use-task-scheduler-launch-programs-without-uac-prompts/
https://www.raymond.cc/blog/task-scheduler-bypass-uac-prompt/

These examples use "cmd" so they break the task into two lines.
https://www.tenforums.com/tutorials/57690-create-elevated-shortcut-without-uac-prompt-windows-10-a.html
https://winaero.com/create-elevated-shortcut-to-skip-uac-prompt-in-windows-10/
https://www.download3k.com/articles/How-to-make-an-Elevated-Program-Shortcut-without-a-UAC-Prompt-in-Windows-00805
Kerr-Mudd,John
2021-02-10 10:15:30 UTC
Permalink
On Tue, 09 Feb 2021 21:15:36 GMT, FromTheRafters
<***@nomail.afraid.org> wrote:

[]
Post by FromTheRafters
(3) This is a pretty green/red on/off icon I printscreened & edited with
Irfanview to a 45pixel by 45pixel transparent background ico file
(which I placed in the taskbar as my on/off nettoggle switch)
https://www.flaticon.com/premium-icon/icons/svg/2475/2475499.svg
When you left click that pretty green/red on/off icon in the taskbar
the Windows network symbol toggles from the monitor/globe icon
which instantly indicates the status of your network.
[]

So you didn't really need a batch solution at all!

You could create a shortcut to "Local Area Connection" and hit the
disable button! (OK, *2* double clicks"!)
I expect a VBS or Autokey Scripter could do it in 1.
--
Bah, and indeed, Humbug.
FromTheRafters
2021-02-10 16:36:47 UTC
Permalink
Post by Kerr-Mudd,John
So you didn't really need a batch solution at all!
You could create a shortcut to "Local Area Connection" and hit the
disable button! (OK, *2* double clicks"!)
I expect a VBS or Autokey Scripter could do it in 1.
Thank you for that extra idea of a shortcut to Local Area Connection.
Does it also protect when the VPN suddenly unexpectedly drops?

I was looking for a single-click pretty toggle icon in the taskbar.
I have it now (& it came with an unexpected bonus of protecting VPN!)

Off VPN
If the gateway is on, clicking once turns it off (Win10 globe icon)
If the gateway is off, clicking once turns it on (Win10 monitor icon)
On VPN
If VPN is on, clicking once protects if the VPN drops (Win10 monitor icon)
If the VPN suddenly drops, instantly the network fails (Win10 globe icon)

I didn't aim to protect VPN.
That just came as an added bonus when I tested it under various conditions.

The overall solution was pretty simple once I gave up on finding a unicorn
(1) Batch script that tests the gateway & toggles it based on that test
(2) Scheduled task running that batch script with elevated permission
(3) A pretty green/red on/off shortcut to that scheduled task in the taskbar

If there is a simpler solution out there that is a single click
I'd be happy to test it out.

I tried this for example, but it's more clicks for the same result
https://www.liquidvpn.com/vpn-kill-switches/

And I tried this software suggested by wasbit today but it didn't work
http://crystalrich.com/internetoff/
FromTheRafters
2021-02-10 19:55:24 UTC
Permalink
Post by FromTheRafters
If there is a simpler solution out there that is a single click
I'd be happy to test it out.
Someone suggested bringing the Ethernet adaptor into the taskbar as a
shortcut which can then be used to hit the "Disable" button.

Here's what they suggested (but it didn't toggle back on for me).

I went to Control Panel\Network and Internet\Network Connections\
I right clicked on "Ethernet" & chose "Create Shortcut"
which only allowed the shortcut to go to the desktop (which is ok).

I right click on the taskbar and select "Toolbars -> Links"
which adds a fugly "Links" section to the taskbar.

I dragged the desktop "Ethernet" shortcut into "Links" in the taskbar.

When I left clicked on "Links -> Ethernet" comes up as "Ethernet Status"
Which has a GUI with a big fat "Disable" button (at first).

Then from the Taskbar I can click on that Ethernet shortcut in the Links
section of the taskbar to toggle the network from enable to disable.

Oddly the Disable button is on a GUI but the Enable just happens
when you click on the "Ethernet" icon (without a GUI). Strange.

The disable works but the enable isn't consistent in my tests today.

Worse, I tried to put the Ethernet shortcut in the taskbar but nothing I
tried would let me do that (you can't right click and "pin to taskbar" for
example and you can't move it to the taskbar because it won't stick).

You can right click it and Send To your start menu or just move it there
C:\Users\FTR\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Ethernet

But I couldn't get that "Ethernet" shortcut to stick to the taskbar
no matter what I tried.

If this Ethernet adaptor disable/enable method can be made to work in a
batch script it would toggle the network (and not just the gateway).
Kerr-Mudd,John
2021-02-11 09:27:47 UTC
Permalink
On Wed, 10 Feb 2021 19:55:24 GMT, FromTheRafters
Post by FromTheRafters
Post by FromTheRafters
If there is a simpler solution out there that is a single click
I'd be happy to test it out.
Someone suggested bringing the Ethernet adaptor into the taskbar as a
shortcut which can then be used to hit the "Disable" button.
It was me, 9 hours earlier 2 messages back in this thread!
Post by FromTheRafters
If this Ethernet adaptor disable/enable method can be made to work in
a batch script it would toggle the network (and not just the gateway).
http://ixquick.com/do/metasearch.pl?
query=cmd+disable+local+area+connection

https://www.neowin.net/forum/topic/848202-disable-local-area-connection-
from-command-line/?cmpredirect

sounds similar:

Netsh interface set interface "Local Area Connection" disable

ditto enable; needs admin (or an Unicorn)



What is it you actually want to achieve?
--
Bah, and indeed, Humbug.
FromTheRafters
2021-02-11 15:59:37 UTC
Permalink
Post by Kerr-Mudd,John
What is it you actually want to achieve?
The most graceful way possible to kill the "network."
FromTheRafters
2021-02-11 22:30:46 UTC
Permalink
FromTheRafters used his or her keyboard to write :
I originally used separate on and off gateway toggles until this thread
(OFF) Run as admin to disconnect the gateway to the Internet connection
%comspec% /c route delete 0.0.0.0 192.168.0.1

(ON) Run as admin to toggle the gateway to the Internet connection back on
%comspec% /c route add 0.0.0.0 mask 0.0.0.0 192.168.0.1

I originally wanted to string those two together but the if/then/else
worked better given the need to toggle both ways & to avoid the UAC query.

I learned only somewhere in the middle of this thread that there is no
way possible to get around the UAC query inside of a batch script.

That is why people suggested using the task scheduler which bypasses the
UAC query (if I set the scheduled task to run with elevated privileges).

I should also make it clear that I have an ethernet cable connection
(I don't feel like crawling on the floor to toggle it on and off).

If you have a wifi connection it may be easier to toggle from the taskbar
(but this method works just the same whether you're on wifi or ethernet).

Also the "NetToggle" should probably be called "GateToggle" since it doesn't
actually turn off the network but just the gateway (toggling the gateway adds
bonus advantages for when your VPN connection suddenly unexpectedly drops).
@echo off
REM gatetoggle.bat (set the default gateway to YOUR router IP address!)
set defgw=192.168.0.1
set "ip="
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do if not defined ip set ip=%%~a
IF "%ip%"=="%defgw%" ( %comspec% /c %windir%\system32\route.exe delete 0.0.0.0 %defgw%) ELSE ( %comspec% /c %windir%\system32\route.exe add 0.0.0.0 mask 0.0.0.0 %defgw%)
exit

While you're testing that script, you can right click on it and select
"Run as administrator" which will bring up the UAC query also.

If it doesn't work, put "pause" statements and "echo" requests of
the variables to help you debug why it's not working yet for you.

Once you have it working you can run taskschd.msc to create a task
in the "Task Scheduler Library" of something like this
Name: GateToggle (Run with highest privileges)
Action: Start a program
Program/script: %comspec%
Add arguments (optional): /c start "" c:\custom\gatetoggle.bat

Then you can create a new shortcut target using the schtasks command
C:\Windows\System32\schtasks.exe /run /TN "GateToggle"

For the shortcut icon I saved a prntscrn of this pretty on/off icon
https://www.flaticon.com/premium-icon/icons/svg/2475/2475499.svg
With Irfanview I saved that as a 45x45px transparent bg ico and stored
that icon file in the custom directory c:\custom\gatetoggle.ico

Then I pinned that c:\custom\gatetoggle.lnk shortcut to the taskbar.

For archive I exported & imported the taskschd.msc elevated task
schtasks /query /xml /tn "GateToggle" > C:\custom\gatetoggle.xml
schtasks /create /f /xml C:\custom\gatetoggle.xml

This is the exported task "gatetoggle.xml"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2021-02-11T24:24:24.5482511</Date>
<Author>FTR\ftr</Author>
<Description>Single-click taskbar on/off toggle of the local network gateway</Description>
<URI>\GateToggle</URI>
</RegistrationInfo>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-1978554282-387915082-910891285-1001</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
</Settings>
<Triggers />
<Actions Context="Author">
<Exec>
<Command>%comspec%</Command>
<Arguments>/c start "" c:\custom\gatetoggle.bat</Arguments>
</Exec>
</Actions>
</Task>

These are some of the links which were used to create this solution
http://crystalrich.com/internetoff/
https://community.spiceworks.com/topic/329458-using-if-else-login-with-findstr-in-batch-script
https://petri.com/3-ways-disable-network-connection-windows-10
https://stackoverflow.com/questions/11081735/how-to-use-if-else-structure-in-a-batch-file
https://stackoverflow.com/questions/1894967/how-to-request-administrator-access-inside-a-batch-file/10052222
https://stackoverflow.com/questions/22367173/get-default-gateway-from-batch-file
https://stackoverflow.com/questions/8530976/how-to-conditionally-take-action-if-findstr-fails-to-find-a-string
https://superuser.com/questions/1331606/how-to-toggle-wi-fi-in-windows-10-via-the-command-line
https://winaero.com/create-elevated-shortcut-to-skip-uac-prompt-in-windows-10/
https://www.digitalcitizen.life/use-task-scheduler-launch-programs-without-uac-prompts/
https://www.download3k.com/articles/How-to-make-an-Elevated-Program-Shortcut-without-a-UAC-Prompt-in-Windows-00805
https://www.raymond.cc/blog/task-scheduler-bypass-uac-prompt/
https://www.robvanderwoude.com/schtasks.php
https://www.techspot.com/guides/287-default-router-ip-addresses/
https://www.tenforums.com/tutorials/57690-create-elevated-shortcut-without-uac-prompt-windows-10-a.html
http://youtu.be/2JOsdTpq3qY
Fin Tres Nueve Dos
2021-05-03 05:47:47 UTC
Permalink
What about this option?

List of network interfaces: netsh interface show interface

Disable an interface: netsh interface set interface "interface_name" disable

Enable an interface: netsh interface set interface "interface_name" enable
FromTheRafters
2022-03-30 18:10:14 UTC
Permalink
Post by Fin Tres Nueve Dos
What about this option?
List of network interfaces: netsh interface show interface
Disable an interface: netsh interface set interface "interface_name" disable
Enable an interface: netsh interface set interface "interface_name" enable
Saw these on another newsgroup and am putting the links here for you.
https://www.action1.com/how-to-enable-disable-or-restart-network-adapter/
https://gist.github.com/gusg21/d5c81c70cc0935be006b21673fadcf7d
https://www.yeahhub.com/enable-disable-network-connection-windows-10-wmic-netsh-powershell/
https://stackoverflow.com/questions/14424338/netsh-interface-set-interface-name-local-area-connection-2-admin-disabled
https://michlstechblog.info/blog/windows-show-and-configure-network-settings-using-netsh/
https://www.windowscentral.com/how-enable-or-disable-wi-fi-and-ethernet-network-adapters-windows-10

Default Gateway.
https://stackoverflow.com/questions/52090451/batch-script-file-get-default-gateway-and-ping-ip-address
https://stackoverflow.com/questions/22367173/get-default-gateway-from-batch-file

Net Disabler.
https://www.sordum.org/9660/net-disabler-v1-1/
https://www.accuratereviews.com/how-to-temporarily-disable-your-internet-connection/
https://techtipsnreview.com/on-off-and-manage-the-internet-on-your-computer-with-net-disabler/
https://www.thewindowsclub.com/net-disabler-turn-internet-on-off
https://www.ghacks.net/2017/02/22/net-disabler/
https://www.majorgeeks.com/files/details/net_disabler.html

Network Kill.
https://sourceforge.net/projects/subproject.network-ip-tools.p/

VPN Watcher.
https://www.raymond.cc/blog/download/did/3743/

VPN Lifeguard.
https://www.raymond.cc/blog/download/did/3744/

VPN Check.
https://www.raymond.cc/blog/download/did/3745/

Comodo Kill.
https://offlinemn.tistory.com/11

Kill DHCP.
https://blog.shiraj.com/2012/10/netsh-command-to-change-from-static-ip-address-to-dhcp/

Disable Network.
https://www.action1.com/how-to-enable-disable-or-restart-network-adapter/

Internet Off.
http://crystalrich.com/internetoff/

Kill Switch.
https://www.raymond.cc/blog/automatic-vpn-kill-switch/
https://www.raymond.cc/blog/download/did/3746/
https://raymondcc.r.worldssl.net/LiquidVPN-Kill-Switch-3746.zip (raymondcc)
@echo off

:: GetAdmin
:-------------------------------------
:: Verify permissions
Post by Fin Tres Nueve Dos
nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
:: On Error No Admin
if '%errorlevel%' NEQ '0' (
echo Getting administrative privileges...
goto DoUAC
) else ( goto getAdmin )

:DoUAC
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B

:getAdmin
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------


@echo off
:: CHANGE DEFAULT GW IP BELOW
set defgw=192.168.0.1


@For /f "tokens=3" %%1 in (
'route.exe print 0.0.0.0 ^|findstr "\<0.0.0.0.*0.0.0.0\>"') Do set defgw=%%1
cls
:start
cls
echo.
color 0C
echo LiquidVPN's Simple VPN Kill Switch, ver. 0.1 - by LiquidVPN

echo.
echo.
echo Your routers gateway is probably "%defgw%"
echo -if nothing appears or its incorrect, add it manually (Press '3')
echo.
echo USAGE:
echo.
echo -Press "1" to Enable Kill Switch (IP "%defgw%")
echo -Press "2" to Disable Kill Switch (IP "%defgw%")
echo -Press "3" to manually set default gateway if its not detected above.
echo -Press "h" for Kill Switch Help
echo -Press "x" to exit Kill Switch.
echo.
set /p option=Your option:
if '%option%'=='1' goto :option1
if '%option%'=='2' goto :option2
if '%option%'=='3' goto :option3
if '%option%'=='x' goto :exit
if '%option%'=='h' goto :help
echo Insert 1, 2, x or h
timeout 3
goto start
:option1
route delete 0.0.0.0 %defgw%
echo Default gateway "%defgw%" removed
timeout 3
goto start
:option2
route add 0.0.0.0 mask 0.0.0.0 %defgw%
echo Defaulte gateway "%defgw%" restored
timeout 3
goto start
:option3
echo
set /p defgw=your gw IP (e.g. 192.168.0.1):
goto start
:help
cls
echo.
echo.
echo ======================
echo This simple kill switch removes your default gateway
echo and blocks traffic from reaching the internet when
echo your VPN gets disconnected.
echo.
echo Here is how you use it.
echo.
echo Step 1: Connect to LiquidVPN
echo Step 2: Enable LiquidVPN's Kill Switch (option "1")
echo.
echo Now Any internet traffic will pass through LiquidVPN only.
echo.
echo - If your VPN gets disconnected so will your internet.
echo - Disable the Kill Switch and reconnect.
echo.
echo.
echo When you disconnect from LiquidVPN follow these steps
echo to reconnect or to browse the internet normally.
echo.
echo Step 1: Close any software that may leak your real IP
echo Step 2: Disable the LiquidVPN kill switch (Option "2")
echo Step 3: Reconnect to LiquidVPN and enable the kill switch (Option "1")
echo.
timeout /T -1
goto start
:exit
exit

FromTheRafters
2022-03-30 05:55:05 UTC
Permalink
USE MODEL:
a. Hit the taskbar shortcut (gwtoggle.lnk)
b. If the network was on, it (the gateway) will be turned off.
If the network was off, it (the gateway) will be turned on.
The Windows hardware icons will show the status accordingly.
c. If VPN was on, nothing will happen until the VPN drops.
If the VPN subsequently drops, the network (gateway) will be turned off.
The Windows hardware icons will show the status accordingly.

TASKBAR SHORTCUT:
gwtoggle.lnk
Target = C:\Windows\System32\schtasks.exe /run /TN "task gwtoggle"

SCHEDULED TASK:
taskschd.msc
task gwtoggle
Run with highest privileges = checked
Action = Start a program
Program/script = %comspec%
Add arguments = /c start "anything" c:\pathto\gwtoggle.bat

BATCH SCRIPT:
c:\pathto\gwtoggle.bat
@echo off
set defgw=192.168.1.1
set "ip="
for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do if not defined ip set ip=%%~a
IF "%ip%"=="%defgw%" ( %comspec% /c %windir%\system32\route.exe delete 0.0.0.0 %defgw%) ELSE ( %comspec% /c %windir%\system32\route.exe add 0.0.0.0 mask 0.0.0.0 %defgw%)
exit

SHORTCUT ICONS:
https://www.flaticon.com/free-icons/on-off
https://icons8.com/icons/set/on-off
https://iconarchive.com/tag/on-off

Example icon:
Loading Image...
Loading...