C # Specifies the sample code (reproduced) of the user executive program

xiaoxiao2021-03-31  211

#Region Using Directives Using System; Using System.Security.principal; Using System.Runtime.InteropServices; Using System.Text.RegularExpressions; #ENDREGON

A summary description of Namespace TestenumWindows {///

/// changeuser. /// public class ChangeUser {[DllImport ( "advapi32.dll", SetLastError = true)] public extern static bool LogonUser (String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken) ;

[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);

Public static void main (string [] args) {console.writeline ("The current user is:" windowsidentity.getCurrent (); impersonatedWork testdel = new impersonateDwork (test); impersonateAnddo ("test", "," BCA ~ 123 ", testdel); console.writeline (" The current user is: " windowsidentity.getcurrent (). name);}

Static void test () {console.writeline ("The current user is:" windowsidentity.getcurrent (). name);

Public delegate void impersonatedWork ();

/// Do something with the specified user /// /// /// < / param> /// public static void ImpersonateAndDo (string UserName, string PWD, ImpersonatedWork WhatToDo) {string domainName = string.Empty; string userName = string.Empty; IntPtr tokenHandle = new IntPtr (0); IntPtr dupeTokenHandle = new IntPtr (0); const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_INTERACTIVE = 2; const int SecurityImpersonation = 2;! if (Regex.IsMatch (UserName, @ "^ / w [// ]? / w $ ")) {throw new applicationException (" illegal user name ");} string [] TMP = username.split (new char [] {'//'}); if (Tmp.Length> 1 ) {domainName = tmp [0]; userName = tmp [1];} else {userName = tmp [0];} tokenHandle = IntPtr.Zero; dupeTokenHandle = IntPtr.Zero; bool returnValue = LogonUser (userName, domainName, PWD, Logon32_logon_interactive, logon32_provider_default, ref tokenhandle; if (! ReturnValue) {throw new applicationException ("Take Handle Error!");} // console.writeline ("The current user is:" // windowsidentity.getCurrent (). name);

bool retVal = DuplicateToken (tokenHandle, SecurityImpersonation, ref dupeTokenHandle); if (retVal!) {CloseHandle (tokenHandle); throw new ApplicationException ( "copy Handle wrong!");} WindowsIdentity newId = new WindowsIdentity (dupeTokenHandle); WindowsImpersonationContext impersonatedUser = Newid.impersonate (); whattodo (); impersonateduser.undo (); if (tokenhandle! = INTPTR.ZERO) CloseHandle; if (DupetokenHandle! = INTPTR.ZERO) CloseHandle (Dupetokenhandle);}}}

转载请注明原文地址:https://www.9cbs.com/read-130967.html

New Post(0)