1

我正在尝试使用 AsyncSSH 模块来执行命令并捕获输出以进行进一步处理。我正在关注官方文档上的示例,但它们都 print() 结果,我想将其保存为列表。我将如何在 Python 3.5 中做到这一点?我试图通过添加将返回“out”列表的 getdata() 来修改类,但它似乎不起作用

import asyncio, asyncssh, sys


class MySSHClientSession(asyncssh.SSHClientSession):

    out = []

    def data_received(self, data, datatype):
        if datatype == asyncssh.EXTENDED_DATA_STDERR:
            print(data, end='', file=sys.stderr)
        else:
            #print(data, end='')
            self.out.append(data)

    def connection_lost(self, exc):
        if exc:
            print('SSH session error: ' + str(exc), file=sys.stderr)

    def getdata(self):
        return self.out


async def run_client(zone, cmd):
    async with asyncssh.connect(zone, password='xxx', username='xxx', known_hosts=None) as conn:
        chan, session = await conn.create_session(MySSHClientSession, cmd)
        await chan.wait_closed()

try:
    x = asyncio.get_event_loop().run_until_complete(run_client('fetish', 'sudo fl-service status'))
# the code to process x would go here
    print(x.getdata())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))
4

1 回答 1

0

我已经更正了你的代码。

  • 你的 out[] 没有启动,你试图追加到 None
  • self.out 只能在其生命周期中使用。
import asyncio, asyncssh, sys
    
class MySSHClientSession(asyncssh.SSHClientSession):
    def __init__(self):
        self.out = []

    def data_received(self, data, datatype):
        if datatype == asyncssh.EXTENDED_DATA_STDERR:
            print(data, end='', file=sys.stderr)
        else:
            #print(data, end='')
            self.out.append(data)

    def connection_lost(self, exc):
        if exc:
            print('SSH session error: ' + str(exc), file=sys.stderr)
        else:
            print(self.out)


async def run_client(zone, cmd):
    async with asyncssh.connect(zone, password='xxx', username='xxx', known_hosts=None) as conn:
        chan, session = await conn.create_session(MySSHClientSession, cmd)
        await chan.wait_closed()

try:
    x = asyncio.get_event_loop().run_until_complete(run_client('fetish', 'whoami'))
# the code to process x would go here
    #print(x.getdata())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))
于 2022-01-25T15:02:01.887 回答