Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.86 KB | None | 0 0
  1. import asyncio
  2. import crypt
  3. import sys
  4. import os
  5.  
  6. from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop
  7. from prompt_toolkit.patch_stdout import patch_stdout
  8. from prompt_toolkit import prompt
  9.  
  10. import asyncssh
  11.  
  12. # Tell prompt_toolkit to use the asyncio event loop.
  13. use_asyncio_event_loop()
  14.  
  15. class ChatClient:
  16. _clients = []
  17.  
  18. def __init__(self, process):
  19. self._process = process
  20.  
  21. @classmethod
  22. async def handle_client(cls, process):
  23. await cls(process).interact()
  24.  
  25. def write(self, msg):
  26. self._process.stdout.write(msg)
  27.  
  28. def broadcast(self, msg):
  29. for client in self._clients:
  30. if client != self:
  31. client.write(msg)
  32.  
  33. async def interact(self):
  34. self.write('Welcome to chat!nn')
  35.  
  36. self.write('Enter your name: ')
  37. name = (await self._process.stdin.readline()).rstrip('n')
  38.  
  39. self.write('n%d other users are connected.nn' % len(self._clients))
  40.  
  41. self._clients.append(self)
  42. self.broadcast('*** %s has entered chat ***n' % name)
  43.  
  44. try:
  45. ### This works, but it isn't using prompt toolkit...
  46. #async for line in self._process.stdin:
  47. # self.broadcast('%s: %s' % (name, line))
  48. # self._process.stdout.write('chat# ')
  49. while True:
  50. line = await prompt('chat# ', async_=True) # <--- Should use client's stdout
  51. self.broadcast('{0}: {1}'.format(name, line))
  52. except asyncssh.BreakReceived:
  53. pass
  54.  
  55. self.broadcast('*** %s has left chat ***n' % name)
  56. self._clients.remove(self)
  57.  
  58. passwords = {'guest': '', # guest account with no password
  59. 'user123': 'qV2iEadIGV2rw' # password of 'secretpw'
  60. }
  61.  
  62. class CustomSSHServer(asyncssh.SSHServer):
  63. def connection_made(self, conn):
  64. print('SSH connection received from %s.' %
  65. conn.get_extra_info('peername')[0])
  66.  
  67. def connection_lost(self, exc):
  68. if exc:
  69. print('SSH connection error: ' + str(exc), file=sys.stderr)
  70. else:
  71. print('SSH connection closed.')
  72.  
  73. def begin_auth(self, username):
  74. # If the user's password is the empty string, no auth is required
  75. return passwords.get(username) != ''
  76.  
  77. def password_auth_supported(self):
  78. return True
  79.  
  80. def validate_password(self, username, password):
  81. pw = passwords.get(username, '*')
  82. return crypt.crypt(password, pw) == pw
  83.  
  84. async def start_server():
  85. await asyncssh.create_server(CustomSSHServer, '', 8022,
  86. server_host_keys=['ssh_host_key'],
  87. process_factory=ChatClient.handle_client)
  88.  
  89. loop = asyncio.get_event_loop()
  90.  
  91. try:
  92. loop.run_until_complete(start_server())
  93. except (OSError, asyncssh.Error) as exc:
  94. sys.exit('Error starting server: ' + str(exc))
  95.  
  96. loop.run_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement