Ejemplo n.º 1
0
 def close_session(self, channel: paramiko.Channel) -> None:
     channel.lock.acquire()
     if not channel.closed:
         channel.lock.release()
         channel.close()
     if channel.lock.locked():
         channel.lock.release()
Ejemplo n.º 2
0
def shell(channel: paramiko.Channel):
  stdin: paramiko.ChannelFile = channel.makefile_stdin("wb")
  stdout: paramiko.ChannelFile = channel.makefile("r")
  stderr: paramiko.ChannelFile = channel.makefile_stderr("r")
  print("Tip: F12 + I to show connection info, F12+C to close connection")

  stdoutReader = Thread(target=__buffered_reader, name="stdoutReader", args=(stdout, sys.stdout))
  stderrReader = Thread(target=__buffered_reader, name="stderrReader", args=(stderr, sys.stderr))
  stdinWriter = Thread(target=__input_handler, name="stdinWriter", args=(sys.stdin, stdin, channel))
  sizeHandler = Thread(target=__window_size_change_handler, name="TerminalSizeWatchdog", args=(channel,))

  sizeHandler.setDaemon(True)
  stdoutReader.setDaemon(True)
  stderrReader.setDaemon(True)
  stdinWriter.setDaemon(True)

  orig_sigint = signal.getsignal(signal.SIGINT)
  try:
    signal.signal(signal.SIGINT, _sigint)

    sizeHandler.start()
    stderrReader.start()
    stdoutReader.start()
    stdinWriter.start()

    stdoutReader.join()
  finally:
    print("Closing ssh session...")
    try:
      channel.close()
    except:
      pass
    signal.signal(signal.SIGINT, orig_sigint)
Ejemplo n.º 3
0
 def _handle_client(self, channel: paramiko.Channel) -> None:
     try:
         command = self.command_queues[channel.chanid].get(block=True)
         _logger.debug(f"Channel {channel.chanid}, executing {command}")
         command_result = self._command_handler(command.decode())
         channel.sendall(command_result.stdout)
         channel.sendall_stderr(command_result.stderr)
         channel.send_exit_status(command_result.returncode)
     except Exception:  # pylint: disable=broad-except
         _logger.exception(f"Error handling client (channel: {channel})")
     finally:
         try:
             channel.close()
         except EOFError:
             _logger.debug("Tried to close already closed channel")
Ejemplo n.º 4
0
 def handler(self, channel: paramiko.Channel, origin: Optional[Tuple[str,
                                                                     int]],
             destination: Optional[Tuple[str, int]]) -> None:
     try:
         logging.debug(
             "Opening forwarded-tcpip channel (%s -> %s) to client", origin,
             destination)
         f = TunnelForwarder(
             self.session.transport.open_channel("forwarded-tcpip",
                                                 destination, origin),
             channel)
         self.server_interface.forwarders.append(f)
     except paramiko.ssh_exception.ChannelException:
         channel.close()
         logging.error("Could not setup forward from %s to %s.", origin,
                       destination)
Ejemplo n.º 5
0
Archivo: main.py Proyecto: hyzyla/dhavn
def right_forwarder(channel: Channel, local_port: int):
    selector = selectors.DefaultSelector()

    def from_localhost():
        data = sock.recv(1024)
        if len(data) == 0:
            return data
        channel.send(data)
        return data

    def to_localhost():
        data = sock.recv(1024)
        if len(data) == 0:
            return data
        channel.send(data)
        return data


    selector.register(socket, selectors.EVENT_READ, from_localhost)
    selector.register(channel, selectors.EVENT_READ, to_localhost)

    # connect to localhost via sockets
    sock = socket.socket()
    try:
        sock.connect((LOCALHOST, local_port))
    except Exception as e:
        logger.error(f'Forwarding request to {local_port} failed: e')
        return

    # read data from channel or socket and send to opposite site
    while True:
        r, _, _ = select.select([sock, channel], [], [])
        if sock in r:
            data = sock.recv(1024)
            if len(data) == 0:
                break
            channel.send(data)
        if channel in r:
            data = channel.recv(1024)
            if len(data) == 0:
                break
            sock.send(data)
    channel.close()
    sock.close()
    logger.info(f'Tunnel closed from {channel.origin_addr}')
Ejemplo n.º 6
0
 def do_close():
     if ch.channel_file is not None and not ch.channel_file.closed:
         ch.close_pending = True
         return
     else:
         try:
             return Channel.close(ch)
         except EOFError as e:
             # Some problems while closing yield an EOFError, which is not
             # descriptive
             raise ConnectionError('Closing channel') from e
Ejemplo n.º 7
0
    def _initiate_channel(self, channel: paramiko.Channel, email: str):
        """
        Initiates channel with given channel object and email
        :param channel: SSH Channel object
        :param email: user's email
        """
        data = channel.recv(5)
        data = data.decode("utf-8")
        logging.debug("Data recived: {data}".format(data=data))

        if data == self.READY:
            size = channel.recv(64)
            size = size.decode('utf-8')
            size = size.replace('.', '')
            name = channel.recv(int(size))
            setattr(channel,"anylink_name",name.decode('utf-8'))
            channel.send(self.CONFIRM_READY)
            self.channels[channel] = email
        else:
            channel.close()
Ejemplo n.º 8
0
 def close_channel(self, channel: Channel):
     channel.close()