您的位置:首页 > 编程语言 > C#

在服务中创建用户进程的方法(C#版)

2009-11-20 11:30 471 查看
Windows NT/2000提供了一个函数CreateProcessAsUser,它的功能类似于CreateProcess函数,所不同的是CreateProcessAsUser创建的新进程能以用户(任何用户)的安全上下文方式运行。

// PlatformInvoke Stuff
[StructLayout(LayoutKind.Sequential)]
struct STARTUPINFO
{
public Int32 cb;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpReserved;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpDesktop;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpTitle;
public UInt32 dwX;
public UInt32 dwY;
public UInt32 dwXSize;
public UInt32 dwYSize;
public UInt32 dwXCountChars;
public UInt32 dwYCountChars;
public UInt32 dwFillAttribute;
public UInt32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public HandleRef hStdInput;
public HandleRef hStdOutput;
public HandleRef hStdError;
}

const int NORMAL_PRIORITY_CLASS = 0x00000020;

struct PROCESS_INFORMATION
{
public HandleRef hProcess;
public HandleRef hThread;
public UInt32 dwProcessId;
public UInt32 dwThreadId;
}

struct SECURITY_ATTRIBUTES
{
public UInt32 nLength;
public IntPtr lpSecurityDescriptor;
public Boolean bInheritHandle;
}

[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
static extern Boolean CreateProcessAsUser(
IntPtr hToken,
String lpApplicationName,
String lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
Boolean bInheritHandles,
UInt32 dwCreationFlags,
IntPtr lpEnvironment,
String lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);

[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
static extern Boolean LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
Int32 dwLogonType,
Int32 dwLogonProvider,
ref IntPtr phToken
);
const int LOGON32_LOGON_INTERACTIVE = 2;

public void Execute(string File)
{
try
{
//unsafe
{
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();

STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = "winsta0//default";

IntPtr hToken = new IntPtr(0);
if (LogonUser("auser", "mydomain", "Passw0rd!",
LOGON32_LOGON_INTERACTIVE, 0, ref hToken))
{
Boolean bResult = CreateProcessAsUser(
hToken,
File, // file to execute
null, // command line
IntPtr.Zero, // pointer to process SECURITY_ATTRIBUTES
IntPtr.Zero, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
0, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out pi // receives information about new process
);

if (bResult)
{
}
}
}
}
catch(Exception e)
{
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息