Package paramiko :: Module channel
[frames] | no frames]

Source Code for Module paramiko.channel

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