logo

K8哥哥

没有绝对安全的系统

利用SqlDataSourceEnumerator获取局域网SQL主机

本文于 1304 天之前发表

前言

SQL Server 允许应用程序在当前网络中查找 SQL Server 实例。 SqlDataSourceEnumerator 类向应用程序开发人员公开此信息,提供包含所有可见服务器的信息的 DataTable。 此返回的表包含网络上可用的服务器实例的列表,该列表与用户尝试创建新连接时提供的列表匹配,并展开包含连接属性上所有可用服务器的下拉列表。对话框。 显示的结果并非总是完整的。

SqlDataSourceEnumerator

命名空间: System.Data.Sql
程序集: System.Data.dll

提供了一种枚举本地网络内的所有可用 SQL Server 实例的机制。

通过方法调用返回的表包含以下列,所有列均包含 string 值:
列 描述
ServerName 服务器的名称。
InstanceName 服务器实例的名称。 如果服务器作为默认实例运行,则为空白。
IsClustered 指示服务器是否属于群集。
Version 服务器的版本。 例如:

-9.00 (SQL Server 2005)
-10.0. xx (SQL Server 2008)
-10.50 (SQL Server 2008 R2)
-11.0. xx (SQL Server 2012)

C#示例代码

.NET与PowerShell谁的兼容性和执行效率更好就不用我说了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System.Data.Sql;  

class Program
{
static void Main()
{
// Retrieve the enumerator instance and then the data.
SqlDataSourceEnumerator instance =
SqlDataSourceEnumerator.Instance;
System.Data.DataTable table = instance.GetDataSources();

// Display the contents of the table.
DisplayData(table);

Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}

private static void DisplayData(System.Data.DataTable table)
{
foreach (System.Data.DataRow row in table.Rows)
{
foreach (System.Data.DataColumn col in table.Columns)
{
Console.WriteLine("{0} = {1}", col.ColumnName, row[col]);
}
Console.WriteLine("============================");
}
}
}

PowerShell命令

系统未安装或禁用PowerShell会失效,但也比国人故意吹捧的PowerUPSQL好很多倍。

1
2
3
4
5
6
C:\Users\k8gege\Desktop>PowerShell -Command "[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()"

ServerName InstanceName IsClustered Version
---------- ------------ ----------- -------
K82003-77562E10
WIN-OLDM1T2H9M4

PowerUPSQL

此工具也是基于SqlDataSourceEnumerator实现的,兼容性较差,很多系统下运行各种报错。

PS C:\Users\k8gege\Desktop\PowerUpSQL-master> Get-SQLInstanceBroadcast -Verbose
详细信息: Attempting to identify SQL Server instances on the broadcast domain.
详细信息: 2 SQL Server instances were found.

ComputerName                        Instance                           IsClustered                        Version                           
------------                        --------                           -----------                        -------                           
K82003-77562E10                     K82003-77562E10                                                                                         
WIN-OLDM1T2H9M4                     WIN-OLDM1T2H9M4          

Ladon EnumMssql

Ladon的EnumMssql模块不支持扫描,若内网存在多个网段,可使用PortScan扫描探测。
img

Ladon与PowerUPSQL对比,Ladon支持任意Win系统,而PowerUPSQL就未必能用了
img

参考

https://github.com/k8gege/Ladon
https://docs.microsoft.com/zh-cn/dotnet/framework/data/adonet/sql/enumerating-instances-of-sql-server

扫码加入K8小密圈