C#指定用户执行程序的示例代码(转载)

#region using directives
 using System;
 using System.Security.Principal;
 using System.Runtime.InteropServices;
 using System.Text.RegularExpressions;
#endregion


namespace testEnumWindows
{
 /// <summary>
 /// ChangeUser 的摘要说明。
 /// </summary>
 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("当前用户是: "+ WindowsIdentity.GetCurrent().Name);
   ImpersonatedWork testDel = new ImpersonatedWork(Test);
   ImpersonateAndDo("test", "bca~123", testDel);
   Console.WriteLine("当前用户是: "+ WindowsIdentity.GetCurrent().Name);
  }

  static void Test()
  {
   Console.WriteLine("当前用户是: " + WindowsIdentity.GetCurrent().Name);
  }

  public delegate void ImpersonatedWork();

   <summary>
  /// 以指定用户的身份去做一件事情
  /// </summary>
  /// <param name="UserName"></param>
  /// <param name="PWD"></param>
  /// <param name="WhatToDo"></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("非法的用户名");
   }
   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("取Handle出错了!");
   }

   //Console.WriteLine("当前用户是: "
   //    + WindowsIdentity.GetCurrent().Name);

   bool retVal = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
   if (!retVal)
   {
    CloseHandle(tokenHandle);
    throw new ApplicationException("复制Handle出错了!");
   }
   WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
   WindowsImpersonationContext impersonatedUser = newId.Impersonate();
   
   
    WhatToDo();
   
   
    impersonatedUser.Undo();
   if (tokenHandle != IntPtr.Zero)
    CloseHandle(tokenHandle);
   if (dupeTokenHandle != IntPtr.Zero)
    CloseHandle(dupeTokenHandle);
   
 }

 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值