I want to run local python script on remote server by using Posh-SSH which is a module in Powerhsell. This topic mention it with regular ssh by doing this:
Get-Content hello.py | ssh user@192.168.1.101 python -
I would like here to use Posh-SSH module but I don't get how to achieve it...
I tried sth like this but it doesn't work
Invoke-SSHCommand -Index $sessionid.sessionid -Command "$(Get-Content hello.py) | python3 -u -" -ErrorAction Stop
EDIT
No errors shown, only stuck on it and and do nothing...
EDIT2
Ok I get it now why I have this error when I send a multiline py file.
New lines are not retranscripted, look what command will be send to the remote server :
python3 -u - <<"--ENDOFPYTHON--"
chevre="basic" print("Hello, World!")
--ENDOFPYTHON--
and not:
python3 -u - <<"--ENDOFPYTHON--"
chevre="basic"
print("Hello, World!")
--ENDOFPYTHON--
EDIT3
And finally Done ! Thanks to this topic I performed to change the whitespace to newline as it should be. For doing this just to this
( (Get-Content hello.py) -join "`r`n")
instead of simple
$(Get-Content hello.py)
Finally the line will be :
$cmd = "python3 -u - <<`"--ENDOFPYTHON--`"`n$((Get-Content $pyscript) -join "`r`n")`n--ENDOFPYTHON--"
Invoke-SSHCommand -Index $sessionid.sessionid -Command $cmd -ErrorAction Stop
Also don't forget to remove the line
#!/usr/bin/env python3
if present on top of your py file, otherwise it won't work.
You are currently sending the following to the SSH endpoint:
# Example Python Added: would be replaced with your code
print("Hello, World!") | python3 -u -
Assuming bash as the endpoint shell, the above is invalid and would either produce an error or hang.
You need to encapsulate the code being sent to the server using echo
(assuming bash ssh endpoint).
Invoke-SSHCommand -Index $sessionid.sessionid -Command "echo '$((Get-Content hello.py) -join "`r`n")' | python3 -u -" -ErrorAction Stop
The above will now send:
echo 'print("Hello, World!")' | python3 -u -
This works as long as you don't use single quotes. However, if you must use those or other special characters, you may need to use a here document instead:
Invoke-SSHCommand -Index $sessionid.sessionid -Command "python3 -u - <<`"--ENDOFPYTHON--`"`n$((Get-Content hello.py) -join "`r`n")`n--ENDOFPYTHON--" -ErrorAction Stop
The here document will send exactly what it is to the standard input stream of the program: tabs, spaces, quotes and all. Therefore the above will send the following:
python3 -u - <<"--ENDOFPYTHON--"
print("Hello, World!")
--ENDOFPYTHON--
You can replace --ENDOFPYTHON--
with anything as long as it does not appear in your python file.
Added -join "`r`n"
as it is needed for newlines to be sent correctly, as pointed out by the asker.