python - 借助 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 文件之上,否则它将无法工作。
解决方案
您当前正在向 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"
了正确发送换行符所需的内容。
推荐阅读
- node.js - 如何在猫鼬模式中使用项目的值
- r - 正确使用扩展函数
- vue.js - Vue.js - Element UI - 获取表单验证的状态
- google-analytics - 使用增强型电子商务事件跟踪来源/媒介
- python - pytest下unittest subTest元素输出不足
- elasticsearch - 尝试在 Elasticsearch 中设置 max_gram 和 min_gram
- javascript - 我如何将数据从 ReactJS 提交表单传递给 AdonisJS
- html - 在css中排列4个具有相同类名的div
- ios - 在 iOS C# 中从 Unity 拨打电话
- gradle - Gradle - 将文件夹复制到 jar 中