channel.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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. Abstraction for an SSH2 channel.
  20. """
  21. import binascii
  22. import os
  23. import socket
  24. import time
  25. import threading
  26. # TODO: switch as much of py3compat.py to 'six' as possible, then use six.wraps
  27. from functools import wraps
  28. from paramiko import util
  29. from paramiko.common import (
  30. cMSG_CHANNEL_REQUEST,
  31. cMSG_CHANNEL_WINDOW_ADJUST,
  32. cMSG_CHANNEL_DATA,
  33. cMSG_CHANNEL_EXTENDED_DATA,
  34. DEBUG,
  35. ERROR,
  36. cMSG_CHANNEL_SUCCESS,
  37. cMSG_CHANNEL_FAILURE,
  38. cMSG_CHANNEL_EOF,
  39. cMSG_CHANNEL_CLOSE,
  40. )
  41. from paramiko.message import Message
  42. from paramiko.py3compat import bytes_types
  43. from paramiko.ssh_exception import SSHException
  44. from paramiko.file import BufferedFile
  45. from paramiko.buffered_pipe import BufferedPipe, PipeTimeout
  46. from paramiko import pipe
  47. from paramiko.util import ClosingContextManager
  48. def open_only(func):
  49. """
  50. Decorator for `.Channel` methods which performs an openness check.
  51. :raises:
  52. `.SSHException` -- If the wrapped method is called on an unopened
  53. `.Channel`.
  54. """
  55. @wraps(func)
  56. def _check(self, *args, **kwds):
  57. if (
  58. self.closed
  59. or self.eof_received
  60. or self.eof_sent
  61. or not self.active
  62. ):
  63. raise SSHException("Channel is not open")
  64. return func(self, *args, **kwds)
  65. return _check
  66. class Channel(ClosingContextManager):
  67. """
  68. A secure tunnel across an SSH `.Transport`. A Channel is meant to behave
  69. like a socket, and has an API that should be indistinguishable from the
  70. Python socket API.
  71. Because SSH2 has a windowing kind of flow control, if you stop reading data
  72. from a Channel and its buffer fills up, the server will be unable to send
  73. you any more data until you read some of it. (This won't affect other
  74. channels on the same transport -- all channels on a single transport are
  75. flow-controlled independently.) Similarly, if the server isn't reading
  76. data you send, calls to `send` may block, unless you set a timeout. This
  77. is exactly like a normal network socket, so it shouldn't be too surprising.
  78. Instances of this class may be used as context managers.
  79. """
  80. def __init__(self, chanid):
  81. """
  82. Create a new channel. The channel is not associated with any
  83. particular session or `.Transport` until the Transport attaches it.
  84. Normally you would only call this method from the constructor of a
  85. subclass of `.Channel`.
  86. :param int chanid:
  87. the ID of this channel, as passed by an existing `.Transport`.
  88. """
  89. #: Channel ID
  90. self.chanid = chanid
  91. #: Remote channel ID
  92. self.remote_chanid = 0
  93. #: `.Transport` managing this channel
  94. self.transport = None
  95. #: Whether the connection is presently active
  96. self.active = False
  97. self.eof_received = 0
  98. self.eof_sent = 0
  99. self.in_buffer = BufferedPipe()
  100. self.in_stderr_buffer = BufferedPipe()
  101. self.timeout = None
  102. #: Whether the connection has been closed
  103. self.closed = False
  104. self.ultra_debug = False
  105. self.lock = threading.Lock()
  106. self.out_buffer_cv = threading.Condition(self.lock)
  107. self.in_window_size = 0
  108. self.out_window_size = 0
  109. self.in_max_packet_size = 0
  110. self.out_max_packet_size = 0
  111. self.in_window_threshold = 0
  112. self.in_window_sofar = 0
  113. self.status_event = threading.Event()
  114. self._name = str(chanid)
  115. self.logger = util.get_logger("paramiko.transport")
  116. self._pipe = None
  117. self.event = threading.Event()
  118. self.event_ready = False
  119. self.combine_stderr = False
  120. self.exit_status = -1
  121. self.origin_addr = None
  122. def __del__(self):
  123. try:
  124. self.close()
  125. except:
  126. pass
  127. def __repr__(self):
  128. """
  129. Return a string representation of this object, for debugging.
  130. """
  131. out = "<paramiko.Channel {}".format(self.chanid)
  132. if self.closed:
  133. out += " (closed)"
  134. elif self.active:
  135. if self.eof_received:
  136. out += " (EOF received)"
  137. if self.eof_sent:
  138. out += " (EOF sent)"
  139. out += " (open) window={}".format(self.out_window_size)
  140. if len(self.in_buffer) > 0:
  141. out += " in-buffer={}".format(len(self.in_buffer))
  142. out += " -> " + repr(self.transport)
  143. out += ">"
  144. return out
  145. @open_only
  146. def get_pty(
  147. self,
  148. term="vt100",
  149. width=80,
  150. height=24,
  151. width_pixels=0,
  152. height_pixels=0,
  153. ):
  154. """
  155. Request a pseudo-terminal from the server. This is usually used right
  156. after creating a client channel, to ask the server to provide some
  157. basic terminal semantics for a shell invoked with `invoke_shell`.
  158. It isn't necessary (or desirable) to call this method if you're going
  159. to execute a single command with `exec_command`.
  160. :param str term: the terminal type to emulate
  161. (for example, ``'vt100'``)
  162. :param int width: width (in characters) of the terminal screen
  163. :param int height: height (in characters) of the terminal screen
  164. :param int width_pixels: width (in pixels) of the terminal screen
  165. :param int height_pixels: height (in pixels) of the terminal screen
  166. :raises:
  167. `.SSHException` -- if the request was rejected or the channel was
  168. closed
  169. """
  170. m = Message()
  171. m.add_byte(cMSG_CHANNEL_REQUEST)
  172. m.add_int(self.remote_chanid)
  173. m.add_string("pty-req")
  174. m.add_boolean(True)
  175. m.add_string(term)
  176. m.add_int(width)
  177. m.add_int(height)
  178. m.add_int(width_pixels)
  179. m.add_int(height_pixels)
  180. m.add_string(bytes())
  181. self._event_pending()
  182. self.transport._send_user_message(m)
  183. self._wait_for_event()
  184. @open_only
  185. def invoke_shell(self):
  186. """
  187. Request an interactive shell session on this channel. If the server
  188. allows it, the channel will then be directly connected to the stdin,
  189. stdout, and stderr of the shell.
  190. Normally you would call `get_pty` before this, in which case the
  191. shell will operate through the pty, and the channel will be connected
  192. to the stdin and stdout of the pty.
  193. When the shell exits, the channel will be closed and can't be reused.
  194. You must open a new channel if you wish to open another shell.
  195. :raises:
  196. `.SSHException` -- if the request was rejected or the channel was
  197. closed
  198. """
  199. m = Message()
  200. m.add_byte(cMSG_CHANNEL_REQUEST)
  201. m.add_int(self.remote_chanid)
  202. m.add_string("shell")
  203. m.add_boolean(True)
  204. self._event_pending()
  205. self.transport._send_user_message(m)
  206. self._wait_for_event()
  207. @open_only
  208. def exec_command(self, command):
  209. """
  210. Execute a command on the server. If the server allows it, the channel
  211. will then be directly connected to the stdin, stdout, and stderr of
  212. the command being executed.
  213. When the command finishes executing, the channel will be closed and
  214. can't be reused. You must open a new channel if you wish to execute
  215. another command.
  216. :param str command: a shell command to execute.
  217. :raises:
  218. `.SSHException` -- if the request was rejected or the channel was
  219. closed
  220. """
  221. m = Message()
  222. m.add_byte(cMSG_CHANNEL_REQUEST)
  223. m.add_int(self.remote_chanid)
  224. m.add_string("exec")
  225. m.add_boolean(True)
  226. m.add_string(command)
  227. self._event_pending()
  228. self.transport._send_user_message(m)
  229. self._wait_for_event()
  230. @open_only
  231. def invoke_subsystem(self, subsystem):
  232. """
  233. Request a subsystem on the server (for example, ``sftp``). If the
  234. server allows it, the channel will then be directly connected to the
  235. requested subsystem.
  236. When the subsystem finishes, the channel will be closed and can't be
  237. reused.
  238. :param str subsystem: name of the subsystem being requested.
  239. :raises:
  240. `.SSHException` -- if the request was rejected or the channel was
  241. closed
  242. """
  243. m = Message()
  244. m.add_byte(cMSG_CHANNEL_REQUEST)
  245. m.add_int(self.remote_chanid)
  246. m.add_string("subsystem")
  247. m.add_boolean(True)
  248. m.add_string(subsystem)
  249. self._event_pending()
  250. self.transport._send_user_message(m)
  251. self._wait_for_event()
  252. @open_only
  253. def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0):
  254. """
  255. Resize the pseudo-terminal. This can be used to change the width and
  256. height of the terminal emulation created in a previous `get_pty` call.
  257. :param int width: new width (in characters) of the terminal screen
  258. :param int height: new height (in characters) of the terminal screen
  259. :param int width_pixels: new width (in pixels) of the terminal screen
  260. :param int height_pixels: new height (in pixels) of the terminal screen
  261. :raises:
  262. `.SSHException` -- if the request was rejected or the channel was
  263. closed
  264. """
  265. m = Message()
  266. m.add_byte(cMSG_CHANNEL_REQUEST)
  267. m.add_int(self.remote_chanid)
  268. m.add_string("window-change")
  269. m.add_boolean(False)
  270. m.add_int(width)
  271. m.add_int(height)
  272. m.add_int(width_pixels)
  273. m.add_int(height_pixels)
  274. self.transport._send_user_message(m)
  275. @open_only
  276. def update_environment(self, environment):
  277. """
  278. Updates this channel's remote shell environment.
  279. .. note::
  280. This operation is additive - i.e. the current environment is not
  281. reset before the given environment variables are set.
  282. .. warning::
  283. Servers may silently reject some environment variables; see the
  284. warning in `set_environment_variable` for details.
  285. :param dict environment:
  286. a dictionary containing the name and respective values to set
  287. :raises:
  288. `.SSHException` -- if any of the environment variables was rejected
  289. by the server or the channel was closed
  290. """
  291. for name, value in environment.items():
  292. try:
  293. self.set_environment_variable(name, value)
  294. except SSHException as e:
  295. err = 'Failed to set environment variable "{}".'
  296. raise SSHException(err.format(name), e)
  297. @open_only
  298. def set_environment_variable(self, name, value):
  299. """
  300. Set the value of an environment variable.
  301. .. warning::
  302. The server may reject this request depending on its ``AcceptEnv``
  303. setting; such rejections will fail silently (which is common client
  304. practice for this particular request type). Make sure you
  305. understand your server's configuration before using!
  306. :param str name: name of the environment variable
  307. :param str value: value of the environment variable
  308. :raises:
  309. `.SSHException` -- if the request was rejected or the channel was
  310. closed
  311. """
  312. m = Message()
  313. m.add_byte(cMSG_CHANNEL_REQUEST)
  314. m.add_int(self.remote_chanid)
  315. m.add_string("env")
  316. m.add_boolean(False)
  317. m.add_string(name)
  318. m.add_string(value)
  319. self.transport._send_user_message(m)
  320. def exit_status_ready(self):
  321. """
  322. Return true if the remote process has exited and returned an exit
  323. status. You may use this to poll the process status if you don't
  324. want to block in `recv_exit_status`. Note that the server may not
  325. return an exit status in some cases (like bad servers).
  326. :return:
  327. ``True`` if `recv_exit_status` will return immediately, else
  328. ``False``.
  329. .. versionadded:: 1.7.3
  330. """
  331. return self.closed or self.status_event.is_set()
  332. def recv_exit_status(self):
  333. """
  334. Return the exit status from the process on the server. This is
  335. mostly useful for retrieving the results of an `exec_command`.
  336. If the command hasn't finished yet, this method will wait until
  337. it does, or until the channel is closed. If no exit status is
  338. provided by the server, -1 is returned.
  339. .. warning::
  340. In some situations, receiving remote output larger than the current
  341. `.Transport` or session's ``window_size`` (e.g. that set by the
  342. ``default_window_size`` kwarg for `.Transport.__init__`) will cause
  343. `.recv_exit_status` to hang indefinitely if it is called prior to a
  344. sufficiently large `.Channel.recv` (or if there are no threads
  345. calling `.Channel.recv` in the background).
  346. In these cases, ensuring that `.recv_exit_status` is called *after*
  347. `.Channel.recv` (or, again, using threads) can avoid the hang.
  348. :return: the exit code (as an `int`) of the process on the server.
  349. .. versionadded:: 1.2
  350. """
  351. self.status_event.wait()
  352. assert self.status_event.is_set()
  353. return self.exit_status
  354. def send_exit_status(self, status):
  355. """
  356. Send the exit status of an executed command to the client. (This
  357. really only makes sense in server mode.) Many clients expect to
  358. get some sort of status code back from an executed command after
  359. it completes.
  360. :param int status: the exit code of the process
  361. .. versionadded:: 1.2
  362. """
  363. # in many cases, the channel will not still be open here.
  364. # that's fine.
  365. m = Message()
  366. m.add_byte(cMSG_CHANNEL_REQUEST)
  367. m.add_int(self.remote_chanid)
  368. m.add_string("exit-status")
  369. m.add_boolean(False)
  370. m.add_int(status)
  371. self.transport._send_user_message(m)
  372. @open_only
  373. def request_x11(
  374. self,
  375. screen_number=0,
  376. auth_protocol=None,
  377. auth_cookie=None,
  378. single_connection=False,
  379. handler=None,
  380. ):
  381. """
  382. Request an x11 session on this channel. If the server allows it,
  383. further x11 requests can be made from the server to the client,
  384. when an x11 application is run in a shell session.
  385. From :rfc:`4254`::
  386. It is RECOMMENDED that the 'x11 authentication cookie' that is
  387. sent be a fake, random cookie, and that the cookie be checked and
  388. replaced by the real cookie when a connection request is received.
  389. If you omit the auth_cookie, a new secure random 128-bit value will be
  390. generated, used, and returned. You will need to use this value to
  391. verify incoming x11 requests and replace them with the actual local
  392. x11 cookie (which requires some knowledge of the x11 protocol).
  393. If a handler is passed in, the handler is called from another thread
  394. whenever a new x11 connection arrives. The default handler queues up
  395. incoming x11 connections, which may be retrieved using
  396. `.Transport.accept`. The handler's calling signature is::
  397. handler(channel: Channel, (address: str, port: int))
  398. :param int screen_number: the x11 screen number (0, 10, etc.)
  399. :param str auth_protocol:
  400. the name of the X11 authentication method used; if none is given,
  401. ``"MIT-MAGIC-COOKIE-1"`` is used
  402. :param str auth_cookie:
  403. hexadecimal string containing the x11 auth cookie; if none is
  404. given, a secure random 128-bit value is generated
  405. :param bool single_connection:
  406. if True, only a single x11 connection will be forwarded (by
  407. default, any number of x11 connections can arrive over this
  408. session)
  409. :param handler:
  410. an optional callable handler to use for incoming X11 connections
  411. :return: the auth_cookie used
  412. """
  413. if auth_protocol is None:
  414. auth_protocol = "MIT-MAGIC-COOKIE-1"
  415. if auth_cookie is None:
  416. auth_cookie = binascii.hexlify(os.urandom(16))
  417. m = Message()
  418. m.add_byte(cMSG_CHANNEL_REQUEST)
  419. m.add_int(self.remote_chanid)
  420. m.add_string("x11-req")
  421. m.add_boolean(True)
  422. m.add_boolean(single_connection)
  423. m.add_string(auth_protocol)
  424. m.add_string(auth_cookie)
  425. m.add_int(screen_number)
  426. self._event_pending()
  427. self.transport._send_user_message(m)
  428. self._wait_for_event()
  429. self.transport._set_x11_handler(handler)
  430. return auth_cookie
  431. @open_only
  432. def request_forward_agent(self, handler):
  433. """
  434. Request for a forward SSH Agent on this channel.
  435. This is only valid for an ssh-agent from OpenSSH !!!
  436. :param handler:
  437. a required callable handler to use for incoming SSH Agent
  438. connections
  439. :return: True if we are ok, else False
  440. (at that time we always return ok)
  441. :raises: SSHException in case of channel problem.
  442. """
  443. m = Message()
  444. m.add_byte(cMSG_CHANNEL_REQUEST)
  445. m.add_int(self.remote_chanid)
  446. m.add_string("auth-agent-req@openssh.com")
  447. m.add_boolean(False)
  448. self.transport._send_user_message(m)
  449. self.transport._set_forward_agent_handler(handler)
  450. return True
  451. def get_transport(self):
  452. """
  453. Return the `.Transport` associated with this channel.
  454. """
  455. return self.transport
  456. def set_name(self, name):
  457. """
  458. Set a name for this channel. Currently it's only used to set the name
  459. of the channel in logfile entries. The name can be fetched with the
  460. `get_name` method.
  461. :param str name: new channel name
  462. """
  463. self._name = name
  464. def get_name(self):
  465. """
  466. Get the name of this channel that was previously set by `set_name`.
  467. """
  468. return self._name
  469. def get_id(self):
  470. """
  471. Return the `int` ID # for this channel.
  472. The channel ID is unique across a `.Transport` and usually a small
  473. number. It's also the number passed to
  474. `.ServerInterface.check_channel_request` when determining whether to
  475. accept a channel request in server mode.
  476. """
  477. return self.chanid
  478. def set_combine_stderr(self, combine):
  479. """
  480. Set whether stderr should be combined into stdout on this channel.
  481. The default is ``False``, but in some cases it may be convenient to
  482. have both streams combined.
  483. If this is ``False``, and `exec_command` is called (or ``invoke_shell``
  484. with no pty), output to stderr will not show up through the `recv`
  485. and `recv_ready` calls. You will have to use `recv_stderr` and
  486. `recv_stderr_ready` to get stderr output.
  487. If this is ``True``, data will never show up via `recv_stderr` or
  488. `recv_stderr_ready`.
  489. :param bool combine:
  490. ``True`` if stderr output should be combined into stdout on this
  491. channel.
  492. :return: the previous setting (a `bool`).
  493. .. versionadded:: 1.1
  494. """
  495. data = bytes()
  496. self.lock.acquire()
  497. try:
  498. old = self.combine_stderr
  499. self.combine_stderr = combine
  500. if combine and not old:
  501. # copy old stderr buffer into primary buffer
  502. data = self.in_stderr_buffer.empty()
  503. finally:
  504. self.lock.release()
  505. if len(data) > 0:
  506. self._feed(data)
  507. return old
  508. # ...socket API...
  509. def settimeout(self, timeout):
  510. """
  511. Set a timeout on blocking read/write operations. The ``timeout``
  512. argument can be a nonnegative float expressing seconds, or ``None``.
  513. If a float is given, subsequent channel read/write operations will
  514. raise a timeout exception if the timeout period value has elapsed
  515. before the operation has completed. Setting a timeout of ``None``
  516. disables timeouts on socket operations.
  517. ``chan.settimeout(0.0)`` is equivalent to ``chan.setblocking(0)``;
  518. ``chan.settimeout(None)`` is equivalent to ``chan.setblocking(1)``.
  519. :param float timeout:
  520. seconds to wait for a pending read/write operation before raising
  521. ``socket.timeout``, or ``None`` for no timeout.
  522. """
  523. self.timeout = timeout
  524. def gettimeout(self):
  525. """
  526. Returns the timeout in seconds (as a float) associated with socket
  527. operations, or ``None`` if no timeout is set. This reflects the last
  528. call to `setblocking` or `settimeout`.
  529. """
  530. return self.timeout
  531. def setblocking(self, blocking):
  532. """
  533. Set blocking or non-blocking mode of the channel: if ``blocking`` is 0,
  534. the channel is set to non-blocking mode; otherwise it's set to blocking
  535. mode. Initially all channels are in blocking mode.
  536. In non-blocking mode, if a `recv` call doesn't find any data, or if a
  537. `send` call can't immediately dispose of the data, an error exception
  538. is raised. In blocking mode, the calls block until they can proceed. An
  539. EOF condition is considered "immediate data" for `recv`, so if the
  540. channel is closed in the read direction, it will never block.
  541. ``chan.setblocking(0)`` is equivalent to ``chan.settimeout(0)``;
  542. ``chan.setblocking(1)`` is equivalent to ``chan.settimeout(None)``.
  543. :param int blocking:
  544. 0 to set non-blocking mode; non-0 to set blocking mode.
  545. """
  546. if blocking:
  547. self.settimeout(None)
  548. else:
  549. self.settimeout(0.0)
  550. def getpeername(self):
  551. """
  552. Return the address of the remote side of this Channel, if possible.
  553. This simply wraps `.Transport.getpeername`, used to provide enough of a
  554. socket-like interface to allow asyncore to work. (asyncore likes to
  555. call ``'getpeername'``.)
  556. """
  557. return self.transport.getpeername()
  558. def close(self):
  559. """
  560. Close the channel. All future read/write operations on the channel
  561. will fail. The remote end will receive no more data (after queued data
  562. is flushed). Channels are automatically closed when their `.Transport`
  563. is closed or when they are garbage collected.
  564. """
  565. self.lock.acquire()
  566. try:
  567. # only close the pipe when the user explicitly closes the channel.
  568. # otherwise they will get unpleasant surprises. (and do it before
  569. # checking self.closed, since the remote host may have already
  570. # closed the connection.)
  571. if self._pipe is not None:
  572. self._pipe.close()
  573. self._pipe = None
  574. if not self.active or self.closed:
  575. return
  576. msgs = self._close_internal()
  577. finally:
  578. self.lock.release()
  579. for m in msgs:
  580. if m is not None:
  581. self.transport._send_user_message(m)
  582. def recv_ready(self):
  583. """
  584. Returns true if data is buffered and ready to be read from this
  585. channel. A ``False`` result does not mean that the channel has closed;
  586. it means you may need to wait before more data arrives.
  587. :return:
  588. ``True`` if a `recv` call on this channel would immediately return
  589. at least one byte; ``False`` otherwise.
  590. """
  591. return self.in_buffer.read_ready()
  592. def recv(self, nbytes):
  593. """
  594. Receive data from the channel. The return value is a string
  595. representing the data received. The maximum amount of data to be
  596. received at once is specified by ``nbytes``. If a string of
  597. length zero is returned, the channel stream has closed.
  598. :param int nbytes: maximum number of bytes to read.
  599. :return: received data, as a ``str``/``bytes``.
  600. :raises socket.timeout:
  601. if no data is ready before the timeout set by `settimeout`.
  602. """
  603. try:
  604. out = self.in_buffer.read(nbytes, self.timeout)
  605. except PipeTimeout:
  606. raise socket.timeout()
  607. ack = self._check_add_window(len(out))
  608. # no need to hold the channel lock when sending this
  609. if ack > 0:
  610. m = Message()
  611. m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST)
  612. m.add_int(self.remote_chanid)
  613. m.add_int(ack)
  614. self.transport._send_user_message(m)
  615. return out
  616. def recv_stderr_ready(self):
  617. """
  618. Returns true if data is buffered and ready to be read from this
  619. channel's stderr stream. Only channels using `exec_command` or
  620. `invoke_shell` without a pty will ever have data on the stderr
  621. stream.
  622. :return:
  623. ``True`` if a `recv_stderr` call on this channel would immediately
  624. return at least one byte; ``False`` otherwise.
  625. .. versionadded:: 1.1
  626. """
  627. return self.in_stderr_buffer.read_ready()
  628. def recv_stderr(self, nbytes):
  629. """
  630. Receive data from the channel's stderr stream. Only channels using
  631. `exec_command` or `invoke_shell` without a pty will ever have data
  632. on the stderr stream. The return value is a string representing the
  633. data received. The maximum amount of data to be received at once is
  634. specified by ``nbytes``. If a string of length zero is returned, the
  635. channel stream has closed.
  636. :param int nbytes: maximum number of bytes to read.
  637. :return: received data as a `str`
  638. :raises socket.timeout: if no data is ready before the timeout set by
  639. `settimeout`.
  640. .. versionadded:: 1.1
  641. """
  642. try:
  643. out = self.in_stderr_buffer.read(nbytes, self.timeout)
  644. except PipeTimeout:
  645. raise socket.timeout()
  646. ack = self._check_add_window(len(out))
  647. # no need to hold the channel lock when sending this
  648. if ack > 0:
  649. m = Message()
  650. m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST)
  651. m.add_int(self.remote_chanid)
  652. m.add_int(ack)
  653. self.transport._send_user_message(m)
  654. return out
  655. def send_ready(self):
  656. """
  657. Returns true if data can be written to this channel without blocking.
  658. This means the channel is either closed (so any write attempt would
  659. return immediately) or there is at least one byte of space in the
  660. outbound buffer. If there is at least one byte of space in the
  661. outbound buffer, a `send` call will succeed immediately and return
  662. the number of bytes actually written.
  663. :return:
  664. ``True`` if a `send` call on this channel would immediately succeed
  665. or fail
  666. """
  667. self.lock.acquire()
  668. try:
  669. if self.closed or self.eof_sent:
  670. return True
  671. return self.out_window_size > 0
  672. finally:
  673. self.lock.release()
  674. def send(self, s):
  675. """
  676. Send data to the channel. Returns the number of bytes sent, or 0 if
  677. the channel stream is closed. Applications are responsible for
  678. checking that all data has been sent: if only some of the data was
  679. transmitted, the application needs to attempt delivery of the remaining
  680. data.
  681. :param str s: data to send
  682. :return: number of bytes actually sent, as an `int`
  683. :raises socket.timeout: if no data could be sent before the timeout set
  684. by `settimeout`.
  685. """
  686. m = Message()
  687. m.add_byte(cMSG_CHANNEL_DATA)
  688. m.add_int(self.remote_chanid)
  689. return self._send(s, m)
  690. def send_stderr(self, s):
  691. """
  692. Send data to the channel on the "stderr" stream. This is normally
  693. only used by servers to send output from shell commands -- clients
  694. won't use this. Returns the number of bytes sent, or 0 if the channel
  695. stream is closed. Applications are responsible for checking that all
  696. data has been sent: if only some of the data was transmitted, the
  697. application needs to attempt delivery of the remaining data.
  698. :param str s: data to send.
  699. :return: number of bytes actually sent, as an `int`.
  700. :raises socket.timeout:
  701. if no data could be sent before the timeout set by `settimeout`.
  702. .. versionadded:: 1.1
  703. """
  704. m = Message()
  705. m.add_byte(cMSG_CHANNEL_EXTENDED_DATA)
  706. m.add_int(self.remote_chanid)
  707. m.add_int(1)
  708. return self._send(s, m)
  709. def sendall(self, s):
  710. """
  711. Send data to the channel, without allowing partial results. Unlike
  712. `send`, this method continues to send data from the given string until
  713. either all data has been sent or an error occurs. Nothing is returned.
  714. :param str s: data to send.
  715. :raises socket.timeout:
  716. if sending stalled for longer than the timeout set by `settimeout`.
  717. :raises socket.error:
  718. if an error occurred before the entire string was sent.
  719. .. note::
  720. If the channel is closed while only part of the data has been
  721. sent, there is no way to determine how much data (if any) was sent.
  722. This is irritating, but identically follows Python's API.
  723. """
  724. while s:
  725. sent = self.send(s)
  726. s = s[sent:]
  727. return None
  728. def sendall_stderr(self, s):
  729. """
  730. Send data to the channel's "stderr" stream, without allowing partial
  731. results. Unlike `send_stderr`, this method continues to send data
  732. from the given string until all data has been sent or an error occurs.
  733. Nothing is returned.
  734. :param str s: data to send to the client as "stderr" output.
  735. :raises socket.timeout:
  736. if sending stalled for longer than the timeout set by `settimeout`.
  737. :raises socket.error:
  738. if an error occurred before the entire string was sent.
  739. .. versionadded:: 1.1
  740. """
  741. while s:
  742. sent = self.send_stderr(s)
  743. s = s[sent:]
  744. return None
  745. def makefile(self, *params):
  746. """
  747. Return a file-like object associated with this channel. The optional
  748. ``mode`` and ``bufsize`` arguments are interpreted the same way as by
  749. the built-in ``file()`` function in Python.
  750. :return: `.ChannelFile` object which can be used for Python file I/O.
  751. """
  752. return ChannelFile(*([self] + list(params)))
  753. def makefile_stderr(self, *params):
  754. """
  755. Return a file-like object associated with this channel's stderr
  756. stream. Only channels using `exec_command` or `invoke_shell`
  757. without a pty will ever have data on the stderr stream.
  758. The optional ``mode`` and ``bufsize`` arguments are interpreted the
  759. same way as by the built-in ``file()`` function in Python. For a
  760. client, it only makes sense to open this file for reading. For a
  761. server, it only makes sense to open this file for writing.
  762. :returns:
  763. `.ChannelStderrFile` object which can be used for Python file I/O.
  764. .. versionadded:: 1.1
  765. """
  766. return ChannelStderrFile(*([self] + list(params)))
  767. def makefile_stdin(self, *params):
  768. """
  769. Return a file-like object associated with this channel's stdin
  770. stream.
  771. The optional ``mode`` and ``bufsize`` arguments are interpreted the
  772. same way as by the built-in ``file()`` function in Python. For a
  773. client, it only makes sense to open this file for writing. For a
  774. server, it only makes sense to open this file for reading.
  775. :returns:
  776. `.ChannelStdinFile` object which can be used for Python file I/O.
  777. .. versionadded:: 2.6
  778. """
  779. return ChannelStdinFile(*([self] + list(params)))
  780. def fileno(self):
  781. """
  782. Returns an OS-level file descriptor which can be used for polling, but
  783. but not for reading or writing. This is primarily to allow Python's
  784. ``select`` module to work.
  785. The first time ``fileno`` is called on a channel, a pipe is created to
  786. simulate real OS-level file descriptor (FD) behavior. Because of this,
  787. two OS-level FDs are created, which will use up FDs faster than normal.
  788. (You won't notice this effect unless you have hundreds of channels
  789. open at the same time.)
  790. :return: an OS-level file descriptor (`int`)
  791. .. warning::
  792. This method causes channel reads to be slightly less efficient.
  793. """
  794. self.lock.acquire()
  795. try:
  796. if self._pipe is not None:
  797. return self._pipe.fileno()
  798. # create the pipe and feed in any existing data
  799. self._pipe = pipe.make_pipe()
  800. p1, p2 = pipe.make_or_pipe(self._pipe)
  801. self.in_buffer.set_event(p1)
  802. self.in_stderr_buffer.set_event(p2)
  803. return self._pipe.fileno()
  804. finally:
  805. self.lock.release()
  806. def shutdown(self, how):
  807. """
  808. Shut down one or both halves of the connection. If ``how`` is 0,
  809. further receives are disallowed. If ``how`` is 1, further sends
  810. are disallowed. If ``how`` is 2, further sends and receives are
  811. disallowed. This closes the stream in one or both directions.
  812. :param int how:
  813. 0 (stop receiving), 1 (stop sending), or 2 (stop receiving and
  814. sending).
  815. """
  816. if (how == 0) or (how == 2):
  817. # feign "read" shutdown
  818. self.eof_received = 1
  819. if (how == 1) or (how == 2):
  820. self.lock.acquire()
  821. try:
  822. m = self._send_eof()
  823. finally:
  824. self.lock.release()
  825. if m is not None:
  826. self.transport._send_user_message(m)
  827. def shutdown_read(self):
  828. """
  829. Shutdown the receiving side of this socket, closing the stream in
  830. the incoming direction. After this call, future reads on this
  831. channel will fail instantly. This is a convenience method, equivalent
  832. to ``shutdown(0)``, for people who don't make it a habit to
  833. memorize unix constants from the 1970s.
  834. .. versionadded:: 1.2
  835. """
  836. self.shutdown(0)
  837. def shutdown_write(self):
  838. """
  839. Shutdown the sending side of this socket, closing the stream in
  840. the outgoing direction. After this call, future writes on this
  841. channel will fail instantly. This is a convenience method, equivalent
  842. to ``shutdown(1)``, for people who don't make it a habit to
  843. memorize unix constants from the 1970s.
  844. .. versionadded:: 1.2
  845. """
  846. self.shutdown(1)
  847. @property
  848. def _closed(self):
  849. # Concession to Python 3's socket API, which has a private ._closed
  850. # attribute instead of a semipublic .closed attribute.
  851. return self.closed
  852. # ...calls from Transport
  853. def _set_transport(self, transport):
  854. self.transport = transport
  855. self.logger = util.get_logger(self.transport.get_log_channel())
  856. def _set_window(self, window_size, max_packet_size):
  857. self.in_window_size = window_size
  858. self.in_max_packet_size = max_packet_size
  859. # threshold of bytes we receive before we bother to send
  860. # a window update
  861. self.in_window_threshold = window_size // 10
  862. self.in_window_sofar = 0
  863. self._log(DEBUG, "Max packet in: {} bytes".format(max_packet_size))
  864. def _set_remote_channel(self, chanid, window_size, max_packet_size):
  865. self.remote_chanid = chanid
  866. self.out_window_size = window_size
  867. self.out_max_packet_size = self.transport._sanitize_packet_size(
  868. max_packet_size
  869. )
  870. self.active = 1
  871. self._log(
  872. DEBUG, "Max packet out: {} bytes".format(self.out_max_packet_size)
  873. )
  874. def _request_success(self, m):
  875. self._log(DEBUG, "Sesch channel {} request ok".format(self.chanid))
  876. self.event_ready = True
  877. self.event.set()
  878. return
  879. def _request_failed(self, m):
  880. self.lock.acquire()
  881. try:
  882. msgs = self._close_internal()
  883. finally:
  884. self.lock.release()
  885. for m in msgs:
  886. if m is not None:
  887. self.transport._send_user_message(m)
  888. def _feed(self, m):
  889. if isinstance(m, bytes_types):
  890. # passed from _feed_extended
  891. s = m
  892. else:
  893. s = m.get_binary()
  894. self.in_buffer.feed(s)
  895. def _feed_extended(self, m):
  896. code = m.get_int()
  897. s = m.get_binary()
  898. if code != 1:
  899. self._log(
  900. ERROR, "unknown extended_data type {}; discarding".format(code)
  901. )
  902. return
  903. if self.combine_stderr:
  904. self._feed(s)
  905. else:
  906. self.in_stderr_buffer.feed(s)
  907. def _window_adjust(self, m):
  908. nbytes = m.get_int()
  909. self.lock.acquire()
  910. try:
  911. if self.ultra_debug:
  912. self._log(DEBUG, "window up {}".format(nbytes))
  913. self.out_window_size += nbytes
  914. self.out_buffer_cv.notify_all()
  915. finally:
  916. self.lock.release()
  917. def _handle_request(self, m):
  918. key = m.get_text()
  919. want_reply = m.get_boolean()
  920. server = self.transport.server_object
  921. ok = False
  922. if key == "exit-status":
  923. self.exit_status = m.get_int()
  924. self.status_event.set()
  925. ok = True
  926. elif key == "xon-xoff":
  927. # ignore
  928. ok = True
  929. elif key == "pty-req":
  930. term = m.get_string()
  931. width = m.get_int()
  932. height = m.get_int()
  933. pixelwidth = m.get_int()
  934. pixelheight = m.get_int()
  935. modes = m.get_string()
  936. if server is None:
  937. ok = False
  938. else:
  939. ok = server.check_channel_pty_request(
  940. self, term, width, height, pixelwidth, pixelheight, modes
  941. )
  942. elif key == "shell":
  943. if server is None:
  944. ok = False
  945. else:
  946. ok = server.check_channel_shell_request(self)
  947. elif key == "env":
  948. name = m.get_string()
  949. value = m.get_string()
  950. if server is None:
  951. ok = False
  952. else:
  953. ok = server.check_channel_env_request(self, name, value)
  954. elif key == "exec":
  955. cmd = m.get_string()
  956. if server is None:
  957. ok = False
  958. else:
  959. ok = server.check_channel_exec_request(self, cmd)
  960. elif key == "subsystem":
  961. name = m.get_text()
  962. if server is None:
  963. ok = False
  964. else:
  965. ok = server.check_channel_subsystem_request(self, name)
  966. elif key == "window-change":
  967. width = m.get_int()
  968. height = m.get_int()
  969. pixelwidth = m.get_int()
  970. pixelheight = m.get_int()
  971. if server is None:
  972. ok = False
  973. else:
  974. ok = server.check_channel_window_change_request(
  975. self, width, height, pixelwidth, pixelheight
  976. )
  977. elif key == "x11-req":
  978. single_connection = m.get_boolean()
  979. auth_proto = m.get_text()
  980. auth_cookie = m.get_binary()
  981. screen_number = m.get_int()
  982. if server is None:
  983. ok = False
  984. else:
  985. ok = server.check_channel_x11_request(
  986. self,
  987. single_connection,
  988. auth_proto,
  989. auth_cookie,
  990. screen_number,
  991. )
  992. elif key == "auth-agent-req@openssh.com":
  993. if server is None:
  994. ok = False
  995. else:
  996. ok = server.check_channel_forward_agent_request(self)
  997. else:
  998. self._log(DEBUG, 'Unhandled channel request "{}"'.format(key))
  999. ok = False
  1000. if want_reply:
  1001. m = Message()
  1002. if ok:
  1003. m.add_byte(cMSG_CHANNEL_SUCCESS)
  1004. else:
  1005. m.add_byte(cMSG_CHANNEL_FAILURE)
  1006. m.add_int(self.remote_chanid)
  1007. self.transport._send_user_message(m)
  1008. def _handle_eof(self, m):
  1009. self.lock.acquire()
  1010. try:
  1011. if not self.eof_received:
  1012. self.eof_received = True
  1013. self.in_buffer.close()
  1014. self.in_stderr_buffer.close()
  1015. if self._pipe is not None:
  1016. self._pipe.set_forever()
  1017. finally:
  1018. self.lock.release()
  1019. self._log(DEBUG, "EOF received ({})".format(self._name))
  1020. def _handle_close(self, m):
  1021. self.lock.acquire()
  1022. try:
  1023. msgs = self._close_internal()
  1024. self.transport._unlink_channel(self.chanid)
  1025. finally:
  1026. self.lock.release()
  1027. for m in msgs:
  1028. if m is not None:
  1029. self.transport._send_user_message(m)
  1030. # ...internals...
  1031. def _send(self, s, m):
  1032. size = len(s)
  1033. self.lock.acquire()
  1034. try:
  1035. if self.closed:
  1036. # this doesn't seem useful, but it is the documented behavior
  1037. # of Socket
  1038. raise socket.error("Socket is closed")
  1039. size = self._wait_for_send_window(size)
  1040. if size == 0:
  1041. # eof or similar
  1042. return 0
  1043. m.add_string(s[:size])
  1044. finally:
  1045. self.lock.release()
  1046. # Note: We release self.lock before calling _send_user_message.
  1047. # Otherwise, we can deadlock during re-keying.
  1048. self.transport._send_user_message(m)
  1049. return size
  1050. def _log(self, level, msg, *args):
  1051. self.logger.log(level, "[chan " + self._name + "] " + msg, *args)
  1052. def _event_pending(self):
  1053. self.event.clear()
  1054. self.event_ready = False
  1055. def _wait_for_event(self):
  1056. self.event.wait()
  1057. assert self.event.is_set()
  1058. if self.event_ready:
  1059. return
  1060. e = self.transport.get_exception()
  1061. if e is None:
  1062. e = SSHException("Channel closed.")
  1063. raise e
  1064. def _set_closed(self):
  1065. # you are holding the lock.
  1066. self.closed = True
  1067. self.in_buffer.close()
  1068. self.in_stderr_buffer.close()
  1069. self.out_buffer_cv.notify_all()
  1070. # Notify any waiters that we are closed
  1071. self.event.set()
  1072. self.status_event.set()
  1073. if self._pipe is not None:
  1074. self._pipe.set_forever()
  1075. def _send_eof(self):
  1076. # you are holding the lock.
  1077. if self.eof_sent:
  1078. return None
  1079. m = Message()
  1080. m.add_byte(cMSG_CHANNEL_EOF)
  1081. m.add_int(self.remote_chanid)
  1082. self.eof_sent = True
  1083. self._log(DEBUG, "EOF sent ({})".format(self._name))
  1084. return m
  1085. def _close_internal(self):
  1086. # you are holding the lock.
  1087. if not self.active or self.closed:
  1088. return None, None
  1089. m1 = self._send_eof()
  1090. m2 = Message()
  1091. m2.add_byte(cMSG_CHANNEL_CLOSE)
  1092. m2.add_int(self.remote_chanid)
  1093. self._set_closed()
  1094. # can't unlink from the Transport yet -- the remote side may still
  1095. # try to send meta-data (exit-status, etc)
  1096. return m1, m2
  1097. def _unlink(self):
  1098. # server connection could die before we become active:
  1099. # still signal the close!
  1100. if self.closed:
  1101. return
  1102. self.lock.acquire()
  1103. try:
  1104. self._set_closed()
  1105. self.transport._unlink_channel(self.chanid)
  1106. finally:
  1107. self.lock.release()
  1108. def _check_add_window(self, n):
  1109. self.lock.acquire()
  1110. try:
  1111. if self.closed or self.eof_received or not self.active:
  1112. return 0
  1113. if self.ultra_debug:
  1114. self._log(DEBUG, "addwindow {}".format(n))
  1115. self.in_window_sofar += n
  1116. if self.in_window_sofar <= self.in_window_threshold:
  1117. return 0
  1118. if self.ultra_debug:
  1119. self._log(
  1120. DEBUG, "addwindow send {}".format(self.in_window_sofar)
  1121. )
  1122. out = self.in_window_sofar
  1123. self.in_window_sofar = 0
  1124. return out
  1125. finally:
  1126. self.lock.release()
  1127. def _wait_for_send_window(self, size):
  1128. """
  1129. (You are already holding the lock.)
  1130. Wait for the send window to open up, and allocate up to ``size`` bytes
  1131. for transmission. If no space opens up before the timeout, a timeout
  1132. exception is raised. Returns the number of bytes available to send
  1133. (may be less than requested).
  1134. """
  1135. # you are already holding the lock
  1136. if self.closed or self.eof_sent:
  1137. return 0
  1138. if self.out_window_size == 0:
  1139. # should we block?
  1140. if self.timeout == 0.0:
  1141. raise socket.timeout()
  1142. # loop here in case we get woken up but a different thread has
  1143. # filled the buffer
  1144. timeout = self.timeout
  1145. while self.out_window_size == 0:
  1146. if self.closed or self.eof_sent:
  1147. return 0
  1148. then = time.time()
  1149. self.out_buffer_cv.wait(timeout)
  1150. if timeout is not None:
  1151. timeout -= time.time() - then
  1152. if timeout <= 0.0:
  1153. raise socket.timeout()
  1154. # we have some window to squeeze into
  1155. if self.closed or self.eof_sent:
  1156. return 0
  1157. if self.out_window_size < size:
  1158. size = self.out_window_size
  1159. if self.out_max_packet_size - 64 < size:
  1160. size = self.out_max_packet_size - 64
  1161. self.out_window_size -= size
  1162. if self.ultra_debug:
  1163. self._log(DEBUG, "window down to {}".format(self.out_window_size))
  1164. return size
  1165. class ChannelFile(BufferedFile):
  1166. """
  1167. A file-like wrapper around `.Channel`. A ChannelFile is created by calling
  1168. `Channel.makefile`.
  1169. .. warning::
  1170. To correctly emulate the file object created from a socket's `makefile
  1171. <python:socket.socket.makefile>` method, a `.Channel` and its
  1172. `.ChannelFile` should be able to be closed or garbage-collected
  1173. independently. Currently, closing the `ChannelFile` does nothing but
  1174. flush the buffer.
  1175. """
  1176. def __init__(self, channel, mode="r", bufsize=-1):
  1177. self.channel = channel
  1178. BufferedFile.__init__(self)
  1179. self._set_mode(mode, bufsize)
  1180. def __repr__(self):
  1181. """
  1182. Returns a string representation of this object, for debugging.
  1183. """
  1184. return "<paramiko.ChannelFile from " + repr(self.channel) + ">"
  1185. def _read(self, size):
  1186. return self.channel.recv(size)
  1187. def _write(self, data):
  1188. self.channel.sendall(data)
  1189. return len(data)
  1190. class ChannelStderrFile(ChannelFile):
  1191. """
  1192. A file-like wrapper around `.Channel` stderr.
  1193. See `Channel.makefile_stderr` for details.
  1194. """
  1195. def _read(self, size):
  1196. return self.channel.recv_stderr(size)
  1197. def _write(self, data):
  1198. self.channel.sendall_stderr(data)
  1199. return len(data)
  1200. class ChannelStdinFile(ChannelFile):
  1201. """
  1202. A file-like wrapper around `.Channel` stdin.
  1203. See `Channel.makefile_stdin` for details.
  1204. """
  1205. def close(self):
  1206. super(ChannelStdinFile, self).close()
  1207. self.channel.shutdown_write()