首页 > 代码库 > windows 实现用户切换

windows 实现用户切换

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

 

namespace changeUser
{
class Program
{
[DllImport("advapi32.dll", SetLastError = true)]

private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

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

//获得登录之后的token
private static IntPtr tokenHandle = new IntPtr(0);

private static WindowsImpersonationContext impersonatedUser;

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

private static bool Impersonate(string domainName, string userName, string password)
{

try
{

const int LOGON32_PROVIDER_DEFAULT = 0;

const int LOGON32_LOGON_INTERACTIVE = 2;

tokenHandle = IntPtr.Zero;

 

bool returnValue = http://www.mamicode.com/LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);

 

if (!returnValue)
{

int ret = Marshal.GetLastWin32Error();

// Console.WriteLine("LogonUser call failed with error code : " + ret);

throw new System.ComponentModel.Win32Exception(ret);

}

 

WindowsIdentity newId = new WindowsIdentity(tokenHandle);

impersonatedUser = newId.Impersonate();

return true;

}

catch (Exception ex)
{

Console.WriteLine("Exception occurred. " + ex.Message);

return false;

}

}

/// <summary>
/// 实现用户上下文切换。
/// </summary>
private static void Undo()
{

try
{
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
// Console.WriteLine("first:"+currentIdentity.User.ToString());
//实现用户切换
impersonatedUser.Undo();
currentIdentity = WindowsIdentity.GetCurrent();
// Console.WriteLine("second:" + currentIdentity.User.ToString());
// Free the tokens.

if (tokenHandle != IntPtr.Zero)

CloseHandle(tokenHandle);


}
catch (System.Exception ex)
{
Console.WriteLine("undo except:" + ex.Message);
}


}


public static void AddFileSecurity(string fileName, string account,

FileSystemRights rights, AccessControlType controlType)
{

 

 

// Get a FileSecurity object that represents the

// current security settings.

FileSecurity fSecurity = File.GetAccessControl(fileName);

 

// Add the FileSystemAccessRule to the security settings.

fSecurity.AddAccessRule(new FileSystemAccessRule(account,

rights, controlType));

 

// Set the new access settings.

File.SetAccessControl(fileName, fSecurity);

 

}


static void Main(string[] args)
{
try
{
if (args.Length < 3)
{
Console.WriteLine("info:");
Console.WriteLine("exe username password file:use username password zai path xia create index111.asp");
return;
}


string strUserName = args[0];
string strPass = args[1];
string strFile = args[2];
string strDomain = ".";

if (strUserName.IndexOf("\\") != -1)
{
strDomain = strUserName.Split(‘\\‘)[0];
strUserName = strUserName.Split(‘\\‘)[1];
}
Impersonate(strDomain, strUserName, strPass);

if (File.Exists(strFile))
{
//加入访问控制
AddFileSecurity(strFile, strUserName, FileSystemRights.FullControl, AccessControlType.Allow);
//设置文件属性
System.IO.File.SetAttributes(strFile, System.IO.FileAttributes.Normal);
File.Delete(strFile);

Console.WriteLine("delete is ok\n");
}



Undo();


}
catch (System.Exception ex)
{
Console.WriteLine("main except:" + ex.Message);
}
//http://www.gutefreunde.ch/content/files/documents/en_admin.aspx

 

}
}
}

 

windows 实现用户切换