有另一个库或PYODBC,可以访问SQL Server Configuration Manager,以便我获取此服务列表?
作为附带说明,我使用WMI的Win32_Product类尝试检索与SQL Server相关的任何内容,但它返回了太多不需要的回报,例如语言包,驱动程序等。
server_connection = wmi.WMI(server, user=username, password=password)
task = server_connection.Win32_Product()
`for service in task:`
`if 'SQL Server' in service.Caption:`
`print(f"Service Name: {service.Caption}")`
如果您尝试使用Python检索SQL Server Services(SQL Server Configuration Manager)的列表,那么最好的方法是使用WMI(Windows Management Instrumentation)。 Win32_Product类检索太多无关的结果(例如驱动程序,语言包),因此,您应该使用win32_service.
import wmi
server = "your_server_name" # Change this to your target server
username = "your_username" # If needed
password = "your_password" # If needed
# Connect to the machine
server_connection = wmi.WMI(server, user=username, password=password)
# Get SQL Server-related services
for service in server_connection.Win32_Service():
if "SQL" in service.Name or "SQL" in service.DisplayName:
print(f"Service Name: {service.Name}")
print(f"Display Name: {service.DisplayName}")
print(f"State: {service.State}")
print(f"Start Mode: {service.StartMode}")
print("-" * 50)
SQLServer服务通常包括
MSSQLSERVER
(默认实例),SQLSERVERAGENT
SQLBrowser
,SQLWriter
等。如果您需要所有已安装的SQL Server实例(即使它们当前未运行),请查询Windows注册表:
import winreg
def get_sql_instances():
sql_instances = []
reg_path = r"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL"
try:
reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
i = 0
while True:
try:
instance_name, service_name, _ = winreg.EnumValue(reg_key, i)
sql_instances.append((instance_name, service_name))
i += 1
except OSError:
break
except FileNotFoundError:
print("SQL Server registry path not found.")
return sql_instances
# Example usage
for instance, service in get_sql_instances():
print(f"Instance Name: {instance} - Service Name: {service}")