Monday, February 15, 2010

Automate adding Server 2008/R2 Firewall rule for SQL Server

On servers that are running Windows server 2008 or later, you can take advantage of the built-in two-way firewall. Rules can be pretty easily created through the GUI, but it can be a bit tedious. So this weekend I wrote a little batch file that asks you for an IP address and then opens the SQL port such that it only accepts connections from that IP.

You can of course extend this to any other program just by modifying the switches, protocols, IPs, etc. It will error out if you don't supply an IP address, so that you don't get a meaningless rule. A new rule is created each time you run the command..it doesn't update an existing rule. That is possible with the netsh command though.

@echo off
:: Configures Windows Server 2008/R2 firewall for SQL.

:: Requires a single argument, the IP address of the remote application server that requires SQL access.

:: Usage: SQL-Firewall.cmd

if [%1]==[] ; GOTO :ERROR

Echo Configuring Windows Advanced Firewall for SQL to listen on IP %1

netsh advfirewall firewall add rule name="SQL Server (TCP-in)" dir=in action=allow protocol=TCP Profile=domain localport=1433 program="D:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn\sqlservr.exe" description="Allows inbound Microsoft SQL connections." remoteip=%1

Exit /B

:ERROR

Echo Please specify IP address.

3 comments:

  1. Would it really be asking too much for me to expect Microsoft to make a set of firewall exceptions for SQL server, so I can enable and disable them as needed for the different contexts? On their "Configuring Windows Firewall to Allow SQL Server Access" they don't even mention if the rules are inbound or outboud. Now they certainly can provide that info, right?

    ReplyDelete
  2. Completely agree with the comments above, a glaring omission by Microsoft.

    Worse still predefined SQL exceptions are still ominously absent in R2!!

    ReplyDelete
  3. hi.. if i have make firewall rule for SQL server to access it from WAN side,then which port i have to define for SQL to accessing it from WAN

    ReplyDelete