Чтение удаленного реестра Windows через C # - PullRequest
0 голосов
/ 17 ноября 2011

Мне нужно прочитать некоторые значения ключей из удаленного реестра.Я использовал классы Registry и RegistryKey, и он хорошо работает на локальной машине.Затем я попробовал это на удаленной машине, и я могу получить только базовые ключи (HKLM, HKCU и т. Д.), Но я не могу получить никаких подразделов, потому что у меня нет прав доступа.Я ищу в Google и обнаружил класс Олицетворения и написанную оболочку.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

namespace WindowsFormsApplication1
{ 
    class ImpersonateClass
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
            int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
            int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
        private string userName;
        private string computerName;
        private string password;
        private IntPtr tokenHandle = IntPtr.Zero;

        public ImpersonateClass(string aUserName, string aComputerName, string aPassword)
        {
            userName = aUserName;
            computerName = aComputerName;
            password = aPassword;
        }

        public WindowsImpersonationContext impersonateUser()
        {
            if (LogonUser(userName, computerName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle))
            {
                Console.WriteLine("Value of Windows NT token: " + tokenHandle);
                WindowsIdentity newId = new WindowsIdentity(tokenHandle);
                return newId.Impersonate();
            }
            else
            {
                return null;
            }
        }

        public void unimpersonateUser(ref WindowsImpersonationContext anImpersonatedUser)
        {
            if (anImpersonatedUser != null)
            {
                anImpersonatedUser.Undo();
            }   
        }
    }
}

И основной класс

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Principal;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, EventArgs e)
        {
            ImpersonateClass impersonate = new ImpersonateClass(@"admministrator", "localMachine", "2.71828");
            Console.WriteLine("before impersonation: "
                + WindowsIdentity.GetCurrent().Name);
            this.output.Text += WindowsIdentity.GetCurrent().Name + "\r\n";

            WindowsImpersonationContext tmpid = impersonate.impersonateUser();
            Console.WriteLine("After impersonation: "
                + WindowsIdentity.GetCurrent().Name);
            this.output.Text += WindowsIdentity.GetCurrent().Name + "\r\n";

            impersonate.unimpersonateUser(ref tmpid);
            Console.WriteLine("After unimpersonation: "
                + WindowsIdentity.GetCurrent().Name);
            this.output.Text += WindowsIdentity.GetCurrent().Name + "\r\n";
        }
    }
}

Если параметры конструктора - "admministrator", "localMachine", "2.71828", то у меня естьвыведите localMachine \ User localMachine \ administrator localMachine \ User

Если в конструкторе указаны параметры «administrator», «remoteMachine», «2.71828» localMachine \ User localMachine \ administrator localMachine \ User

Если параметрыКонструктор: «remoteMachine \ admministrator», «remoteMachine», «2.71828», программа возвращает

localMachine \ User localMachine \ User localMachine \ User

пароли верны и администратор пользователя создан на обеих машинах

Я не могу понять, почему не могу стать удаленнымMachine \ Administrator

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...