2010-10-14 38 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