使用 Java,您现在可以使用 JNA-API 在 Windows 系统上执行 CreateProcess 函数 -
这会在当前用户桌面(从会话 0 上运行的 windows 服务)上启动一个 cmd 控制台,该控制台运行一个程序 - 经过测试的 windows 7-11
使用喜欢
new CreateProcessAsUser("notepad.exe");
new CreateProcessAsUser("start PowerShell ");
import com.sun.jna.*;
import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.WinBase.*;
public class CreateProcessAsUser
{
public CreateProcessAsUser(String toExecute)
{
WString nullW = null;
PROCESS_INFORMATION processInformation = new PROCESS_INFORMATION();
STARTUPINFO startupInfo = new STARTUPINFO();
boolean result = MoreAdvApi32.INSTANCE.CreateProcessWithLogonW
(new WString("username"), // user
nullW, // domain , null if local
new WString("password"), // password
MoreAdvApi32.LOGON_WITH_PROFILE, // dwLogonFlags
nullW, // lpApplicationName
new WString("c:\\windows\\system32\\cmd.exe /c " + toExecute), // command line
MoreAdvApi32.CREATE_NEW_CONSOLE, // dwCreationFlags
null, // lpEnvironment
nullW, // directory
startupInfo,
processInformation);
if (!result)
{
int error = Kernel32.INSTANCE.GetLastError();
System.out.println("OS error #" + error);
System.out.println(Kernel32Util.formatMessageFromLastErrorCode(error));
}
}
}
interface MoreAdvApi32 extends Advapi32
{
MoreAdvApi32 INSTANCE =
(MoreAdvApi32) Native.loadLibrary("AdvApi32", MoreAdvApi32.class);
/*
* BOOL WINAPI CreateProcessWithLogonW( __in LPCWSTR lpUsername,
* __in_opt LPCWSTR lpDomain, __in LPCWSTR lpPassword, __in DWORD
* dwLogonFlags, __in_opt LPCWSTR lpApplicationName, __inout_opt LPWSTR
* lpCommandLine, __in DWORD dwCreationFlags, __in_opt LPVOID
* lpEnvironment, __in_opt LPCWSTR lpCurrentDirectory, __in
* LPSTARTUPINFOW lpStartupInfo, __out LPPROCESS_INFORMATION
* lpProcessInfo );
*/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682431%28v=vs.85%29.aspx
boolean CreateProcessWithLogonW
(WString lpUsername,
WString lpDomain,
WString lpPassword,
int dwLogonFlags,
WString lpApplicationName,
WString lpCommandLine,
int dwCreationFlags,
Pointer lpEnvironment,
WString lpCurrentDirectory,
STARTUPINFO lpStartupInfo,
PROCESS_INFORMATION lpProcessInfo);
public static final int LOGON_WITH_PROFILE = 0x00000001;
public static final int LOGON_NETCREDENTIALS_ONLY = 0x00000002;
int CREATE_NO_WINDOW = 0x08000000;
int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
int CREATE_NEW_CONSOLE = 0x00000010;
int DETACHED_PROCESS = 0x00000008;
}