public class IdentityScope : IDisposable { /// <summary> /// 登录一个新用户 /// </summary> /// <param name="pszUsername"></param> /// <param name="pszDomain"></param> /// <param name="pszPassword"></param> /// <param name="dwLogonType"></param> /// <param name="dwLogonProvider"></param> /// <param name="phToken"></param> /// <returns></returns> [DllImport("advapi32.dll", SetLastError = true)] static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); //closes open handes returned by LogonUser [DllImport("kernel32.dll", CharSet = CharSet.Auto)] extern static bool CloseHandle(IntPtr handle); /// <summary> /// 让调用线程模拟一个用户 /// </summary> /// <param name="hToken"></param> /// <returns></returns> [DllImport("Advapi32.DLL")] static extern bool ImpersonateLoggedOnUser(IntPtr hToken); /// <summary> ///终止模拟的客户应用程序 /// </summary> /// <returns></returns> [DllImport("Advapi32.DLL")] static extern bool RevertToSelf(); public IdentityScope(string Username, string Domain, string Password) { // initialize tokens IntPtr pExistingTokenHandle = new IntPtr(0); IntPtr pDuplicateTokenHandle = new IntPtr(0); try { // get handle to token bool bImpersonated = LogonUser(Username, Domain, Password, LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle); if (true == bImpersonated) { if (!ImpersonateLoggedOnUser(pExistingTokenHandle)) { int nErrorCode = Marshal.GetLastWin32Error(); throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode); } } else { int nErrorCode = Marshal.GetLastWin32Error(); throw new Exception("LogonUser error;Code=" + nErrorCode); } } finally { // close handle(s) if (pExistingTokenHandle != IntPtr.Zero) CloseHandle(pExistingTokenHandle); if (pDuplicateTokenHandle != IntPtr.Zero) CloseHandle(pDuplicateTokenHandle); } } const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_LOGON_NEWCREDENTIALS = 9; private bool disposed; public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!disposed) { RevertToSelf(); disposed = true; } } }
using (IdentityScope iss = new IdentityScope("登录服务器用户名", "服务器IP", "登录服务器密码")) { //连接服务器后,按正常的操作来做你想要的操作! }
时间: 2024-10-28 15:43:35