文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>用指定账号运行代码

用指定账号运行代码

时间:2011-03-08  来源:Haitch

需要调用Windows登陆函数,从AdvAPI32.dll里面导入3个函数LogonUser,DuplicateToken,CloseHandle。具体过程和代码一并写在下面:

Code Snippet
  1. //μ?è?3个?oˉêy。£
  2. [DllImport("advapi32.dll", SetLastError = true)]
  3. private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
  4. [DllImport("advapi32.dll", SetLastError = true)]
  5. private static extern bool DuplicateToken(IntPtr ExistingTokenHandle, Int32 ImpersonationLevel, out IntPtr DuplicateTokenHandle);
  6. [DllImport("advapi32.dll", SetLastError = true)]
  7. private static extern bool CloseHandle(IntPtr hHandle);

定义一些枚举变量

Code Snippet
  1. public enum WindowsLogonType
  2. {
  3.     INTERACTIVE = 2,
  4.     NETWORK = 3,
  5.     BATCH = 4,
  6.     SERVICE = 5,
  7.     UNLOCK = 7,
  8.     NETWORK_CLEARTEXT = 8,
  9.     NEW_CREDENTIALS = 9
  10. }
  11.  
  12. public enum ImpersonationLevel
  13. {
  14.     SecurityAnonymous,
  15.     SecurityIdentification,
  16.     SecurityImpersonation,
  17.     SecurityDelegation
  18. }
  19.  
  20. const Int32 LOGON32_PROVIDER_DEFAULT = 0;

开始登陆过程:
Code Snippet
  1. IntPtr hToken = IntPtr.Zero; //LogonUser·μ回?值μ
  2. WindowsIdentity windowsIdentity;
  3.  
  4. if (LogonUser(username, domain, password, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, out hToken))
  5. {
  6.     windowsIdentity = new WindowsIdentity(hToken);
  7.     WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate();
  8.     //旧é帐êo?μ?句?±úè?栈?£?这aà?íùoóμ?′ú码?都?运?DD在úD?μ?账?o?下?面?。£
  9.     //这aà?运?DD你?μ?′ú码?
  10.     impersonationContext.Undo();
  11.     //D?帐êo?μ?句?±ú×÷·?£?旧é帐êo?μ?句?±ú恢?复′。£
  12. }
  13. else
  14. {
  15.     int ret = Marshal.GetLastWin32Error();
  16.     Console.WriteLine("Logon as service failed, Error Code: " + ret.ToString());
  17. }
  18. if (hToken != IntPtr.Zero) CloseHandle(hToken);

Windows登陆后返回一个句柄,拿着这个句柄可以生成一个WindowsIdentity,然后WindowsIdentity的Impersonate函数会把当前账号入栈,新帐号激活,并且返回一个WindowsImpersonationContext。这时后面的代码就运行在新帐号权限下面,想返回之前的账号时用WindowsImpersonationContext的Undo函数就可以撤销账号的更改,旧帐号激活。

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载