簡體   English   中英

將所有用戶限制為1個會話

[英]limit all users to 1 session

我被要求將SQL Server配置為每次登錄只允許一個會話。 我已經找到了一些關於創建登錄觸發器的引用,以防止登錄建立多個會話,但我想知道是否有某種方法可以在較低級別定義它,所以這個會話限制是默認的,而不是而不是必須在每個用戶的另一個登錄中定義它?

我在stackoverflow上的“可能已經有你的答案的問題”和“類似的問題”中看到了很多關於這個主題的引用,但到目前為止還沒有找到或者沒有理解描述我想要做什么的帖子。 我還看到了一個關於聲明式管理框架的參考資料,它允許您按照我認為的策略配置SQL Server。

我將繼續在這里查看文章以嘗試學習這一點,但在此期間......非常感謝建議!

聯機叢書中登錄觸發器的示例與我認為您想要的非常接近,我做了一些更改,使其適用於所有登錄。

-- Trigger must be created by a user with 'view server state' permission in order the trigger to have unrestricted access to sys.dm_exec_sessions.
create trigger connection_limit_trigger on all server with execute as self for logon
as
begin
    -- Check whether the caller is a SysAdmin.
    -- Note: The trigger is executing under an elevated security context so we must switch to the caller's context to test their SysAdmin status.
    declare @IsSysAdmin int
    execute as caller
    set @IsSysAdmin = isnull(is_srvrolemember ('sysadmin'), 0)
    revert

    -- If the user is not a SysAdmin and there are already too many non-dormant sessions for this login then 'rollback' the logon.
    -- Note: sys.dm_exec_sessions does not include an entry for this logon attempt.
    if ((@IsSysAdmin = 0) and ((select count(1) from sys.dm_exec_sessions where is_user_process = 1 and status <> 'Dormant' and original_login_name = original_login()) > 1))
    begin
        raiserror('This login has exceeded the maximum of 1 connections to this SQL Server.', 16, 1)
        rollback
    end
end

我添加了一個檢查,因此該限制不適用於SysAdmin登錄,也不計算休眠連接池連接。 有幾點需要注意;

  • 如果連接沒有正確關閉,它可以在sys.dm_exec_sessions中暫停一段時間,在這種情況下,用戶將無法重新連接,直到死連接自行清除。
  • 如果你弄亂了登錄觸發器,你可以將自己(以及其他所有人!)鎖定在SQL Server之外。 有關如何返回的詳細信息,請參閱登錄觸發器頁面:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM