简体   繁体   English

如何使用.NET应用Windows组策略?

[英]How to apply Windows group policy using .NET?

Is it possible to apply (and remove) Windows group policy settings using .NET? 是否可以使用.NET应用(和删除)Windows组策略设置?

I am working on an application that needs to temporarily put a machine into a restricted, kiosk-like state. 我正在开发一个应用程序,需要暂时将机器置于受限制的,类似于kiosk的状态。 One of the things I need to control is access to USB drives which I believe I can do through group policy. 我需要控制的一件事是访问USB驱动器,我相信我可以通过组策略来实现。 I'd like my app to set the policy when it starts and revert the change when it exits... is this something I can do through .NET framework calls? 我希望我的应用程序在启动时设置策略并在退出时还原更改...这是我可以通过.NET框架调用做的事情吗?

These are my primary requirements: 这些是我的主要要求:

  • Apply group policy settings when my console app is started. 启动控制台应用程序时应用组策略设置。
  • Identify when a user action is denied by the policy and log it. 确定策略拒绝用户操作的时间并记录它。
    • Logging to the system security log is acceptable. 登录系统安全日志是可以接受的。
  • Revert my policy changes when my app stops. 当我的应用停止时,还原我的政策更改。

Try using IGroupPolicyObject 尝试使用IGroupPolicyObject

bool SetGroupPolicy(HKEY hKey, LPCTSTR subKey, LPCTSTR valueName, DWORD dwType, const BYTE* szkeyValue, DWORD dwkeyValue)
{
    CoInitialize(NULL);
    HKEY ghKey, ghSubKey, hSubKey;
    LPDWORD flag = NULL;
    IGroupPolicyObject *pGPO = NULL;
    HRESULT hr = CoCreateInstance(CLSID_GroupPolicyObject, NULL, CLSCTX_ALL, IID_IGroupPolicyObject, (LPVOID*)&pGPO);

    if(!SUCCEEDED(hr))
    {
        MessageBox(NULL, L"Failed to initialize GPO", L"", S_OK);
    }

    if (RegCreateKeyEx(hKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hSubKey, flag) != ERROR_SUCCESS)
    {
        return false;
        CoUninitialize();
    }

    if(dwType == REG_SZ)
    {
        if(RegSetValueEx(hSubKey, valueName, 0, dwType, szkeyValue, strlen((char*)szkeyValue) + 1) != ERROR_SUCCESS)
        {
            RegCloseKey(hSubKey);
            CoUninitialize();
            return false;
        }
    }

    else if(dwType == REG_DWORD)
    {
        if(RegSetValueEx(hSubKey, valueName, 0, dwType, (BYTE*)&dwkeyValue, sizeof(dwkeyValue)) != ERROR_SUCCESS)
        {
            RegCloseKey(hSubKey);
            CoUninitialize();
            return false;
        }
    }

    if(!SUCCEEDED(hr))
    {
        MessageBox(NULL, L"Failed to initialize GPO", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(pGPO->OpenLocalMachineGPO(GPO_OPEN_LOAD_REGISTRY) != S_OK)
    {
        MessageBox(NULL, L"Failed to get the GPO mapping", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(pGPO->GetRegistryKey(GPO_SECTION_USER,&ghKey) != S_OK)
    {
        MessageBox(NULL, L"Failed to get the root key", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(RegCreateKeyEx(ghKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &ghSubKey, flag) != ERROR_SUCCESS)
    {
        RegCloseKey(ghKey);
        MessageBox(NULL, L"Cannot create key", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(dwType == REG_SZ)
    {
        if(RegSetValueEx(ghSubKey, valueName, 0, dwType, szkeyValue, strlen((char*)szkeyValue) + 1) != ERROR_SUCCESS)
        {
            RegCloseKey(ghKey);
            RegCloseKey(ghSubKey);
            MessageBox(NULL, L"Cannot create sub key", L"", S_OK);
            CoUninitialize();
            return false;
        }
    }

    else if(dwType == REG_DWORD)
    {
        if(RegSetValueEx(ghSubKey, valueName, 0, dwType, (BYTE*)&dwkeyValue, sizeof(dwkeyValue)) != ERROR_SUCCESS)
        {
            RegCloseKey(ghKey);
            RegCloseKey(ghSubKey);
            MessageBox(NULL, L"Cannot set value", L"", S_OK);
            CoUninitialize();
            return false;
        }
    }

    if(pGPO->Save(false, true, const_cast<GUID*>(&EXTENSION_GUID), const_cast<GUID*>(&CLSID_GPESnapIn)) != S_OK)
    {
        RegCloseKey(ghKey);
        RegCloseKey(ghSubKey);
        MessageBox(NULL, L"Save failed", L"", S_OK);
        CoUninitialize();
        return false;
    }

    pGPO->Release();
    RegCloseKey(ghKey);
    RegCloseKey(ghSubKey);
    CoUninitialize();
    return true;
}

You can call this function like this.. 你可以像这样调用这个函数..

// Remove the Log Off in start menu
SetGroupPolicy(HKEY_CURRENT_USER,
    L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
    L"StartMenuLogOff", REG_DWORD, NULL, 1);

NOTE: I use two GroupPolicy assembly references: C:\\Windows\\assembly\\GAC_MSIL\\Microsoft.GroupPolicy.Management\\2.0.0.0__31bf3856ad364e35\\Microsoft.GroupPolicy.Management.dll and C:\\Windows\\assembly\\GAC_32\\Microsoft.GroupPolicy.Management.Interop\\2.0.0.0__31bf3856ad364e35\\Microsoft.GroupPolicy.Management.Interop.dll This framework 2.0, so there are mixed code, and you must use app.config: http://msmvps.com/blogs/rfennell/archive/2010/03/27/mixed-mode-assembly-is-built-against-version-v2-0-50727-error-using-net-4-development-web-server.aspx 注意:我使用两个GroupPolicy程序集引用:C:\\ Windows \\ assembly \\ GAC_MSIL \\ Microsoft.GroupPolicy.Management \\ 2.0.0.0__31bf3856ad364e35 \\ Microsoft.GroupPolicy.Management.dll和C:\\ Windows \\ assembly \\ GAC_32 \\ Microsoft.GroupPolicy。 Management.Interop \\ 2.0.0.0__31bf3856ad364e35 \\ Microsoft.GroupPolicy.Management.Interop.dll这个框架2.0,所以有混合代码,你必须使用app.config: http//msmvps.com/blogs/rfennell/archive/ 2010/3月27日/混合模式具组件的内置,对版本,使用网-4-发展v2-0-50727 -错误-网络server.aspx

I made it like that. 我就这样做了。

using System.Collections.ObjectModel;
using Microsoft.GroupPolicy;
using Microsoft.Win32;

/// <summary>
/// Change user's registry policy
/// </summary>
/// <param name="gpoName">The name of Group Policy Object(DisplayName)</param>
/// <param name="keyPath">Is KeyPath(like string path=@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")</param>
/// <param name="typeOfKey">DWord, ExpandString,... e.t.c </param>
/// <param name="parameterName">Name of parameter</param>
/// <param name="value">Value</param>
/// <returns>result: true\false</returns>
public bool ChangePolicyUser(string gpoName, string keyPath, RegistryValueKind typeOfKey, string parameterName, object value)
    {
        try
        {
            RegistrySetting newSetting = new PolicyRegistrySetting();
            newSetting.Hive = RegistryHive.CurrentUser;
            newSetting.KeyPath = keyPath;
            bool contains = false;
            //newSetting.SetValue(parameterName, value, typeOfKey);
            switch (typeOfKey)
            {
                case RegistryValueKind.String:
                    newSetting.SetValue(parameterName, (string)value, typeOfKey);
                    break;
                case RegistryValueKind.ExpandString:
                    newSetting.SetValue(parameterName, (string)value, typeOfKey);
                    break;
                case RegistryValueKind.DWord:
                    newSetting.SetValue(parameterName, (Int32)value);
                    break;
                case RegistryValueKind.QWord:
                    newSetting.SetValue(parameterName, (Int64)value);
                    break;
                case RegistryValueKind.Binary:
                    newSetting.SetValue(parameterName, (byte[])value);
                    break;
                case RegistryValueKind.MultiString:
                    newSetting.SetValue(parameterName, (string[])value, typeOfKey);
                    break;
            }
            Gpo gpoTarget = _gpDomain.GetGpo(gpoName);
            RegistryPolicy registry = gpoTarget.User.Policy.GetRegistry(false);
            try
            {
                ReadOnlyCollection<RegistryItem> items = gpoTarget.User.Policy.GetRegistry(false).Read(newSetting.Hive, keyPath);
                foreach (RegistryItem item in items)
                {
                    if (((RegistrySetting) item).ValueName == parameterName)
                    {
                        contains = true;
                    }
                }
                registry.Write((PolicyRegistrySetting) newSetting, !contains);
                registry.Save(false);
                return true;
            }
            catch (ArgumentException)
            {
                registry.Write((PolicyRegistrySetting)newSetting, contains);
                registry.Save(true);
                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

Check out www.sdmsoftware.com/group_policy_scripting. 查看www.sdmsoftware.com/group_policy_scripting。 Its not free but will do exactly what you're after. 它不是免费的,但会完全按照你的要求行事。

I haven't played with it myself, but System.Security.Policy looks like it might be an interesting starting-point. 我自己没有玩过它,但System.Security.Policy看起来可能是一个有趣的起点。

Re-posted link as requested: Group Policy access via Registry 根据要求重新发布链接: 通过注册表访问组策略

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

相关问题 如何使用c ++配置Windows组策略? - How to configure Windows Group Policy using c++? 如何在C#中以编程方式更改Windows 8.1组策略? - How to change Windows 8.1 Group Policy programmatically in c#? .NET组策略\\机器文件夹 - .NET Group Policy\Machine folder 如何使用.NET更改本地安全策略 - How to Change Local Security Policy using .NET 如何使用c#.net,windowsce,.net3.5框架,Windows Mobile 6 Professional将滚动条应用于Windows Mobile应用程序 - How to apply scrollbar to windows mobile application using c#.net, windowsce, .net3.5 framework, windows mobile 6 professional 如何使用 C# 通过组策略检查 PowerShell 禁用 - How to check PowerShell disable by group policy using C# 如何使用MongoDb将一个分组应用于另一个分组的结果? - How can apply a group by to a result of another group by using MongoDb? 如何使用 c# 配置密码策略(组策略) - How can I configure Password Policy(Group Policy) using c# 以编程方式更改 Windows 10 壁纸(限制使用“组策略中的活动桌面壁纸”) - Change Windows 10 wallpaper programmatically (Restricted using 'Active Desktop Wallpaper in Group Policy') 如何在SQL中应用分组 - How to apply group by in sql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM