Commit 2a187b83 authored by Thomas Souvignet's avatar Thomas Souvignet Committed by Sébastien Luttringer
Browse files

implement 'console' command

parent 5d3a9380
Loading
Loading
Loading
Loading
+76 −0
Original line number Diff line number Diff line
#!/usr/bin/env python
#coding=utf8

'''
Connection to a remote shell
'''

import os
import sys
import tty
import fcntl
import signal
import struct
import termios
import time

from cccli.exception import *
from sjrpc.core.exceptions import *
from cccli.printer import Printer, color
from cccli.command import ConsoleCommand

from sjrpc.core.protocols import TunnelProtocol
from sjrpc.core import AsyncWatcher

class Command_console(ConsoleCommand):
    '''Start a remote shell on the provided host'''

    def __init__(self, cli, argv0):
        ConsoleCommand.__init__(self, cli, argv0)
        #self.tql_filter = "&con"

    def __call__(self, argv):
        # args parse
        self.parse_args(argv)
        if len(self.args) != 1:
            raise cmdBadArgument()
        # rpccall
        self.rpccall("console", self.args[0], _callback=self._cb_open_shell,
                     _status=True, _direct=True)

    def _cb_open_shell(self, response):
        if not 'objects' in response:
            return
        response = response['objects'][0]
        if not 'status' in response:
            return
        if response['status'] == 'success':
            label = response['output']
            try:
                size = 0
                self.start_console(sys.stdin, sys.stdout, sys.stderr)
                # Connect to remote end using sjrpc
                tun = self.rpc.create_tunnel(endpoint=self)
                # Save current terminal size
                size = struct.pack('HHHH', 0, 0, 0, 0)
                size = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, size)
                while self.running:
                    time.sleep(1)
            except Exception:
                # Cleanup
                self.stop_console()
                tun.shutdown()
                tun.close()
                # Restore terminal size
                fcntl.ioctl(sys.stdout.fileno(), termios.TIOCSWINSZ, size)
                raise
            else:
                # Cleanup
                self.stop_console()
                tun.shutdown()
                tun.close()
                # Restore terminal size
                fcntl.ioctl(sys.stdout.fileno(), termios.TIOCSWINSZ, size)

    def remote_functions(self):
        return set(("rshell",))