-
Технические форумы
-
Системы управления базами данных
-
Microsoft SQL Server
-
Автор темы
Автор темыNanoSuit
-
Дата начала
Дата начала -
-
Теги
Теги -
firewall
-
-
-
#1
Приветствую. Ставлю Microsoft SQL Server 2016 в качестве изолированного инстанса на новый сервер. Не проходит проверка требований для установки. Проверка не проходит на этапе IsFirewallEnabled
Брандмауэр Windows включен. Чтобы обеспечить удаленный доступ, убедитесь, что открыты соответствующие порты.
Какии порты нужно открыть для sql сервера? И как..
-
-
#2
Код:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
и для повышенной безопасности
Код:
netsh advfirewall firewall add rule name = SQLPort dir = in protocol = tcp action = allow localport = 1433 remoteip = localsubnet profile = DOMAIN
-
Технические форумы
-
Системы управления базами данных
-
Microsoft SQL Server
-
На данном сайте используются cookie-файлы, чтобы персонализировать контент и сохранить Ваш вход в систему, если Вы зарегистрируетесь.
Продолжая использовать этот сайт, Вы соглашаетесь на использование наших cookie-файлов.
Введение
В статье описано, как разрешить подключаться к базе данный MS SQL Server через брандмауэр
Настройка
В Брандмауэре необходимо разрешить входящие соединения.
Откройте Брандмауэр Windows — Пуск > Панель управления > Администрирование > Монитор брандмауэра Защитника Windows в режиме повышенной безопасности
|
На следующем шаге Укажите протокол TCP и порт — 1433 |
Выберите Разрешить подключение |
В настройках профилей поставьте флажки на всех 3 пунктах |
Укажите имя для созданного правила |
На клиентском компьютере в SQL Management Studio не обязательно вводить адрес нужного экземпляра БД. |
Теперь можно подключаться с этого компьютера к базе данных.
(Updated 2016-10-24)
Intro
If you want to allow remote computers on your network to access an instance of Sql Server running on one machine, you’ll have to add some new Incoming rules to the Windows Firewall, or no connections can come through. So, let’s show you what has to be considered and how to achieve this.
Sql Server Instance Types
Before you can configure the Windows Firewall to allow remote access to your Sql Server instance, it’s important to understand the “instance type” of the Sql Server that you are running. For Sql Server, its “instance type” can either be the default instance, an unnamed instance, or a named instance. Which one you have determines which port you have to open in Windows Firewall.
- When SQL Server is installed as the default instance, it does not require a client to specify the name of the instance to make a connection. The client only has to know the server name. This typically uses Port 1433 in the TCP protocol.
- A named instance is identified by the network name of the computer plus the instance name that you specify during installation (i.e. \\ComputerName\SqlExpress or something similar). The client must specify both the server name and the instance name when connecting. This typically uses the Sql Server Browser service to find the Sql Server instance, and that requires access to Port 1434 UDP protocol.
Windows Firewall Setup to Allow Remote Access
So, in order to allow remote access to the Sql Server instance, you will need to add these Incoming rules to the Windows Firewall:
- Add an Incoming rule to all access the application SqlServr.exe (C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Binn\sqlservr.exe)
- If you want to access the Sql Server Instance from other computers by using the computer name (i.e. {ComputerName}\SQLEXPRESS, you will need to add an Incoming rule to allow access to the application SqlBrowser.exe (C:\Program Files (x86)\Microsoft SQL Server\90\Shared\sqlbrowser.exe). Note: If you are only going to use the IP address {xxx.xxx.xxx.xxx}\SQLEXPRESS, then you will not need this rule for SqlBrowser.exe.
- Add an Incoming rule for the correct port (1433 TCP or 1434 UDP depending on Sql Server instance type (from above)).
You can use these handy Poweshell scripts to add the above Firewall rules:
# http://mattslay.com/opening-up-windows-firewall-to-allow-sql-server-to-allow-remote-connections/ # https://blog.brankovucinec.com/2015/12/04/scripts-to-open-windows-firewall-ports-for-sql-server/ Write-host Enabling SQLServer Default instance port 1433 TCP Inbound New-NetFirewallRule -DisplayName «SQL Server TCP Port 1433» –Direction inbound -Protocol TCP –LocalPort 1433 -Action Allow Write-host Enabling SQLServer Named Instance port 143 UDP Inbound New-NetFirewallRule -DisplayName “SQL Server UDP Port 1434” -Direction Inbound –Protocol UDP –LocalPort 1434 -Action allow Write-host Enabling SQLServer EXE Application rule New-NetFirewallRule -DisplayName “SQL Server EXE” -Direction Inbound -Program «C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Binn\sqlservr.exe» -Action allow Write-host Enabling SQLServer Browser Application rule New-NetFirewallRule -DisplayName “SQL Server Browser” -Direction Inbound -Program «C:\Program Files (x86)\Microsoft SQL Server\90\Shared\sqlbrowser.exe» -Action allow |
You should see the new rules here:
Sql Server Full version
For the full version of Sql Server (not Express), by default it installs as the default instance unless you specify an instance name. So, the next step to allow remote connections to the default instance is to add a Port Rule to open Port 1433 for the TCP protocol.
Sql Server Express
SQL Server Express always installs by default as a named instance unless you force a default instance during setup. So, if you are running a named instance of Sql Server (or Sql Server Express), and you want to allow remote connections to it, add an Incoming port rule for Port 1434 for the UDP protocol.
Since I was running a named instance, I found that I did not need the 1433 TCP port rule at all, I only needed the 1434 UDP port rule (along with the two application rules) to get it working on my network.
Other steps to check
This post only covers the Windows Firewall. There are other steps required in configuring Sql Server itself:
- Enabling the correct protocols, and make sure Sql Server has the option “Allow remote connections to this server” checked on the Connections tab of the Server properties. You can access this setting in Sql Server Management Studio tool.
- Enable the correct protocols in the Sql Server Configuration Management Tool, under the Sql Server Network Configuration node. Honest, I wasn’t sure exactly which I needed, so I enabled all 3. I’m pretty sure TCP/IP was disable by default.
Some details pulled from these links:
https://technet.microsoft.com/en-us/library/ms165614%28v=sql.90%29.aspx
and a comment by user J_m on this Technet article: https://technet.microsoft.com/en-us/library/ms175043%28v=sql.110%29.aspx
Doctor of Code
May 2, 2016 updated by
Leave a reply »
By default, Windows Firewall doesn’t allow inbound / outbound requests for SQL Server. If you try to connect to a SQL Server instance from network, you might get the error saying “The server was not found or was not accessible”. In this tutorial we’ll show you 2 ways to configure Windows Firewall to allow SQL Server access.
Method 1: Allow SQL Server Access Through Control Panel
- Open Control Panel in Large icons or Small icons view, click on Windows Firewall.
- Click the link “Allow a program or feature through Windows Firewall” on the left of window.
- You will now see a list with all the apps which are allowed to communicate through the Windows Firewall. To change the rules, you need to click the Change Settings button. The list of rules will no longer be gray and you will be able to edit it.
- Click the “Allow another program…” button.
- From the “Add a Program” window, click the Browse button.
- Navigate to the installation path for your SQL Server instance and select sqlservr.exe, and click Open. In my example, the location is
C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe
. - You’ll back to the “Add a Program” window and see SQL Server is added to the list. Click the Add button.
- SQL Server now appears in the list of Allowed programs and features. You can check any of the location types: private or public. When done, press OK.
Method 2: Allow SQL Server Access Through Command Prompt
- Open an elevated Command Prompt.
-
You can run the Netsh advfirewall command to open all ports for SQL Server connections. Assuming the path of your SQL Server service is C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe, copy / and paste the following commands in the Command Prompt, press Enter after each.
netsh advfirewall firewall add rule name="SQL Server TCP" protocol=tcp dir=in action=allow program="C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" enable=yes profile=any localip=any localport=any remoteip=any remoteport=any
netsh advfirewall firewall add rule name="SQL Server UDP" protocol=udp dir=in action=allow program="C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" enable=yes profile=any localip=any localport=any remoteip=any remoteport=any
- When it’s done, you’ve successfully opened up all ports to allow SQL Server access through Windows Firewall.
- Previous Post: How to Reset Start Menu Layout to Default in Windows 10
- Next Post: How to Block An Application from Running in Windows 10
Пройдите тест, узнайте какой профессии подходите
Работать самостоятельно и не зависеть от других
Работать в команде и рассчитывать на помощь коллег
Организовывать и контролировать процесс работы
Быстрый ответ
Для того, чтобы подключиться к SQL Server с использованием Windows-идентификации, установите параметр Integrated Security
в строке подключения на true
или SSPI
:
Убедитесь, что у пользователя Windows, запустившего процесс, есть соответствующие права доступа к SQL Server.

Основные компоненты успешного подключения
Создание строки подключения
Строка подключения должна включать параметры Server
или Data Source
, Database
или Initial Catalog
, а также параметр Integrated Security
, установленный на SSPI
или True
. Для именованного экземпляра SQL Server укажите его имя:
Включение удаленного доступа
Включите удаленное подключение в диспетчере конфигурации SQL Server в настройках сетевых служб экземпляра.
Обеспечение доступности сервера в сети
Убедитесь, что сервер SQL доступен с компьютера, который пытается установить подключение. Настройки брандмауэра и проблемы сетевой стабильности могут помешать подключению. Проверьте соединение с помощью TELNET или специализированной диагностической программы.
Защита строк подключения
Для динамического и безопасного формирования строк подключения и защиты конфиденциальных данных используйте SqlConnectionStringBuilder
.
Особенности для ASP.NET
Для приложений на ASP.NET, включите Windows-идентификацию в настройках IIS и назначьте необходимую служебную учётную запись, которая должна быть зарегистрирована в SQL Server. Разместите строку подключения в файле Web.config
.
Визуализация
Подумайте о SQL Server как о закрытой двери (🚪). Вы можете открыть её, используя ключ Windows-идентификации (🔑).
Когда вы применяете данные Windows-учётной записи, поворачивая этот цифровой ключ, вы получаете доступ.
Откройте эту дверь, и вы увидите ресурсы (🔮), скрытые за ней!
Теперь вы получили доступ к вашему миру данных! 🎉
Дополнительные требования и решения
Избегайте ошибок
Обработайте исключения, связанные с подключением, используя эффективный обработчик ошибок. Возникающие ошибки, например, из-за неправильных имен экземпляров, отказов в работы сервисов или проблем с правами доступа, должны быть контролируемы.
Обратный инжиниринг и устранение проблем
Если возникают проблемы с разрешением имен, попробуйте использовать IP-адрес вместо имени сервера. При вводе путей с двойными обратными слешами может потребоваться их удвоение.
Применение лучших практик
Перейдите на Windows-идентификацию вместо анонимной для безопасной передачи данных учётной записи Windows к SQL Server.
Полезные материалы
- Строки подключения к SQL Server — справочник по строкам подключения, включая Windows-идентификацию.
- Помощь в подключении — полезные советы по Windows-идентификации и SQL Server с Stack Overflow.
- Защита ваших данных — основы безопасности и лучшие практики предотвращения SQL-иньекций.
- Лабиринты подключений — помощь в поиске оптимальной строки подключения.
- Командный центр SQL Server — подборка инструментов для диагностики и устранения проблем подключения.