Tuesday, January 25, 2022

Careful - it opens all ports - batch script

 echo off

if "%1"=="-np" goto HandleNp
if "%1"=="-rpc" goto HandleRpc
if "%1"=="-tcp" goto HandleTcp
if "%1"=="-browser" goto HandleBrowser

rem Usage
:Usage

echo "Usage: setupSqlServerPortAll -[np | rpc | tcp | browser] -port [portnum] -[enable | disable]
echo "-np : Setup SQLServer to listen on Named Pipe connections for local subnet only"
echo "-rpc : Setup SQLServer to listen on RPC multiprotocol for local subnet only"
echo "-tcp : Setup SQLServer to listen on TCP connections for local subnet only"
echo "       Must specify a port if -tcp option is chosen."
echo "-browser :  Setup SQLServer to provide SSRP service to support named instances"
echo "-port : Applies only for tcp"
echo " One of the following options MUST be specified"
echo "-enable: Enables a port"
echo "-disable: Disables a port"

goto Exit

:HandleTcp
echo %2
if "%2"=="-port" goto cont
goto Usage
:cont
if "%3"=="" goto Usage
if "%4"=="-enable" goto EnableTcp
if "%4"=="-disable" goto DisableTcp
goto Usage

:EnableTcp
echo "Enabling SQLServer tcp access for port %3 local subnet only"
netsh firewall set portopening tcp %3 SQL%3 ENABLE subnet
goto Exit

:DisableTcp
echo Disabling SQLServer tcp access for port %3 local subnet only"
netsh firewall set portopening tcp %3 SQL%3 disable subnet
goto Exit

:HandleNp
if "%2"=="-enable" goto EnableNp
if "%2"=="-disable" goto DisableNp
goto Usage

:EnableNp
echo "Enabling SQLServer named pipe access for local subnet only"
netsh firewall set portopening tcp 445 SQLNP ENABLE subnet
goto Exit

:DisableNp
echo Disabling SQLServer named pipe access for local subnet only"
netsh firewall set portopening tcp 445 SQLNP DISABLE subnet
goto Exit

:HandleRpc
if "%2"=="-enable" goto EnableRpc
if "%2"=="-disable" goto DisableRpc
goto Usage

:EnableRpc
echo "Enabling SQLServer multiprotocol access for local subnet only"
netsh firewall set portopening tcp 445 SQLNP enable subnet
goto Exit

:DisableRpc
echo Disabling SQLServer multiprotocol access for local subnet only"
netsh firewall set portopening tcp 445 SQLNP disable subnet
goto Exit

:HandleBrowser
if "%2"=="-enable" goto EnableBrowser
if "%2"=="-disable" goto DisableBrowser
goto Usage

:EnableBrowser
echo "Enabling SQLServer SSRP service for local subnet only"
netsh firewall set portopening udp 1434 SQLBrowser enable subnet
goto Exit

:DisableBrowser
echo "Enabling SQLServer SSRP service for local subnet only"
netsh firewall set portopening udp 1434 SQLBrowser disable subnet
goto Exit

:Exit
endlocal