gpt4 book ai didi

delphi - 如何从服务应用程序使用 CreateProcessWithLogonW?

转载 作者:行者123 更新时间:2023-12-02 02:50:56 24 4
gpt4 key购买 nike

我需要从 Windows 服务运行命令行应用程序,以另一个 Windows 用户身份执行它(通过提供域\用户密码)。

我以这种方式将 Windows API CreateProcessWithLogonW() 包装在我自己的 RunAppAsAnotherWindowsUser() 函数中:

function CreateProcessWithLogonW(
lpUsername,
lpDomain,
lpPassword: PWideChar;
dwLogonFlags: DWORD;
lpApplicationName: PWideChar;
lpCommandLine: PWideChar;
dwCreationFlags: DWORD;
lpEnvironment: Pointer;
lpCurrentDirectory: PWideChar;
lpStartupInfo: PStartupInfoW;
lpProcessInformation: PProcessInformation
): BOOL; stdcall; external 'advapi32.dll';

function RunAppAsAnotherWindowsUser(const User, Domain, PW, Application, CmdLineParams: WideString): LongWord;

const
LOGON_WITH_PROFILE = $00000001;

implementation

function RunAppAsAnotherWindowsUser(const User, Domain, PW, Application, CmdLineParams: WideString): LongWord;
var
si : TStartupInfoW;
pif : TProcessInformation;
begin
ZeroMemory(@si, sizeof(si));
si.cb := sizeof(si);
si.dwFlags := STARTF_USESHOWWINDOW;
si.wShowWindow := 1;

SetLastError(0);
CreateProcessWithLogonW(PWideChar(User), PWideChar(Domain), PWideChar(PW),
LOGON_WITH_PROFILE, nil, PWideChar(Application+' '+CmdLineParams),
CREATE_DEFAULT_ERROR_MODE, nil, nil, @si, @pif);
Result := GetLastError;
end;

上面是adapted from here .

当我在为测试而创建的 Win32 VCL 应用程序中使用 RunAppAsAnotherWindowsUser () 时,它工作正常。当我从 Windows 服务调用它时,它不起作用。

我读到this pageadvised here ,但就我而言,我没有交互过程,因为我的命令行应用程序仅执行数据库查询并写入临时文件。

我尝试以本地系统而不是域管理员的身份运行该服务,但行为是相同的。

该服务是作为服务构建的 IntraWeb(VCL for the Web)应用程序。与 exe 一样构建的应用程序运行良好。我写这篇文章只是为了解释我工作的背景。

您能帮我找出问题所在吗?

最佳答案

从服务中,您应该在用户 session 中启动该进程(在物理 PC 上,通常是控制台 session )。自 Windows Vista 以来就是这种情况:

Services have always run in session 0. Before Windows Vista, the first user to log on was also assigned to session 0. Now, session 0 is reserved exclusively for services and other applications not associated with an interactive user session. (The first user to log on is connected to session 1, the second user to log on is connected to session 2, and so on.) Session 0 does not support processes that interact with the user.

参见here我的博客上有一个非常基本的例子,使用 Jedi Apilib .

来自此博客:

uses JwaWinbase, JwaWtsApi32;       

var hToken: THandle;
si: _STARTUPINFOA;
pi: _PROCESS_INFORMATION;
var Ret: Cardinal;
sTitle: string;
sMsg: string;
begin
ZeroMemory(@si, SizeOf(si));
si.cb := SizeOf(si);
si.lpDesktop := nil;

if WTSQueryUserToken(WtsGetActiveConsoleSessionID, hToken) then
begin
if CreateProcessAsUser(hToken, nil, 'notepad.exe', nil, nil, False,
0, nil, nil, si, pi) then
begin
// Do some stuff
end;
end;
end;

关于delphi - 如何从服务应用程序使用 CreateProcessWithLogonW?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43872364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com