我正在尝试使用AsyncSSH模块执行命令并捕获输出以进行进一步处理。我遵循了official documentation上的示例,但是它们都将结果打印(),我想将其保存为列表。如何在Python 3.5中做到这一点?我试图通过添加将返回“退出”列表的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))