1. 程式人生 > >利用PowerShell複製SQLServer賬戶的所有許可權

利用PowerShell複製SQLServer賬戶的所有許可權

#requires -version 3.0
add-type -assembly  "Microsoft.SqlServer.Smo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91";  #if Version-11.xx means sql server 2012

function Clone-SQLLogin
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true, 
                   ValueFromPipeline=$true,
                    Position=0)]
        [string[]] $ServerInstance,
 
        [Parameter(Mandatory=$true)]
        [string] $OldLogin,
 
        [Parameter(Mandatory=$true)]
        [string] $NewLogin,
 
        [string] $NewPassword="",
 
        [string] $FilePath="",
        [switch] $Execute
    )
 
    Begin
    {
        [string]$newUser=$newLogin.Substring($newLogin.IndexOf('\')+1); # if $newLogin is a Windows account, such as domain\username, since "\" is invalid in db user name, we need to remove it
 
        [hashtable[]] $hta = @(); # a hashtable array
        [hashtable] $h = @{};
  
        
        if ( ($FilePath -ne "") -and  (test-path -Path $FilePath))
        { del -Path $filepath; }
    }
    Process
    {
 
        foreach ($sqlinstance in $ServerInstance)
        {
 
           $svr = new-object "Microsoft.SqlServer.Management.Smo.Server" $sqlinstance;
           if ($svr.Edition -eq $null) 
           {
                Write-warning "$sqlinstance cannot be connected";
                continue;
            }
 
            [string]$str = "";
 
            if (-not $WindowsLogin)
            {
                $str += "create login $($newLogin) with password='$($newPassword)'; `r`n"
            }
            else
            {
                $str += "create login $($newLogin) from windows;`r`n "
            }
 
            #find role membership for $login
            if ($svr.logins[$OldLogin] -ne $null)
            { $svr.logins[$oldLogin].ListMembers() | % {$str += "exec sp_addsrvrolemember @loginame = '$($newLogin)', @rolename = '$($_)'; `r`n"};}
            else
            { Write-warning "$oldLogin does not exist on server [$($svr.name)] so this sql instance is skipped"; continue; }
 
            # find permission granted to $login
 
 
            $svr.EnumObjectPermissions($oldLogin)  | % { if ($_.PermissionState -eq 'GrantWithGrant') 
                                                                {$str += "GRANT $($_.PermissionType) on $($_.ObjectClass)::[$($_.ObjectName)] to [$newLogin] WITH GRANT OPTION; `r`n"}
                                                                else
                                                                { $str += "$($_.PermissionState) $($_.PermissionType) on $($_.ObjectClass)::[$($_.ObjectName)] to [$newLogin]; `r`n"} }
                                           
            $svr.EnumServerPermissions($oldLogin)  | % { if ($_.PermissionState -eq 'GrantWithGrant') 
                                                                { $str += "GRANT $($_.PermissionType) to [$newLogin] WITH GRANT OPTION; `r`n"}
                                                                else
                                                                { $str += "$($_.PermissionState) $($_.PermissionType) to [$newLogin]; `r`n" } }
 
            $h = @{Server=$sqlinstance; DBName = 'master'; sqlcmd = $str}; 
            $hta += $h;
            #$str;
 
 
            $ObjPerms = @(); # store login mapped users in each db on $svr
            $Roles = @();
            $DBPerms = @();
            foreach ($itm in $svr.logins[$oldLogin].EnumDatabaseMappings())
            {
                if ($svr.Databases[$itm.DBName].Status -ne 'Normal')
                { continue;}
 
                if ($svr.Databases[$itm.DBName].Users[$newUser] -eq $null)
                { $hta += @{Server=$sqlinstance; DBName = $itm.DBName; sqlcmd = "create user [$newUser] for login [$newLogin];`r`n" }; }
 
                $r = $svr.Databases[$itm.DBName].Users[$itm.UserName].EnumRoles();
                if ($r -ne $null)
                { 
                    $r | % { $hta += @{Server=$sqlinstance; DBName = $itm.DBName; sqlcmd = "exec sp_addrolemember @rolename='$_', @memberName='$($newUser)';`r`n" } }
                }
 
 
                $p = $svr.Databases[$itm.DBName].EnumDatabasePermissions($itm.UserName);
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}
 
                $p = $svr.Databases[$itm.DBName].EnumObjectPermissions($itm.UserName)
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p}; }
 
                $p = $svr.Databases[$itm.DBName].Certificates | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}
 
                #AsymmetricKeys 
                $p = $svr.Databases[$itm.DBName].AsymmetricKeys | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p}; }
 
                #SymmetricKeys 
                $p = $svr.Databases[$itm.DBName].SymmetricKeys | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}
 
                #XMLSchemaCollections
                $p = $svr.Databases[$itm.DBName].XMLSchemaCollections | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}

                #service broker components
                $p = $svr.Databases[$itm.DBName].ServiceBroker.MessageTypes | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}

                $p = $svr.Databases[$itm.DBName].ServiceBroker.Routes | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}

                $p = $svr.Databases[$itm.DBName].ServiceBroker.ServiceContracts | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}

                $p = $svr.Databases[$itm.DBName].ServiceBroker.Services | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}

                #Full text
                $p = $svr.Databases[$itm.DBName].FullTextCatalogs | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}

                $p = $svr.Databases[$itm.DBName].FullTextStopLists | % {$_.EnumObjectPermissions($itm.UserName)} 
                if ($p -ne $null)
                { $ObjPerms += @{DBName=$itm.DBName; Permission=$p};}                
            }
 
 
            #generate t-sql to apply permission using SMO only 
            #[string]$str = ([System.String]::Empty)
            foreach ($pr in $ObjPerms)
            {
   
                $h = @{Server=$sqlinstance; DBName=$($pr.DBName); sqlcmd=""};
                $str = "" #"use $($pr.DBName) `r`n"
                foreach ($p in $pr.Permission)
                {
                    [string]$op_state = $p.PermissionState;

                    if ($p.ObjectClass -ne "ObjectOrColumn")
                    {   
                        [string] $schema = "";

                        if ($p.ObjectSchema -ne $null)
                        { $schema = "$($p.ObjectSchema)."}
 
                        [string]$option = "";

                        if ($op_state -eq "GRANTwithGrant")
                        {
                            $op_state = 'GRANT';
                            $option = ' WITH GRANT OPTION';
                        }
        
       
                        Switch ($p.ObjectClass) 
                        {  
                            'Database'         { $str += "$op_state $($p.PermissionType) to [$newUser]$option;`r`n";} 
                            'SqlAssembly'      { $str += "$op_state $($p.PermissionType) ON Assembly::$($schema)$($p.ObjectName) to [$newUser]$option;`r`n";}
                            'Schema'           { $str += "$op_state $($p.PermissionType) ON SCHEMA::$($schema)$($p.ObjectName) to [$newUser]$option;`r`n";}
                            'UserDefinedType'  { $str += "$op_state $($p.PermissionType) ON TYPE::$($schema)$($p.ObjectName) to [$newUser]$option;`r`n";}
                            'AsymmetricKey'    { $str += "$op_state $($p.PermissionType) ON ASYMMETRIC KEY::$($schema)$($p.ObjectName) to [$newUser]$option;`r`n";}
                            'SymmetricKey'     { $str += "$op_state $($p.PermissionType) ON SYMMETRIC KEY::$($schema)$($p.ObjectName) to [$newUser]$option;`r`n";}
                            'Certificate'      { $str += "$op_state $($p.PermissionType) ON Certificate::$($schema)$($p.ObjectName) to [$newUser]$option`r`n";}
                            'XmlNamespace'     { $str += "$op_state $($p.PermissionType) ON XML SCHEMA COLLECTION::$($schema)$($p.ObjectName) to [$newUser]$option`r`n";}
                            'FullTextCatalog'  { $str += "$op_state $($p.PermissionType) ON FullText Catalog::$($schema)[$($p.ObjectName)] to [$newUser]$option`r`n";}
                            'FullTextStopList' { $str += "$op_state $($p.PermissionType) ON FullText Stoplist::$($schema)[$($p.ObjectName)] to [$newUser]$option`r`n";}
                            'MessageType'      { $str += "$op_state $($p.PermissionType) ON Message Type::$($schema)[$($p.ObjectName)] to [$newUser]$option`r`n";}
                            'ServiceContract'  { $str += "$op_state $($p.PermissionType) ON Contract::$($schema)[$($p.ObjectName)] to [$newUser]$option`r`n";}
                            'ServiceRoute'     { $str += "$op_state $($p.PermissionType) ON Route::$($schema)[$($p.ObjectName)] to [$newUser]$option`r`n";}
                            'Service'          { $str += "$op_state $($p.PermissionType) ON Service::$($schema)[$($p.ObjectName)] to [$newUser]$option`r`n";}
                        #you can add other stuff like Available Group etc in this switch block as well
                        }#switch
      
                    }
                    else
                    {  
                        [string]$col = "" #if grant is on column level, we need to capture it
                        if ($p.ColumnName -ne $null)
                        { $col = "($($p.ColumnName))"};
 
                        $str += "$op_state $($p.PermissionType) ON Object::$($p.ObjectSchema).$($p.ObjectName) $col to [$newUser];`r`n";
                    }#else
   
                }
                #$str += "go`r`n";
                $h.sqlcmd = $str;
                $hta += $h;
            }
 
 
        }#loop $ServerInstance
    } #process block
    End
    {
           [string] $sqlcmd = "";
            
           if ($FilePath.Length -gt 3) # $FilePath is provided
           {
                [string]$servername="";
 
                foreach ($h in $hta)
                {
                   if ($h.Server -ne $Servername)
                   { 
                     $ServerName=$h.Server;
                     $sqlcmd += ":connect $servername `r`n" 
                    }
                    
                    $sqlcmd += "use $($h.DBName);`r`n" + $h.sqlcmd +"`r`ngo`r`n"; 
                     
                 }
                 $sqlcmd | out-file -FilePath $FilePath -Append ;   
            }
 
            if ($Execute)
            {
                foreach ($h in $hta)
                {
                    $server = new-object "Microsoft.sqlserver.management.smo.server" $h.Server;
                    $database = $server.databases[$h.DBName];
                    $database.ExecuteNonQuery($h.sqlcmd)
                }
            } #$Execute
 
    }#end block
} #clone-sqllogin 

# test, change parameters to your own. The following creates a script about all permissions assigned to [Bobby] 
# Clone-SQLLogin -Server "$env:ComputerName", "$env:ComputerName\sql2014" -OldLogin Bobby -NewLogin Bobby -FilePath "c:\temp\Bobby_perm.sql";

相關推薦

利用PowerShell複製SQLServer賬戶所有許可權

#requires -version 3.0 add-type -assembly "Microsoft.SqlServer.Smo, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"; #if Version-11.

SQLSERVER列出所有使用者許可權

--伺服器級許可權WITH CTE AS(SELECT u.name AS 使用者名稱,u.is_disabled AS 是否禁用,g.name as 伺服器角色,'√' as 'flag'FROM sys.server_principals uINNER JOIN sys.server_role_membe

利用Powershell 腳本和定時任務自動批量開郵箱

roc remote c99 rec 執行 shell pro napi module 首先確保powershell 執行策略 PS C:\Users\administrator.51TALK> Set-ExecutionPolicy -ExecutionPolic

利用Powershell每天自動設定提取Win10的windows聚焦圖片(Spotlight)作為桌面桌布的方法

微軟在 Windows 10 上新增了一項功能 Windows 聚焦 (Windows Spotlight),它會自動隨機下載並更換鎖屏介面的桌布 (Lockscreen),讓你每次開啟電腦都有不一樣的視覺享受。這些高清鎖屏桌布往往都很精美,很多視覺衝擊力十足,非常值得收藏。但很多同學想將這些桌

獲取管理員的所有許可權--帶圖示.reg

檔名:獲取管理員的所有許可權--帶圖示.reg Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\runas] [HKEY_CLASSES_ROOT\*\shell\runas] @="獲取超級管理員的所有許可權"

給予使用者所有許可權

1)進入超級使用者模式。也就是輸入"su -",系統會讓你輸入超級使用者密碼,輸入密碼後就進入了超級使用者模式。(當然,你也可以直接用root用)  2)新增檔案的寫許可權。也就是輸入命令"chmod u+w /etc/sudoers"。  3)編輯/etc/sudoers檔案。

sqlserver 獲取所有表的欄位型別等資訊

USE [MultipleAnalysisDataFY] GO /****** Object: View [dbo].[selectfieldtype] Script Date: 2018/11/7 星期三 12:02:27 ******/ SET ANSI_NULLS ON GO SET

《必然》四、不可複製性決定所有價值

今天我們說《必然》的第三個關鍵詞,流動 Flowing 。 KK 大叔認為,今天的世間萬物都將以流動的形式出現。我們現在獲取資訊的方式,已經不在是一張一張的報紙,或者是單純的一個又一個的頁面,而是一種流。這很好理解,比如說當你刷微博、微信、還有瀏覽各種網頁的時候。裡面的所有文字、所

Python實現:某個使用者登入後,檢視自己擁有所有許可權

許可權管理                許可權表:         

mysql建立使用者並設定所有許可權

mysql建立使用者並設定所有許可權1、建立使用者:CREATE USER 'username'@'host' IDENTIFIED BY 'password';username:使用者名稱; host:指定在哪個主機上可以登入,本機可用localhost,%通配所有遠端主機; password

利用反射列印物件的所有屬性及呼叫物件方法

利用java反射輸出物件的所有屬性,呼叫物件的方法 public class ClassUtil { private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class); public s

Android 開發所有許可權解析

訪問登記屬性 android.permission.ACCESS_CHECKIN_PROPERTIES ,讀取或寫入登記check-in資料庫屬性表的許可權 獲取錯略位置 android.permission.ACCESS

利用Navicate把SQLServer轉MYSQL的方法(連資料)

本次轉換需要依賴使用工具Navicat Premium。     首先,將資料庫移至本地SQLServer,我試過直接在區域網上其他SQLServer伺服器上想轉到本地Mysql好像有問題,想將遠端資料庫備份恢復到本地。   1、開啟Navicat Premium,新建一個同名的資料庫,然後在表上點選“匯

MFC獲取SqlServer資料庫所有表、欄位名、記錄資料

程式碼如下過程其實不是每一步都有,但是主要功能都在! //1、連線資料庫類 BOOL CSqlDlg::Ado(CString strConn) { ::CoInitialize(NULL); // 初始化OLE/COM庫環境 try { m_pConn.CreateInstan

利用PowerShell監控Win-Server效能

USE [TestDB] GO /*系統性能監控:CPU、記憶體、disk*/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER proc M_cpumem --手動獲取資料庫伺服器IP @ip nvarchar(20) AS

利用IIS6提權獲得管理員許可權

IIS6也是一個比較古老的提權EXP了,是通過利用WMI的許可權來執行命令。 目標機:漏洞巨多的Win2003 下面說一下通過IIS6在已用菜刀連線上的伺服器上運用IIS6獲得管理員許可權的過程。 1.將cmd和IIS6上傳到已用菜刀控制的伺服器上。 2.用cmd開啟虛擬終

linux上 mysql建立某個使用者只對某個庫有所有許可權

mysql建立某個使用者只對某個庫有所有許可權 grant ALL on  庫名稱.*  to  '使用者名稱'@'允許登入的ip'  IDENTIFIED  BY  '密碼';flush  privileges; (庫名稱.

一次性動態獲取所有許可權

簡介 介紹一種一次性檢測並獲取所有動態許可權的方法 動態獲取許可權 private void requestPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

Android6.0許可權組 動態申請所有許可權詳細介紹

同一組的任何一個許可權被授權了,其他許可權也自動被授權。例如,一旦WRITE_CONTACTS被授權了,app也有READ_CONTACTS和GET_ACCOUNTS了。1、需要手動申請的許可權:Permission GroupPermissionsandroid.permi

利用glassfish4任意檔案讀取拿許可權的一些思路

只要討論的是linux環境測試發現只針對GlassFish4,且基本上是已root執行的http://www.wooyun.org/bugs/wooyun-2010-0144595 zoomeye dorkGlassFish Server Open Source Edition 4.1 放張圖 nosec