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