.NET을 사용하여 Windows 그룹 정책을 적용하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/2266797

  •  20-09-2019
  •  | 
  •  

문제

.NET을 사용하여 Windows 그룹 정책 설정을 적용하고 제거 할 수 있습니까?

필요한 응용 프로그램 작업을하고 있습니다 일시적으로 기계를 제한된 키오스크와 같은 상태에 넣습니다. 내가 통제 해야하는 것 중 하나는 그룹 정책을 통해 할 수 있다고 생각하는 USB 드라이브에 액세스하는 것입니다. 내 앱이 시작될 때 정책을 설정하고 종료 할 때 변경 사항을 되돌릴 수 있기를 바랍니다. 이것이 .NET 프레임 워크 호출을 통해 수행 할 수있는 일입니까?

이것이 나의 주요 요구 사항입니다.

  • 콘솔 앱이 시작될 때 그룹 정책 설정을 적용하십시오.
  • 정책에 의해 사용자 조치가 거부되는시기를 식별하고 로그인하십시오.
    • 시스템 보안 로그에 로깅이 허용됩니다.
  • 내 앱이 중지되면 정책 변경을 되돌립니다.
도움이 되었습니까?

해결책

사용해보십시오 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;
}

이 기능을 이렇게 부를 수 있습니다 ..

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

다른 팁

참고 : 두 개의 GroupPolicy Assembly 참조를 사용합니다. management.interop 2.0.0.0__31BF3856AD364E35 Microsoft.groupPolicy.management.interop.dll이 프레임 워크 2.0이므로 혼합 코드가 있으므로 App.Config를 사용해야합니다. http://msmvps.com/blogs/rfennell/archive/2010/03/27/mixed-mode-assembly-is-built-against-version-v2-0-50727-using-using-4- 개발- web-server.aspx

나는 그것을 그렇게 만들었다.

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;
        }
    }

www.sdmsoftware.com/group_policy_scripting을 확인하십시오. 그것은 무료가 아니지만 당신이 따르는 것을 정확히 할 것입니다.

나는 직접 놀지 않았지만 System.security.policy는 흥미로운 출발점 인 것 같습니다.

요청대로 다시 게시 된 링크 : 레지스트리를 통한 그룹 정책 액세스

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top