-
I wish to create a SSHServer which reads the stdin from a client and if it sends ctrl+c it should close the connection. I am able to sorta achieve this by using the following handle_client function: async def handle_client(process: asyncssh.SSHServerProcess) -> None:
process.stdout.write(f'information from server\n')
async for line in process.stdin:
print(line) With this I can detect if line == 'exit':
process.exit(0)
break for example which is okay, but I prefer to allow the user to exit with ctrl+c. In this case Any help/pointers in either how to allow ctrl+c termination (without causing errors) or in figuring out why ctrl+c is causing the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I'm going to assume that you're running with the defaults on the server, meaning the In such a setup, the line editor on the server takes responsibility for doing things like echoing the user's input and allowing them to edit it a line at a time before actually sending it to the server application. It also does things like convert a received Ctrl-C into a "break" (like what you'd get from OpenSSH by entering "~B") and converting a received Ctrl-D as a "soft" end-of-file, similar to what you get when a client half-closes a connection, where the server application will receive an empty string back from a read to indicate the EOF. The way you deal with this is to put a try..except block round your read() call looking for BreakReceived, or other special exceptions like SignalReceived or TerminalSizeChanged. One such example is at https://asyncssh.readthedocs.io/en/latest/#simple-server-with-input, where you can see it looking for BreakReceived as one way of exiting the read loop. If you don't want the line editing capability, you can set Here's another example: async def handle_client(process):
process.stdout.write('Welcome to my SSH server, %s!\r\n\r\n' %
process.get_extra_info('username'))
try:
async for line in process.stdin:
if not line:
process.stdout.write('EOF received\r\n')
break
process.stdout.write(f'Line received: {repr(line)}\r\n')
except asyncssh.BreakReceived:
process.stdout.write('Break received\r\n')
process.exit(0) |
Beta Was this translation helpful? Give feedback.
I'm going to assume that you're running with the defaults on the server, meaning the
line_editor
feature is enabled, and that you are using an interactive SSH client like OpenSSH, with it requesting a PTY (and sending terminal type information).In such a setup, the line editor on the server takes responsibility for doing things like echoing the user's input and allowing them to edit it a line at a time before actually sending it to the server application. It also does things like convert a received Ctrl-C into a "break" (like what you'd get from OpenSSH by entering "~B") and converting a received Ctrl-D as a "soft" end-of-file, similar to what you get when a client half-closes a connecti…