Manas
Manas

Reputation: 113

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

Trying to run a PowerShell script using WinRM

# $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)

If -Credentials is not used, the output is returned.

Otherwise, this creates an empty out.txt file. How do I redirect the output to out.txt/stdout?

Upvotes: 0

Views: 548

Answers (1)

postanote
postanote

Reputation: 16086

You can not do this with PowerShell natively. It is a Windows proper security boundary. PowerShell will always run in the context of the user who ran the code.

To do this, you need to use an external tool, like 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)"

... or use a scheduled task to run code at logon, or some other point in the day.

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 is still tied to the user session. Yet, take a look at this Stackoverflow Q&A:

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

Upvotes: 1

Related Questions