Powershell에서 폴더의 소유권을 얻고 도메인 계정에 전체 권한을 추가하시겠습니까?

Powershell에서 폴더의 소유권을 얻고 도메인 계정에 전체 권한을 추가하시겠습니까?

이 작업의 일부를 수행하는 Powershell 기능이 있지만 소유권을 가져오고 권한을 추가하는 데 도메인 계정을 사용하지 않고 로컬 관리자를 사용합니다. Powershell에서 이 작업을 수행하는 더 좋은 방법이 있습니까?

<#

.SYNOPSIS
    Take ownership of a folder giving the ownership to ourdomain\myuser

.DESCRIPTION
    Takes ownership of a file the way my boss said to do when deleting a user's home directory.
    Using the GUI:
    1. Right click the folder and select properties.
    2. Click the "Security" tab.
    3. Click the "Advanced" button.
    4. Next to the "Owner:" label, click "Change"
    5. Enter ourdomain\myuser
    6. Click OK, OK, OK
    7. Right click the folder and select properties.
    8. Click the "Security" tab.
    9. Click the "Advanced" button.
    10. Click "Add"
    11. Next to "Principal:" click "Select a principal"
    12. Enter ourdomain\myuser
    13. Click OK
    14. Check "Full control"
    15. Click OK, OK, OK
    16. You should now be able to manipulate or delete the folder.
.NOTES
    File Name : Microsoft.PowerShell_profile.ps1
.EXAMPLE
    Take-Ownership R:\Redirected\Users\<username>
#>
function Take-Ownership {
   param(
     [String]$Folder
   )

   # Take ownership of the folder...  
   # (though I'd prefer if I could specify a user or group instead) 
   takeown.exe /A /F $Folder

   # Obtain the current ACL for this folder.
   $CurrentACL = Get-Acl $Folder

   # Add FullControl permissions to the ACL for the user.
   Write-Host ...Adding ourdomain\myuser to $Folder -Fore Yellow
   $SystemACLPermission = "ourdomain\myuser","FullControl","ContainerInherit,ObjectInherit","None","Allow"
   $SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $SystemACLPermission
   $CurrentACL.AddAccessRule($SystemAccessRule)

   #Write-Host ...Adding Infrastructure Services to $Folder -Fore Yellow
   #$AdminACLPermission = "ourdomain\myuser","FullControl","ContainerInherit,ObjectInherit"."None","Allow"
   #$SystemAccessRule = new-object System.Security.AccessControl.FilesystemAccessRule $AdminACLPermission
   #$CurrentACL.AddAccessRule($SystemAccessRule)

   # Set the ACL again.
   Set-Acl -Path $Folder -AclObject $CurrentACL
}

답변1

개체 소유자를 관리자 그룹으로 설정하는 경우 로컬 관리자여야 합니다. 그렇지 않으면 할당량 계산은 파일 소유권을 기반으로 하고 할당량은 관리자에게 영향을 주지 않기 때문에 사람들은 디스크 할당량을 사소하게 우회할 수 있습니다.

관리자로 스크립트를 실행하는 경우 약간의 조작 후에 개체 소유자를 보안 주체로 설정할 수 있습니다. 너는 필요할거야이 권한 조정 스크립트추가 공백을 제거하고 한 세션에서 여러 번 실행될 수 있도록 약간 편집한 Lee Holmes의 글입니다.

param(    ## The privilege to adjust. This set is taken from
    ## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
    [ValidateSet(
        "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
        "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
        "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
        "SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
        "SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
        "SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
        "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
        "SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
        "SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
        "SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
        "SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
    $Privilege,
    ## The process on which to adjust the privilege. Defaults to the current process.
    $ProcessId = $pid,
    ## Switch to disable the privilege, rather than enable it.
    [Switch] $Disable
)

## Taken from P/Invoke.NET with minor adjustments.
$definition = @'
using System;
using System.Runtime.InteropServices;
public class AdjPriv
{

    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
    ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
    internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

    [DllImport("advapi32.dll", SetLastError = true)]
    internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

    [StructLayout(LayoutKind.Sequential, Pack = 1)]

    internal struct TokPriv1Luid
    {
        public int Count;
        public long Luid;
        public int Attr;
    }

    internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
    internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
    internal const int TOKEN_QUERY = 0x00000008;
    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;

    public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
    {
        bool retVal;
        TokPriv1Luid tp;
        IntPtr hproc = new IntPtr(processHandle);
        IntPtr htok = IntPtr.Zero;
        retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
        tp.Count = 1;
        tp.Luid = 0;

        if(disable)
        {
            tp.Attr = SE_PRIVILEGE_DISABLED;
        }
        else
        {
            tp.Attr = SE_PRIVILEGE_ENABLED;
        }

        retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
        retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
        return retVal;
    }
}

'@

$processHandle = (Get-Process -id $ProcessId).Handle
try { 
  Add-Type $definition 
} catch {} # Silent failure on re-registration

[AdjPriv]::EnablePrivilege($processHandle, $Privilege, $Disable)

으로 저장했습니다 privs.ps1. 그런 다음 전화 .\privs.ps1 SeRestorePrivilege하여 프로세스를 활성화 SeRestorePrivilege하면 원하는 사람에게 파일 소유권을 설정할 수 있습니다.

그런 다음 호출 대신 takeown이미 가지고 있는 ACL 개체를 사용할 수 있습니다.

$ownerPrincipal = New-Object System.Security.Principal.NTAccount($newOwnerName)
$CurrentACL.SetOwner($ownerPrincipal)

새 ACL이 적용되는 동시에 새 소유자가 설정됩니다.

마지막으로 추가 권한을 비활성화할 수 있습니다.

.\privs.ps1 SeRestorePrivilege -Disable

관련 정보