使用 Python 的 Paramiko exec_command 使用 PowerShell Start-Process 启动的进程无法正常工作,尽管它在 SSH 终端上运行良好

Process started with PowerShell Start-Process using Python's Paramiko exec_command is not working although it is working fine from SSH terminal

我想以管理员身份执行 Python 脚本。我正在使用以下命令来执行此操作:

powershell Start-Process python -ArgumentList "C:\Users\myuser\python_script.py","-param1", "param1","-param2","param2" -Verb "runAs"

如果我通过终端使用传统 SSH,则此命令可以正常工作。 目标机器是 Windows RS4,我正在使用自 RS3 以来可用的新本机 SSH 服务器。

我客户的 Python 代码是:

import paramiko

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=myhost, username=myuser, password='trio_012')
stdin, stdout, stderror = ssh_client.exec_command("powershell Start-Process python -ArgumentList \"C:\Users\myuser\python_script.py\",\"-param1\", \"param1\",\"-param2\",\"param2\" -Verb \"runAs\"")

print 'stdout:', stdout.readlines()
print 'stderror:', stderror.readlines()

我得到的输出:

stdout: []
stderror: []

我没看到另一边的脚本是 运行,似乎什么也没发生。 我不知道是什么问题,因为我没有输出。

我正在使用 Paramiko 1.18.5(我无法使用新的 v2,我在 known_hosts 文件和 Windows 使用 paramiko.AutoAddPolicy() 策略时遇到问题)

Start-Process 开始的进程在启动它的 SSH 通道关闭时关闭。

"exec" 通道 (exec_command) 在 powershell 进程完成后立即关闭,这几乎是瞬时的。所以我相信您的 python 进程实际上已启动,但几乎立即被关闭。

如果您添加 -Wait 切换到 Start-Process,应该会有帮助。

stdin, stdout, stderror =
    ssh_client.exec_command("powershell Start-Process python -ArgumentList \"C:\Users\myuser\python_script.py\",\"-param1\", \"param1\",\"-param2\",\"param2\" -Verb \"runAs\" -Wait")

它 "works" 来自 SSH 终端,因为终端(SSH "shell" 通道)在 powershell 进程完成后保持打开状态。但是,如果您在 python 进程完成之前关闭终端,它也会终止它。


强制性警告:请勿使用 AutoAddPolicy – 您将失去对 MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

的保护