以 Windows 上的另一个用户身份远程捕获 cmd 运行 的输出

Capture output of cmd, run remotely as another user on Windows

尝试运行使用 WinRM 的 PowerShell 脚本

# $cred is valid and works for common PowerShell cmdlets

script = """
Start-Process ping.exe -Credential $cred -NoNewWindow -Wait -RedirectStandardOutput out.txt
Get-Content out.txt
"""
session = winrm.Session(host, auth=(user,passwd), transport="credssp')
result = s.run_ps(script)

如果不使用-Credentials,则返回输出。

否则,这会创建一个空的 out.txt 文件。如何将输出重定向到 out.txt/stdout?

您不能使用 PowerShell 本机执行此操作。这是一个 Windows 适当的安全边界。 PowerShell 将始终 运行 在 运行 代码的用户上下文中。

为此,您需要使用外部工具,例如 MS SysInternals PSExec...

# Example:
# Using PsExec to Run Command on Remote Computer
psexec \RemotePCName [-u username[-p password]] command [arguments]

psexec \lon-srv01 powershell -ExecutionPolicy RemoteSigned -command "'{0:N2}' -f ((gci C:\PS | measure Length -Sum).Sum/1MB)"

...或使用计划任务 运行 在登录时或一天中的其他时间编写代码。

Don't use Credssp unless you have no other choice.

Accidental Sabotage: Beware of CredSSP: https://www.powershellmagazine.com/2014/03/06/accidental-sabotage-beware-of-credssp/

PowerShell redirection 仍然绑定到用户会话。然而,看看这个 Whosebug 问答: