2010-10-14 90 views
5

嘗試使用另一個訪問令牌啓動進程,但未成功,它將作爲非模擬用戶運行。Process.Start()模擬問題

using (WindowsIdentity identity = new WindowsIdentity(token)) 
using (identity.Impersonate()) 
{ 
    Process.Start("blabla.txt"); 
} 

如何使其正常工作?

回答

1

http://msdn.microsoft.com/en-us/library/w070t6ka.aspx

private static void ImpersonateIdentity(IntPtr logonToken) 
{ 
    // Retrieve the Windows identity using the specified token. 
    WindowsIdentity windowsIdentity = new WindowsIdentity(logonToken); 

    // Create a WindowsImpersonationContext object by impersonating the 
    // Windows identity. 
    WindowsImpersonationContext impersonationContext = 
     windowsIdentity.Impersonate(); 

    Console.WriteLine("Name of the identity after impersonation: " 
     + WindowsIdentity.GetCurrent().Name + "."); 

    //Start your process here 
    Process.Start("blabla.txt"); 

    Console.WriteLine(windowsIdentity.ImpersonationLevel); 
    // Stop impersonating the user. 
    impersonationContext.Undo(); 

    // Check the identity name. 
    Console.Write("Name of the identity after performing an Undo on the"); 
    Console.WriteLine(" impersonation: " + 
     WindowsIdentity.GetCurrent().Name); 
} 

試試這個例子也可以使用CreateProcessAsUser窗口功能。

http://www.pinvoke.net/default.aspx/advapi32/createprocessasuser.html

+0

謝謝,但這段代碼有完全一樣的結果。 – DxCK 2010-10-14 19:09:33

+0

增加了另外一個解決方案 – 2010-10-14 19:21:34

+1

'CreateProcessAsUser'無法啓動像blabla.txt這樣的非exe文件,所以這個選項對我來說並不好。 – DxCK 2010-10-15 09:28:07

6

您需要設置ProcessStartInfo.UserName和Password屬性。 UseShellExecute設置爲false。如果你只有一個令牌,那麼就調用CreateProcessAsUser()。

+0

將UseShellExecute設置爲false時,我無法啓動非exe文件,如blabla.txt,所以此選項對我不好。 – DxCK 2010-10-14 19:52:05

+2

好吧,獲取與文件擴展名關聯的.exe路徑是一個完全不同的問題。被其他SO線程所覆蓋,無需在此重複。 ShellExecuteEx()不支持使用不同的(受限)用戶令牌創建進程。這個選項對你不好。 – 2010-10-14 19:58:20

+0

'CreateProcessAsUser'沒有'Exited'通知等。我有一個遺留代碼,它啓動一個填充'ProcessStartInfo'的進程,訂閱'Exited'並在其他地方調用'process.Start'。我試圖移植這個代碼,以便它可以與給定的令牌一起工作,並且它看起來我必須自己編寫所有的基礎架構......很多工作。除非Keivan答案有效。我需要先嚐試一下。 – 2013-11-19 08:41:25