You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Inspec验证MSSQL集成身份验证模式?Ruby执行SQL查询方法

搞定Inspec验证MSSQL集成身份验证模式的方法

嘿,我正好有经验处理这个需求!你已经拿到了能查询身份验证模式的SQL语句,接下来只需要在Inspec里用Ruby把这个查询跑起来,再断言结果符合预期就可以了。下面给你一步步拆解:

第一步:确认你的SQL查询没问题

先确认你的查询能正确返回状态,常用的标准查询是:

SELECT SERVERPROPERTY('IsIntegratedSecurityOnly') AS IsIntegratedSecurityOnly;

这个语句返回1就代表服务器只用集成身份验证,返回0就是混合模式(集成+SQL账号登录都允许)。

第二步:在Inspec控制文件里写Ruby代码执行查询

Inspec自带了mssql_session资源,能帮你快速建立SQL连接并执行自定义查询,直接写进你的控制文件就行,示例代码如下:

control 'mssql-integrated-auth-enforced' do
  impact 1.0
  title 'Verify MSSQL is configured for Integrated Authentication Only'
  desc 'Make sure SQL Server only allows Windows Integrated Authentication, no SQL logins'

  # 建立MSSQL会话——如果用当前Windows账号的集成权限连接,就不用写user和password
  sql = mssql_session(host: '你的SQL服务器地址', instance: 'MSSQLSERVER')

  # 执行你的查询,拿到结果集
  auth_mode_result = sql.query("SELECT SERVERPROPERTY('IsIntegratedSecurityOnly') AS IsIntegratedSecurityOnly;")

  # 断言结果必须是1(仅集成模式)
  describe auth_mode_result.rows.first['IsIntegratedSecurityOnly'] do
    it { should eq 1 }
  end
end

几个关键细节要注意

  • 连接参数灵活调整:如果你的环境需要指定域账号来连接,就把user和password加上,比如user: 'your_domain\\your_user', password: 'your_pass';如果用运行Inspec的本地Windows账号权限就能查SQL,直接省略这俩参数就行。
  • 结果类型转换:有时候查询返回的结果可能是字符串类型,你可以加个.to_i确保是整数,比如auth_mode_result.rows.first['IsIntegratedSecurityOnly'].to_i,这样断言的时候不会因为类型不匹配失败。
  • 权限要求:运行Inspec的账号得有SQL Server的VIEW SERVER STATE权限,或者至少能执行SERVERPROPERTY函数的权限,不然会查不到结果。

备选方案:直接用Ruby ODBC连接(如果mssql_session不好使)

要是因为环境限制用不了Inspec的mssql_session,也可以直接用Ruby的ODBC gem来手动连接,代码大概是这样:

require 'odbc'

control 'mssql-integrated-auth-enforced' do
  impact 1.0
  title 'Verify MSSQL uses Integrated Authentication'
  desc 'Ensure SQL Server only allows Windows Integrated Authentication'

  # 用集成身份验证的连接字符串建立ODBC连接
  conn = ODBC.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=你的SQL服务器地址\\MSSQLSERVER;Trusted_Connection=yes;")

  # 准备并执行查询
  stmt = conn.prepare("SELECT SERVERPROPERTY('IsIntegratedSecurityOnly') AS IsIntegratedSecurityOnly;")
  stmt.execute
  result_row = stmt.fetch_hash

  # 断言结果符合预期
  describe result_row['IsIntegratedSecurityOnly'] do
    it { should eq 1 }
  end

  # 记得关闭连接哦
  stmt.close
  conn.close
end

这种方式要提前确保环境装了odbc gem,并且ODBC驱动(比如ODBC Driver 17 for SQL Server)已经正确配置好了。


内容的提问来源于stack exchange,提问作者titanjoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:47:55