class MySSHServerSession(asyncssh.SSHServerSession):
def __init__(self):
pass
def shell_requested(self):
return True
def exec_requested(self, command):
return True
def connection_made(self, chan):
self._chan = chan
def session_started(self):
proc = yield from asyncio.create_subprocess_shell(self._chan.get_command())
stdout, stderr = yield from proc.communicate()
self._chan.write(stdout)
import asyncio, asyncssh, subprocess, sys
@asyncio.coroutine
def forward_data(reader, writer):
try:
while not reader.at_eof():
data = yield from reader.read(8192)
writer.write(data)
writer.write_eof()
except BrokenPipeError:
pass
@asyncio.coroutine
def handle_connection(stdin, stdout, stderr):
cmd = stdin.channel.get_command()
if not cmd:
stderr.write(b'Missing command.\r\n')
stdin.channel.close()
return
shell = yield from asyncio.create_subprocess_shell(cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
asyncio.async(forward_data(stdin, shell.stdin))
asyncio.async(forward_data(shell.stdout, stdout))
asyncio.async(forward_data(shell.stderr, stderr))
yield from shell.wait()
stdin.channel.close()
@asyncio.coroutine
def start_server():
yield from asyncssh.listen('', 8022, server_host_keys=['ssh_host_key'],
authorized_client_keys='ssh_user_ca',
session_factory=handle_connection,
session_encoding=None)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(start_server())
except (OSError, asyncssh.Error) as exc:
sys.exit('Error starting server: ' + str(exc))
loop.run_forever()