windowsbatch-filenetwork-programmingnetsh

netsh and blocking access to all but one WLAN


Currently, I'm using this:

netsh wlan add filter permission=block ssid="WLAN1" networktype=infrastructure

to hide specific WLAN SSIDs from showing up in the systray. Since there's usually more than one of them available, I've decided to put them all in a *.bat file, like so

@echo off
netsh wlan add filter permission=block ssid="WLAN1" networktype=infrastructure
netsh wlan add filter permission=block ssid="WLAN2" networktype=infrastructure
netsh wlan add filter permission=block ssid="AnotherWLAN" networktype=infrastructure
etc

and to block them all with a single click.

However, this keeps them hidden only while the blocked WLANs have those predefined SSIDs. If they change their SSID, they show up again, and I have to change my file. This isn't a problem when there's a few of them, but there's usually more than 20 showing up.

WHAT I WOULD LIKE TO DO

Is there a way for me to use netsh and, say, an if, for, or while loop, to block everything BUT the one SSID I choose? For example, in (broken) pseudo code

    SET myWLAN = Home                // e.g. home WLAN SSID = Home
    if (! SSID == myWLAN) {
       loop through the available SSID, and block them via netsh
    }

Or, would you recommend that I just go with:

netsh wlan add filter permission=denyall networktype=infrastructure

and then create a special whitelist filter for my home WLAN

netsh wlan delete filter permission=block ssid="myWLAN SSID" networktype=infrastructure

I'm pretty much new to all of this, so any help would be more than welcome.


Solution

  • @ECHO OFF
    SETLOCAL
    
    SET "allow=WLAN1"
    
    FOR /f "tokens=3*" %%a IN ('netsh wlan show all^|findstr /i /b /L /c:"SSID "') DO (
     IF "%%b" neq "%allow%" ECHO(netsh wlan add filter permission=block ssid="%%b" networktype=infrastructure
    )
    
    GOTO :EOF
    

    This batch searches the netsh wlan show all output for lines /b beginning /i regardless of case /L the literal /c: this constant string.

    The tokenising is performed using tokens 3 and * (the remainder of the line) using default delimiters hich include space, so a typical SSID line filtered would be

    SSID 5 : WLAN2
    

    Token 1 is SSID, 2 is 5, 3 is : and 4 is WLAN2

    Since the first nominated token is 3, that token is assigned to %%a and the next token is assigned to %%b.

    Then if the token now in %%b does not match the allowed string, block it (well, the command is simply echoed for debugging - change the echo(netsh to netsh to activate.

    If you were to use

    set "allow=%~1" instead of `...WLAN1` then you could run<br>
    

    thisbatch WLAN4

    to block all except WLAN4.