如何将Paramiko stdin,stdout和stderr连接到控制台?

时间:2019-04-12 12:16:27

标签: python paramiko

我使用Paramiko Python软件包通过SSH运行命令。我可以将输出输出到stdout,但是如何正确地将stdout,stderr和stdin重定向到sys呢?

下面的代码在stdout上仅显示“ stdout1”和“ stdout2”。我如何正确地在其中获得“ stderr”?并且最好还支持stdin?

import paramiko
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect("localhost")
stdin, stdout, stderr = ssh.exec_command("echo stdout1 >&1; echo stderr >&2; echo stdout2 >&1")
ch = stdout.channel
while True:
    bs = ch.recv(1)
    if not bs:
        break
    print(bs.decode("utf-8"), end="")

2 个答案:

答案 0 :(得分:0)

您可以从stdin, stdout, stderr = ssh.exec_command("echo stdout1 >&1; echo stderr >&2; echo stdout2 >&1") while True: print(stdout.read().decode(), end='') if stdout.channel.exit_status_ready(): break while True: print(stderr.read().decode(), end='') if stderr.channel.exit_status_ready(): break http://docs.paramiko.org/en/2.4/api/channel.html?highlight=stdout#paramiko.channel.ChannelFile)中读取行。

示例:

Sub Test_It()

    Dim mySheet As Worksheet 
    Dim printRow As Integer
    printRow = 2
    For Each mySheet In ThisWorkbook.Sheets
        Range("A" & printRow).Value = mySheet.Name
        Range("B" & printRow).Value = SumGreen(mySheet)
        Range("C" & printRow).Value = SumRed(mySheet)
        printRow = printRow + 1
    Next mySheet
End Sub
Function SumGreen(mySheet As Worksheet) As Long 
    Dim myCell As Range
    Dim counter As Long
    For Each myCell In mySheet.UsedRange.Columns(1).Cells ' <<<< changed
        If myCell.Font.Color = 65280 Then
            counter = counter + 1
        End If
    Next myCell
    ' Set the function to return the counter
    SumGreen = counter
End Function

Function SumRed(mySheet As Worksheet) As Long
    Dim myCell As Range
    Dim counter As Long
    For Each myCell In mySheet.UsedRange.Columns(1).Cells
        If myCell.Font.Color = 255 Then ' 255 is red
            counter = counter + 1 
        End If
    Next myCell
    ' Set the function to return the counter
    SumRed = counter
End Function

此解决方案具有一些缺点,详细说明如下: Paramiko recv()/read()/readline(s)() on stderr returns empty string

答案 1 :(得分:0)

我发现asyncssh更适合我。以下代码按预期工作:

import asyncssh
import asyncio
import sys

async def run():
    async with asyncssh.connect('localhost') as ssh:
        await ssh.run("echo stdout1 >&1; echo stderr >&2; echo stdout2 >&1",
                      stdout=sys.stdout,
                      stderr=sys.stderr)

asyncio.run(run())