You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

719 lines
30 KiB

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

Powered by TurnKey Linux.