捕获cmd的输出,在Windows上作为另一个用户远程运行

2024-09-30 16:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试使用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


Tags: andtxt脚本forisscriptcommonout
1条回答
网友
1楼 · 发布于 2024-09-30 16:30:42

您无法使用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仍然绑定到用户会话。然而,看看这个问题;A:

Redirect STDOUT\STDERR to current shell from win32_process create on remote computer

相关问题 更多 >