首页 > 解决方案 > 借助 Posh-SSH 模块 (W10) 在远程服务器上运行本地 python 脚本

问题描述

我想使用Powerhsell 中的一个模块Posh-SSH在远程服务器上运行本地 python 脚本。主题通过执行以下操作在常规 ssh 中提及它:

Get-Content hello.py | ssh user@192.168.1.101 python -

我想在这里使用 Posh-SSH 模块,但我不知道如何实现它......

我试过这样但它不起作用

Invoke-SSHCommand -Index $sessionid.sessionid -Command "$(Get-Content hello.py) | python3 -u -" -ErrorAction Stop

编辑

没有显示错误,只是卡在上面,什么也不做......

编辑2

好的,我现在明白了,为什么我在发送多行 py 文件时会出现此错误。

新行没有被重新转录,看看什么命令将被发送到远程服务器:

python3 -u - <<"--ENDOFPYTHON--"
chevre="basic" print("Hello, World!")
--ENDOFPYTHON--

并不是:

python3 -u - <<"--ENDOFPYTHON--"
chevre="basic" 
print("Hello, World!")
--ENDOFPYTHON--

编辑3

最后完成!感谢这个主题,我执行了将空格更改为换行符的操作。这样做只是为了这个

( (Get-Content hello.py) -join "`r`n")

而不是简单

$(Get-Content hello.py)

最后一行将是:

$cmd = "python3 -u - <<`"--ENDOFPYTHON--`"`n$((Get-Content $pyscript) -join "`r`n")`n--ENDOFPYTHON--"
Invoke-SSHCommand -Index $sessionid.sessionid -Command $cmd -ErrorAction Stop

也不要忘记删除线

#!/usr/bin/env python3

如果存在于您的 py 文件之上,否则它将无法工作。

标签: pythonpowershellsshposh-ssh

解决方案


您当前正在向 SSH 端点发送以下内容:

# Example Python Added: would be replaced with your code
print("Hello, World!") | python3 -u -

假设 bash 作为端点 shell,以上是无效的并且会产生错误或挂起。

echo您需要使用(假设 bash ssh 端点)封装发送到服务器的代码。

Invoke-SSHCommand -Index $sessionid.sessionid -Command "echo '$((Get-Content hello.py) -join "`r`n")' | python3 -u -" -ErrorAction Stop

以上内容现在将发送:

echo 'print("Hello, World!")' | python3 -u -

只要您不使用单引号,它就可以工作。但是,如果您必须使用这些或其他特殊字符,则可能需要使用此处的文档:

Invoke-SSHCommand -Index $sessionid.sessionid -Command "python3 -u - <<`"--ENDOFPYTHON--`"`n$((Get-Content hello.py) -join "`r`n")`n--ENDOFPYTHON--" -ErrorAction Stop

这里的文档将准确地发送到程序的标准输入流:制表符、空格、引号和所有内容。因此,上面将发送以下内容:

python3 -u - <<"--ENDOFPYTHON--"
print("Hello, World!")
--ENDOFPYTHON--

--ENDOFPYTHON--只要它没有出现在您的 python 文件中,您就可以替换为任何内容。

此处文档的参考

更新:

正如提问者所指出的那样,添加-join "`r`n"了正确发送换行符所需的内容。


推荐阅读