server.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. """
  19. `.ServerInterface` is an interface to override for server support.
  20. """
  21. import threading
  22. from paramiko import util
  23. from paramiko.common import (
  24. DEBUG,
  25. ERROR,
  26. OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED,
  27. AUTH_FAILED,
  28. AUTH_SUCCESSFUL,
  29. )
  30. from paramiko.py3compat import string_types
  31. class ServerInterface(object):
  32. """
  33. This class defines an interface for controlling the behavior of Paramiko
  34. in server mode.
  35. Methods on this class are called from Paramiko's primary thread, so you
  36. shouldn't do too much work in them. (Certainly nothing that blocks or
  37. sleeps.)
  38. """
  39. def check_channel_request(self, kind, chanid):
  40. """
  41. Determine if a channel request of a given type will be granted, and
  42. return ``OPEN_SUCCEEDED`` or an error code. This method is
  43. called in server mode when the client requests a channel, after
  44. authentication is complete.
  45. If you allow channel requests (and an ssh server that didn't would be
  46. useless), you should also override some of the channel request methods
  47. below, which are used to determine which services will be allowed on
  48. a given channel:
  49. - `check_channel_pty_request`
  50. - `check_channel_shell_request`
  51. - `check_channel_subsystem_request`
  52. - `check_channel_window_change_request`
  53. - `check_channel_x11_request`
  54. - `check_channel_forward_agent_request`
  55. The ``chanid`` parameter is a small number that uniquely identifies the
  56. channel within a `.Transport`. A `.Channel` object is not created
  57. unless this method returns ``OPEN_SUCCEEDED`` -- once a
  58. `.Channel` object is created, you can call `.Channel.get_id` to
  59. retrieve the channel ID.
  60. The return value should either be ``OPEN_SUCCEEDED`` (or
  61. ``0``) to allow the channel request, or one of the following error
  62. codes to reject it:
  63. - ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``
  64. - ``OPEN_FAILED_CONNECT_FAILED``
  65. - ``OPEN_FAILED_UNKNOWN_CHANNEL_TYPE``
  66. - ``OPEN_FAILED_RESOURCE_SHORTAGE``
  67. The default implementation always returns
  68. ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``.
  69. :param str kind:
  70. the kind of channel the client would like to open (usually
  71. ``"session"``).
  72. :param int chanid: ID of the channel
  73. :return: an `int` success or failure code (listed above)
  74. """
  75. return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
  76. def get_allowed_auths(self, username):
  77. """
  78. Return a list of authentication methods supported by the server.
  79. This list is sent to clients attempting to authenticate, to inform them
  80. of authentication methods that might be successful.
  81. The "list" is actually a string of comma-separated names of types of
  82. authentication. Possible values are ``"password"``, ``"publickey"``,
  83. and ``"none"``.
  84. The default implementation always returns ``"password"``.
  85. :param str username: the username requesting authentication.
  86. :return: a comma-separated `str` of authentication types
  87. """
  88. return "password"
  89. def check_auth_none(self, username):
  90. """
  91. Determine if a client may open channels with no (further)
  92. authentication.
  93. Return ``AUTH_FAILED`` if the client must authenticate, or
  94. ``AUTH_SUCCESSFUL`` if it's okay for the client to not
  95. authenticate.
  96. The default implementation always returns ``AUTH_FAILED``.
  97. :param str username: the username of the client.
  98. :return:
  99. ``AUTH_FAILED`` if the authentication fails; ``AUTH_SUCCESSFUL`` if
  100. it succeeds.
  101. :rtype: int
  102. """
  103. return AUTH_FAILED
  104. def check_auth_password(self, username, password):
  105. """
  106. Determine if a given username and password supplied by the client is
  107. acceptable for use in authentication.
  108. Return ``AUTH_FAILED`` if the password is not accepted,
  109. ``AUTH_SUCCESSFUL`` if the password is accepted and completes
  110. the authentication, or ``AUTH_PARTIALLY_SUCCESSFUL`` if your
  111. authentication is stateful, and this key is accepted for
  112. authentication, but more authentication is required. (In this latter
  113. case, `get_allowed_auths` will be called to report to the client what
  114. options it has for continuing the authentication.)
  115. The default implementation always returns ``AUTH_FAILED``.
  116. :param str username: the username of the authenticating client.
  117. :param str password: the password given by the client.
  118. :return:
  119. ``AUTH_FAILED`` if the authentication fails; ``AUTH_SUCCESSFUL`` if
  120. it succeeds; ``AUTH_PARTIALLY_SUCCESSFUL`` if the password auth is
  121. successful, but authentication must continue.
  122. :rtype: int
  123. """
  124. return AUTH_FAILED
  125. def check_auth_publickey(self, username, key):
  126. """
  127. Determine if a given key supplied by the client is acceptable for use
  128. in authentication. You should override this method in server mode to
  129. check the username and key and decide if you would accept a signature
  130. made using this key.
  131. Return ``AUTH_FAILED`` if the key is not accepted,
  132. ``AUTH_SUCCESSFUL`` if the key is accepted and completes the
  133. authentication, or ``AUTH_PARTIALLY_SUCCESSFUL`` if your
  134. authentication is stateful, and this password is accepted for
  135. authentication, but more authentication is required. (In this latter
  136. case, `get_allowed_auths` will be called to report to the client what
  137. options it has for continuing the authentication.)
  138. Note that you don't have to actually verify any key signtature here.
  139. If you're willing to accept the key, Paramiko will do the work of
  140. verifying the client's signature.
  141. The default implementation always returns ``AUTH_FAILED``.
  142. :param str username: the username of the authenticating client
  143. :param .PKey key: the key object provided by the client
  144. :return:
  145. ``AUTH_FAILED`` if the client can't authenticate with this key;
  146. ``AUTH_SUCCESSFUL`` if it can; ``AUTH_PARTIALLY_SUCCESSFUL`` if it
  147. can authenticate with this key but must continue with
  148. authentication
  149. :rtype: int
  150. """
  151. return AUTH_FAILED
  152. def check_auth_interactive(self, username, submethods):
  153. """
  154. Begin an interactive authentication challenge, if supported. You
  155. should override this method in server mode if you want to support the
  156. ``"keyboard-interactive"`` auth type, which requires you to send a
  157. series of questions for the client to answer.
  158. Return ``AUTH_FAILED`` if this auth method isn't supported. Otherwise,
  159. you should return an `.InteractiveQuery` object containing the prompts
  160. and instructions for the user. The response will be sent via a call
  161. to `check_auth_interactive_response`.
  162. The default implementation always returns ``AUTH_FAILED``.
  163. :param str username: the username of the authenticating client
  164. :param str submethods:
  165. a comma-separated list of methods preferred by the client (usually
  166. empty)
  167. :return:
  168. ``AUTH_FAILED`` if this auth method isn't supported; otherwise an
  169. object containing queries for the user
  170. :rtype: int or `.InteractiveQuery`
  171. """
  172. return AUTH_FAILED
  173. def check_auth_interactive_response(self, responses):
  174. """
  175. Continue or finish an interactive authentication challenge, if
  176. supported. You should override this method in server mode if you want
  177. to support the ``"keyboard-interactive"`` auth type.
  178. Return ``AUTH_FAILED`` if the responses are not accepted,
  179. ``AUTH_SUCCESSFUL`` if the responses are accepted and complete
  180. the authentication, or ``AUTH_PARTIALLY_SUCCESSFUL`` if your
  181. authentication is stateful, and this set of responses is accepted for
  182. authentication, but more authentication is required. (In this latter
  183. case, `get_allowed_auths` will be called to report to the client what
  184. options it has for continuing the authentication.)
  185. If you wish to continue interactive authentication with more questions,
  186. you may return an `.InteractiveQuery` object, which should cause the
  187. client to respond with more answers, calling this method again. This
  188. cycle can continue indefinitely.
  189. The default implementation always returns ``AUTH_FAILED``.
  190. :param responses: list of `str` responses from the client
  191. :return:
  192. ``AUTH_FAILED`` if the authentication fails; ``AUTH_SUCCESSFUL`` if
  193. it succeeds; ``AUTH_PARTIALLY_SUCCESSFUL`` if the interactive auth
  194. is successful, but authentication must continue; otherwise an
  195. object containing queries for the user
  196. :rtype: int or `.InteractiveQuery`
  197. """
  198. return AUTH_FAILED
  199. def check_auth_gssapi_with_mic(
  200. self, username, gss_authenticated=AUTH_FAILED, cc_file=None
  201. ):
  202. """
  203. Authenticate the given user to the server if he is a valid krb5
  204. principal.
  205. :param str username: The username of the authenticating client
  206. :param int gss_authenticated: The result of the krb5 authentication
  207. :param str cc_filename: The krb5 client credentials cache filename
  208. :return: ``AUTH_FAILED`` if the user is not authenticated otherwise
  209. ``AUTH_SUCCESSFUL``
  210. :rtype: int
  211. :note: Kerberos credential delegation is not supported.
  212. :see: `.ssh_gss`
  213. :note: : We are just checking in L{AuthHandler} that the given user is
  214. a valid krb5 principal!
  215. We don't check if the krb5 principal is allowed to log in on
  216. the server, because there is no way to do that in python. So
  217. if you develop your own SSH server with paramiko for a cetain
  218. plattform like Linux, you should call C{krb5_kuserok()} in
  219. your local kerberos library to make sure that the
  220. krb5_principal has an account on the server and is allowed to
  221. log in as a user.
  222. :see: http://www.unix.com/man-page/all/3/krb5_kuserok/
  223. """
  224. if gss_authenticated == AUTH_SUCCESSFUL:
  225. return AUTH_SUCCESSFUL
  226. return AUTH_FAILED
  227. def check_auth_gssapi_keyex(
  228. self, username, gss_authenticated=AUTH_FAILED, cc_file=None
  229. ):
  230. """
  231. Authenticate the given user to the server if he is a valid krb5
  232. principal and GSS-API Key Exchange was performed.
  233. If GSS-API Key Exchange was not performed, this authentication method
  234. won't be available.
  235. :param str username: The username of the authenticating client
  236. :param int gss_authenticated: The result of the krb5 authentication
  237. :param str cc_filename: The krb5 client credentials cache filename
  238. :return: ``AUTH_FAILED`` if the user is not authenticated otherwise
  239. ``AUTH_SUCCESSFUL``
  240. :rtype: int
  241. :note: Kerberos credential delegation is not supported.
  242. :see: `.ssh_gss` `.kex_gss`
  243. :note: : We are just checking in L{AuthHandler} that the given user is
  244. a valid krb5 principal!
  245. We don't check if the krb5 principal is allowed to log in on
  246. the server, because there is no way to do that in python. So
  247. if you develop your own SSH server with paramiko for a cetain
  248. plattform like Linux, you should call C{krb5_kuserok()} in
  249. your local kerberos library to make sure that the
  250. krb5_principal has an account on the server and is allowed
  251. to log in as a user.
  252. :see: http://www.unix.com/man-page/all/3/krb5_kuserok/
  253. """
  254. if gss_authenticated == AUTH_SUCCESSFUL:
  255. return AUTH_SUCCESSFUL
  256. return AUTH_FAILED
  257. def enable_auth_gssapi(self):
  258. """
  259. Overwrite this function in your SSH server to enable GSSAPI
  260. authentication.
  261. The default implementation always returns false.
  262. :returns bool: Whether GSSAPI authentication is enabled.
  263. :see: `.ssh_gss`
  264. """
  265. UseGSSAPI = False
  266. return UseGSSAPI
  267. def check_port_forward_request(self, address, port):
  268. """
  269. Handle a request for port forwarding. The client is asking that
  270. connections to the given address and port be forwarded back across
  271. this ssh connection. An address of ``"0.0.0.0"`` indicates a global
  272. address (any address associated with this server) and a port of ``0``
  273. indicates that no specific port is requested (usually the OS will pick
  274. a port).
  275. The default implementation always returns ``False``, rejecting the
  276. port forwarding request. If the request is accepted, you should return
  277. the port opened for listening.
  278. :param str address: the requested address
  279. :param int port: the requested port
  280. :return:
  281. the port number (`int`) that was opened for listening, or ``False``
  282. to reject
  283. """
  284. return False
  285. def cancel_port_forward_request(self, address, port):
  286. """
  287. The client would like to cancel a previous port-forwarding request.
  288. If the given address and port is being forwarded across this ssh
  289. connection, the port should be closed.
  290. :param str address: the forwarded address
  291. :param int port: the forwarded port
  292. """
  293. pass
  294. def check_global_request(self, kind, msg):
  295. """
  296. Handle a global request of the given ``kind``. This method is called
  297. in server mode and client mode, whenever the remote host makes a global
  298. request. If there are any arguments to the request, they will be in
  299. ``msg``.
  300. There aren't any useful global requests defined, aside from port
  301. forwarding, so usually this type of request is an extension to the
  302. protocol.
  303. If the request was successful and you would like to return contextual
  304. data to the remote host, return a tuple. Items in the tuple will be
  305. sent back with the successful result. (Note that the items in the
  306. tuple can only be strings, ints, longs, or bools.)
  307. The default implementation always returns ``False``, indicating that it
  308. does not support any global requests.
  309. .. note:: Port forwarding requests are handled separately, in
  310. `check_port_forward_request`.
  311. :param str kind: the kind of global request being made.
  312. :param .Message msg: any extra arguments to the request.
  313. :return:
  314. ``True`` or a `tuple` of data if the request was granted; ``False``
  315. otherwise.
  316. """
  317. return False
  318. # ...Channel requests...
  319. def check_channel_pty_request(
  320. self, channel, term, width, height, pixelwidth, pixelheight, modes
  321. ):
  322. """
  323. Determine if a pseudo-terminal of the given dimensions (usually
  324. requested for shell access) can be provided on the given channel.
  325. The default implementation always returns ``False``.
  326. :param .Channel channel: the `.Channel` the pty request arrived on.
  327. :param str term: type of terminal requested (for example, ``"vt100"``).
  328. :param int width: width of screen in characters.
  329. :param int height: height of screen in characters.
  330. :param int pixelwidth:
  331. width of screen in pixels, if known (may be ``0`` if unknown).
  332. :param int pixelheight:
  333. height of screen in pixels, if known (may be ``0`` if unknown).
  334. :return:
  335. ``True`` if the pseudo-terminal has been allocated; ``False``
  336. otherwise.
  337. """
  338. return False
  339. def check_channel_shell_request(self, channel):
  340. """
  341. Determine if a shell will be provided to the client on the given
  342. channel. If this method returns ``True``, the channel should be
  343. connected to the stdin/stdout of a shell (or something that acts like
  344. a shell).
  345. The default implementation always returns ``False``.
  346. :param .Channel channel: the `.Channel` the request arrived on.
  347. :return:
  348. ``True`` if this channel is now hooked up to a shell; ``False`` if
  349. a shell can't or won't be provided.
  350. """
  351. return False
  352. def check_channel_exec_request(self, channel, command):
  353. """
  354. Determine if a shell command will be executed for the client. If this
  355. method returns ``True``, the channel should be connected to the stdin,
  356. stdout, and stderr of the shell command.
  357. The default implementation always returns ``False``.
  358. :param .Channel channel: the `.Channel` the request arrived on.
  359. :param str command: the command to execute.
  360. :return:
  361. ``True`` if this channel is now hooked up to the stdin, stdout, and
  362. stderr of the executing command; ``False`` if the command will not
  363. be executed.
  364. .. versionadded:: 1.1
  365. """
  366. return False
  367. def check_channel_subsystem_request(self, channel, name):
  368. """
  369. Determine if a requested subsystem will be provided to the client on
  370. the given channel. If this method returns ``True``, all future I/O
  371. through this channel will be assumed to be connected to the requested
  372. subsystem. An example of a subsystem is ``sftp``.
  373. The default implementation checks for a subsystem handler assigned via
  374. `.Transport.set_subsystem_handler`.
  375. If one has been set, the handler is invoked and this method returns
  376. ``True``. Otherwise it returns ``False``.
  377. .. note:: Because the default implementation uses the `.Transport` to
  378. identify valid subsystems, you probably won't need to override this
  379. method.
  380. :param .Channel channel: the `.Channel` the pty request arrived on.
  381. :param str name: name of the requested subsystem.
  382. :return:
  383. ``True`` if this channel is now hooked up to the requested
  384. subsystem; ``False`` if that subsystem can't or won't be provided.
  385. """
  386. transport = channel.get_transport()
  387. handler_class, larg, kwarg = transport._get_subsystem_handler(name)
  388. if handler_class is None:
  389. return False
  390. handler = handler_class(channel, name, self, *larg, **kwarg)
  391. handler.start()
  392. return True
  393. def check_channel_window_change_request(
  394. self, channel, width, height, pixelwidth, pixelheight
  395. ):
  396. """
  397. Determine if the pseudo-terminal on the given channel can be resized.
  398. This only makes sense if a pty was previously allocated on it.
  399. The default implementation always returns ``False``.
  400. :param .Channel channel: the `.Channel` the pty request arrived on.
  401. :param int width: width of screen in characters.
  402. :param int height: height of screen in characters.
  403. :param int pixelwidth:
  404. width of screen in pixels, if known (may be ``0`` if unknown).
  405. :param int pixelheight:
  406. height of screen in pixels, if known (may be ``0`` if unknown).
  407. :return: ``True`` if the terminal was resized; ``False`` if not.
  408. """
  409. return False
  410. def check_channel_x11_request(
  411. self,
  412. channel,
  413. single_connection,
  414. auth_protocol,
  415. auth_cookie,
  416. screen_number,
  417. ):
  418. """
  419. Determine if the client will be provided with an X11 session. If this
  420. method returns ``True``, X11 applications should be routed through new
  421. SSH channels, using `.Transport.open_x11_channel`.
  422. The default implementation always returns ``False``.
  423. :param .Channel channel: the `.Channel` the X11 request arrived on
  424. :param bool single_connection:
  425. ``True`` if only a single X11 channel should be opened, else
  426. ``False``.
  427. :param str auth_protocol: the protocol used for X11 authentication
  428. :param str auth_cookie: the cookie used to authenticate to X11
  429. :param int screen_number: the number of the X11 screen to connect to
  430. :return: ``True`` if the X11 session was opened; ``False`` if not
  431. """
  432. return False
  433. def check_channel_forward_agent_request(self, channel):
  434. """
  435. Determine if the client will be provided with an forward agent session.
  436. If this method returns ``True``, the server will allow SSH Agent
  437. forwarding.
  438. The default implementation always returns ``False``.
  439. :param .Channel channel: the `.Channel` the request arrived on
  440. :return: ``True`` if the AgentForward was loaded; ``False`` if not
  441. """
  442. return False
  443. def check_channel_direct_tcpip_request(self, chanid, origin, destination):
  444. """
  445. Determine if a local port forwarding channel will be granted, and
  446. return ``OPEN_SUCCEEDED`` or an error code. This method is
  447. called in server mode when the client requests a channel, after
  448. authentication is complete.
  449. The ``chanid`` parameter is a small number that uniquely identifies the
  450. channel within a `.Transport`. A `.Channel` object is not created
  451. unless this method returns ``OPEN_SUCCEEDED`` -- once a
  452. `.Channel` object is created, you can call `.Channel.get_id` to
  453. retrieve the channel ID.
  454. The origin and destination parameters are (ip_address, port) tuples
  455. that correspond to both ends of the TCP connection in the forwarding
  456. tunnel.
  457. The return value should either be ``OPEN_SUCCEEDED`` (or
  458. ``0``) to allow the channel request, or one of the following error
  459. codes to reject it:
  460. - ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``
  461. - ``OPEN_FAILED_CONNECT_FAILED``
  462. - ``OPEN_FAILED_UNKNOWN_CHANNEL_TYPE``
  463. - ``OPEN_FAILED_RESOURCE_SHORTAGE``
  464. The default implementation always returns
  465. ``OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED``.
  466. :param int chanid: ID of the channel
  467. :param tuple origin:
  468. 2-tuple containing the IP address and port of the originator
  469. (client side)
  470. :param tuple destination:
  471. 2-tuple containing the IP address and port of the destination
  472. (server side)
  473. :return: an `int` success or failure code (listed above)
  474. """
  475. return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
  476. def check_channel_env_request(self, channel, name, value):
  477. """
  478. Check whether a given environment variable can be specified for the
  479. given channel. This method should return ``True`` if the server
  480. is willing to set the specified environment variable. Note that
  481. some environment variables (e.g., PATH) can be exceedingly
  482. dangerous, so blindly allowing the client to set the environment
  483. is almost certainly not a good idea.
  484. The default implementation always returns ``False``.
  485. :param channel: the `.Channel` the env request arrived on
  486. :param str name: name
  487. :param str value: Channel value
  488. :returns: A boolean
  489. """
  490. return False
  491. def get_banner(self):
  492. """
  493. A pre-login banner to display to the user. The message may span
  494. multiple lines separated by crlf pairs. The language should be in
  495. rfc3066 style, for example: en-US
  496. The default implementation always returns ``(None, None)``.
  497. :returns: A tuple containing the banner and language code.
  498. .. versionadded:: 2.3
  499. """
  500. return (None, None)
  501. class InteractiveQuery(object):
  502. """
  503. A query (set of prompts) for a user during interactive authentication.
  504. """
  505. def __init__(self, name="", instructions="", *prompts):
  506. """
  507. Create a new interactive query to send to the client. The name and
  508. instructions are optional, but are generally displayed to the end
  509. user. A list of prompts may be included, or they may be added via
  510. the `add_prompt` method.
  511. :param str name: name of this query
  512. :param str instructions:
  513. user instructions (usually short) about this query
  514. :param str prompts: one or more authentication prompts
  515. """
  516. self.name = name
  517. self.instructions = instructions
  518. self.prompts = []
  519. for x in prompts:
  520. if isinstance(x, string_types):
  521. self.add_prompt(x)
  522. else:
  523. self.add_prompt(x[0], x[1])
  524. def add_prompt(self, prompt, echo=True):
  525. """
  526. Add a prompt to this query. The prompt should be a (reasonably short)
  527. string. Multiple prompts can be added to the same query.
  528. :param str prompt: the user prompt
  529. :param bool echo:
  530. ``True`` (default) if the user's response should be echoed;
  531. ``False`` if not (for a password or similar)
  532. """
  533. self.prompts.append((prompt, echo))
  534. class SubsystemHandler(threading.Thread):
  535. """
  536. Handler for a subsytem in server mode. If you create a subclass of this
  537. class and pass it to `.Transport.set_subsystem_handler`, an object of this
  538. class will be created for each request for this subsystem. Each new object
  539. will be executed within its own new thread by calling `start_subsystem`.
  540. When that method completes, the channel is closed.
  541. For example, if you made a subclass ``MP3Handler`` and registered it as the
  542. handler for subsystem ``"mp3"``, then whenever a client has successfully
  543. authenticated and requests subsytem ``"mp3"``, an object of class
  544. ``MP3Handler`` will be created, and `start_subsystem` will be called on
  545. it from a new thread.
  546. """
  547. def __init__(self, channel, name, server):
  548. """
  549. Create a new handler for a channel. This is used by `.ServerInterface`
  550. to start up a new handler when a channel requests this subsystem. You
  551. don't need to override this method, but if you do, be sure to pass the
  552. ``channel`` and ``name`` parameters through to the original
  553. ``__init__`` method here.
  554. :param .Channel channel: the channel associated with this
  555. subsystem request.
  556. :param str name: name of the requested subsystem.
  557. :param .ServerInterface server:
  558. the server object for the session that started this subsystem
  559. """
  560. threading.Thread.__init__(self, target=self._run)
  561. self.__channel = channel
  562. self.__transport = channel.get_transport()
  563. self.__name = name
  564. self.__server = server
  565. def get_server(self):
  566. """
  567. Return the `.ServerInterface` object associated with this channel and
  568. subsystem.
  569. """
  570. return self.__server
  571. def _run(self):
  572. try:
  573. self.__transport._log(
  574. DEBUG, "Starting handler for subsystem {}".format(self.__name)
  575. )
  576. self.start_subsystem(self.__name, self.__transport, self.__channel)
  577. except Exception as e:
  578. self.__transport._log(
  579. ERROR,
  580. 'Exception in subsystem handler for "{}": {}'.format(
  581. self.__name, e
  582. ),
  583. )
  584. self.__transport._log(ERROR, util.tb_strings())
  585. try:
  586. self.finish_subsystem()
  587. except:
  588. pass
  589. def start_subsystem(self, name, transport, channel):
  590. """
  591. Process an ssh subsystem in server mode. This method is called on a
  592. new object (and in a new thread) for each subsystem request. It is
  593. assumed that all subsystem logic will take place here, and when the
  594. subsystem is finished, this method will return. After this method
  595. returns, the channel is closed.
  596. The combination of ``transport`` and ``channel`` are unique; this
  597. handler corresponds to exactly one `.Channel` on one `.Transport`.
  598. .. note::
  599. It is the responsibility of this method to exit if the underlying
  600. `.Transport` is closed. This can be done by checking
  601. `.Transport.is_active` or noticing an EOF on the `.Channel`. If
  602. this method loops forever without checking for this case, your
  603. Python interpreter may refuse to exit because this thread will
  604. still be running.
  605. :param str name: name of the requested subsystem.
  606. :param .Transport transport: the server-mode `.Transport`.
  607. :param .Channel channel: the channel associated with this subsystem
  608. request.
  609. """
  610. pass
  611. def finish_subsystem(self):
  612. """
  613. Perform any cleanup at the end of a subsystem. The default
  614. implementation just closes the channel.
  615. .. versionadded:: 1.1
  616. """
  617. self.__channel.close()