windows 實現使用者切換

來源:互聯網
上載者:User

標籤:split   admin   sum   component   dem   generic   let   settings   run   

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 = 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 實現使用者切換

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.