简体   繁体   English

如何通过powershell给本地用户账号分配用户权限?

[英]How to assign user rights to a local user account through powershell?

I want to modify the user rights associated with a local user account.I want to add groups and users to a particular User Rights.我想修改与本地用户帐户关联的用户权限。我想将组和用户添加到特定用户权限。 This is done by opening the group policy and opening the following folder in the console tree: Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment.这是通过打开组策略并在控制台树中打开以下文件夹来完成的:计算机配置\Windows 设置\安全设置\本地策略\用户权限分配。 Then click on the required user Right and add the user or group to it.然后点击需要的用户权限,将用户或组添加进去。

Is it possible to do the same through powershell scripts?是否可以通过 powershell 脚本执行相同的操作?

What I would do is open SecPol.msc, make your modifications via the GUI to a baseline computer and export an .inf template for installation via powershell. 我要做的是打开SecPol.msc,通过GUI对基线计算机进行修改,并通过PowerShell导出.inf模板进行安装。

The template can be installed with secedit.exe. 可以使用secedit.exe安装该模板。 If you want, you can open the inf file in a text editor and scroll until you see the [Privilege Rights] section. 如果需要,可以在文本编辑器中打开inf文件并滚动,直到看到[Privilege Rights]部分。 Here is one for example. 这是一个例子。

[Privilege Rights]
SeDenyServiceLogonRight = *S-1-1-0,*S-1-5-19, KNUCKLE-DRAGGER

Run this command and reboot. 运行此命令并重新启动。 Edit .inf and .db names as appropriate. 根据需要编辑.inf和.db名称。

    secedit.exe /configure /cfg C:\customsettings.inf /db C:\WINDOWS\security\Database\customsettings.db /quiet

Found a third party command line solution. 找到第三方命令行解决方案。 ntwrongs.exe ntwrongs.exe

http://forums.mydigitallife.info/threads/57557-NTWrongs%99 http://forums.mydigitallife.info/threads/57557-NTWrongs%99

# Grant
.\NTWRONGS.exe -ID "Administrator" -Privilege "SeDenyServiceLogonRight"
# Revoke
.\NTWRONGS.exe -ID "Administrator" -Privilege "SeDenyServiceLogonRight" -Revoke

在此输入图像描述

Here is a purely powershell method - https://stackoverflow.com/a/26393118 这是一个纯粹的PowerShell方法 - https://stackoverflow.com/a/26393118

Add-Type @'
using System;
using System.Collections.Generic;
using System.Text;

namespace LSA
{
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Management;
    using System.Runtime.CompilerServices;
    using System.ComponentModel;

    using LSA_HANDLE = IntPtr;

    [StructLayout(LayoutKind.Sequential)]
    struct LSA_OBJECT_ATTRIBUTES
    {
        internal int Length;
        internal IntPtr RootDirectory;
        internal IntPtr ObjectName;
        internal int Attributes;
        internal IntPtr SecurityDescriptor;
        internal IntPtr SecurityQualityOfService;
    }
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct LSA_UNICODE_STRING
    {
        internal ushort Length;
        internal ushort MaximumLength;
        [MarshalAs(UnmanagedType.LPWStr)]
        internal string Buffer;
    }
    sealed class Win32Sec
    {
        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaOpenPolicy(
        LSA_UNICODE_STRING[] SystemName,
        ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
        int AccessMask,
        out IntPtr PolicyHandle
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern uint LsaAddAccountRights(
        LSA_HANDLE PolicyHandle,
        IntPtr pSID,
        LSA_UNICODE_STRING[] UserRights,
        int CountOfRights
        );

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        internal static extern int LsaLookupNames2(
        LSA_HANDLE PolicyHandle,
        uint Flags,
        uint Count,
        LSA_UNICODE_STRING[] Names,
        ref IntPtr ReferencedDomains,
        ref IntPtr Sids
        );

        [DllImport("advapi32")]
        internal static extern int LsaNtStatusToWinError(int NTSTATUS);

        [DllImport("advapi32")]
        internal static extern int LsaClose(IntPtr PolicyHandle);

        [DllImport("advapi32")]
        internal static extern int LsaFreeMemory(IntPtr Buffer);

    }
    /// <summary>
    /// This class is used to grant "Log on as a service", "Log on as a batchjob", "Log on localy" etc.
    /// to a user.
    /// </summary>
    public sealed class LsaWrapper : IDisposable
    {
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_TRUST_INFORMATION
        {
            internal LSA_UNICODE_STRING Name;
            internal IntPtr Sid;
        }
        [StructLayout(LayoutKind.Sequential)]
        struct LSA_TRANSLATED_SID2
        {
            internal SidNameUse Use;
            internal IntPtr Sid;
            internal int DomainIndex;
            uint Flags;
        }

        [StructLayout(LayoutKind.Sequential)]
        struct LSA_REFERENCED_DOMAIN_LIST
        {
            internal uint Entries;
            internal LSA_TRUST_INFORMATION Domains;
        }

        enum SidNameUse : int
        {
            User = 1,
            Group = 2,
            Domain = 3,
            Alias = 4,
            KnownGroup = 5,
            DeletedAccount = 6,
            Invalid = 7,
            Unknown = 8,
            Computer = 9
        }

        enum Access : int
        {
            POLICY_READ = 0x20006,
            POLICY_ALL_ACCESS = 0x00F0FFF,
            POLICY_EXECUTE = 0X20801,
            POLICY_WRITE = 0X207F8
        }
        const uint STATUS_ACCESS_DENIED = 0xc0000022;
        const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
        const uint STATUS_NO_MEMORY = 0xc0000017;

        IntPtr lsaHandle;

        public LsaWrapper()
            : this(null)
        { }
        // // local system if systemName is null
        public LsaWrapper(string systemName)
        {
            LSA_OBJECT_ATTRIBUTES lsaAttr;
            lsaAttr.RootDirectory = IntPtr.Zero;
            lsaAttr.ObjectName = IntPtr.Zero;
            lsaAttr.Attributes = 0;
            lsaAttr.SecurityDescriptor = IntPtr.Zero;
            lsaAttr.SecurityQualityOfService = IntPtr.Zero;
            lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
            lsaHandle = IntPtr.Zero;
            LSA_UNICODE_STRING[] system = null;
            if (systemName != null)
            {
                system = new LSA_UNICODE_STRING[1];
                system[0] = InitLsaString(systemName);
            }

            uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
            (int)Access.POLICY_ALL_ACCESS, out lsaHandle);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void AddPrivileges(string account, string privilege)
        {
            IntPtr pSid = GetSIDInformation(account);
            LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
            privileges[0] = InitLsaString(privilege);
            uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
        }

        public void Dispose()
        {
            if (lsaHandle != IntPtr.Zero)
            {
                Win32Sec.LsaClose(lsaHandle);
                lsaHandle = IntPtr.Zero;
            }
            GC.SuppressFinalize(this);
        }
        ~LsaWrapper()
        {
            Dispose();
        }
        // helper functions

        IntPtr GetSIDInformation(string account)
        {
            LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
            LSA_TRANSLATED_SID2 lts;
            IntPtr tsids = IntPtr.Zero;
            IntPtr tdom = IntPtr.Zero;
            names[0] = InitLsaString(account);
            lts.Sid = IntPtr.Zero;
            Console.WriteLine("String account: {0}", names[0].Length);
            int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids);
            if (ret != 0)
                throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret));
            lts = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(tsids,
            typeof(LSA_TRANSLATED_SID2));
            Win32Sec.LsaFreeMemory(tsids);
            Win32Sec.LsaFreeMemory(tdom);
            return lts.Sid;
        }

        static LSA_UNICODE_STRING InitLsaString(string s)
        {
            // Unicode strings max. 32KB
            if (s.Length > 0x7ffe)
                throw new ArgumentException("String too long");
            LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
            lus.Buffer = s;
            lus.Length = (ushort)(s.Length * sizeof(char));
            lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
            return lus;
        }
    }
    public class Editor
    {
        public static void AddPrivileges(string account, string privilege)
        {
            using (LsaWrapper lsaWrapper = new LsaWrapper())
            {
                lsaWrapper.AddPrivileges(account, privilege);
            }
        }
    }
}
'@

[LSA.Editor]::AddPrivileges("KNUCKLE-DRAGGER", "SeBatchLogonRight")
secpol.msc

To build upon @Knuckle-Dragger's answer:以@Knuckle-Dragger 的回答为基础:

I couldn't add my user to the secreatesymboliclinkprivilege setting ( Computer Configuration > Windows Settings > Security Settings > Local Policies > ** User Rights Assignment** > Create symbolic links ), always with the error "The specified domain either does not exist or could not be contacted", and it worked with his method, for my DOMAIN\user account from the whoami output:我无法将我的用户添加到secreatesymboliclinkprivilege设置(计算机配置> Windows 设置>安全设置>本地策略> ** 用户权限分配** >创建符号链接),总是出现错误“指定的域不存在或无法联系”,并且它适用于他的方法,用于我来自whoami output 的DOMAIN\user帐户:

SecEdit.exe /export /db C:\WINDOWS\security\Database\secedit.sdb /cfg config
# edited the file, added just ',DOMAIN\user' to this line:
# secreatesymboliclinkprivilege = *S-1-5-83-0,*S-1-5-32-544,DOMAIN\user
SecEdit.exe /configure /db secedit.sdb /cfg config

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用远程PowerShell创建本地Windows用户帐户? - How to create a local windows user account using remote powershell? 如何获取Windows用户帐户的用户权限和权限 - How to get user rights AND privileges of a Windows User account Powershell:导出用户权限分配 - Powershell: Export User Rights Assignment 如何在 Windows 上以本地用户身份安装 NodeJS LTS(没有管理员权限) - How to install NodeJS LTS on Windows as a local user (without admin rights) Powershell 检查用户是否是本地用户,并且在本地 windows 机器上具有用户名和密码的管理员权限(非活动目录) - Powershell check if user is local-user and have admin rights from username and password on local windows machine (Not active directory) Windows使用管理员Powershell的本地用户帐户运行脚本 - windows run script with local user account from administrator powershell 使用 Powershell 创建的本地用户帐户未显示在设置“家庭和其他人”中 - Local user account created with Powershell is NOT shown in settings "Family & Other people" 创建本地用户帐户 - create local user account 如何在Windows中为新用户帐户生成本地用户配置文件? - How to generate a local user profile for a new user account in Windows? 有没有办法使用普通用户权限在 Edge unsing Powershell 中启用收藏夹链接栏? - Is there a way to enable the favorites linkbar in Edge unsing Powershell with normal user rights?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM