Ejemplo n.º 1
0
    def submit(self, session=None, otp='', gui_cmd=None, configFile=None):
        if not session:
            return

        logic_logger.debug("session: " + str(session.hash))

        compute_node = session.hash['node']
        port_string = session.hash.get('port', '')
        if port_string:
            port_number = int(port_string)
        else:
            port_number = 5900 + int(session.hash['display'])

        login_node = session.hash['nodelogin']
        local_port_number = rcm_utils.get_unused_portnumber()

        try:
            tunnelling_method = json.loads(parser.get('Settings',
                                                      'ssh_client'))
        except Exception:
            tunnelling_method = "internal"
        logic_logger.info("Using " + str(tunnelling_method) +
                          " ssh tunnelling")

        plugin_exe = plugin.TurboVNCExecutable()
        plugin_exe.build(session=session, local_portnumber=local_port_number)

        st = thread.SessionThread(plugin_exe.command, login_node,
                                  self.proxynode, self.user, self.password,
                                  gui_cmd, configFile, local_port_number,
                                  compute_node, port_number, tunnelling_method)

        self.session_threads.append(st)
        st.start()
Ejemplo n.º 2
0
def get_server_command(host, user, passwd=''):
    """
    It call bare ssh server to  check if on login node, the user has defined a variable
    named RCM_SERVER_COMMAND, in tht case the content of that variable overrides the default
    rcm command string used for the remaining part of the server interaction
     """

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    logic_logger.info("getting server command from host " + host +
                      " with user " + user)
    try:
        ssh.connect(host, username=user, password=passwd)
    except Exception as e:
        logic_logger.error("ERROR {0}: ".format(e) +
                           "in ssh.connect to host " + host)
        raise e

    chan = ssh.get_transport().open_session()
    chan.get_pty()
    stdin = chan.makefile('wb')
    stdout = chan.makefile('rb')

    start_string = '_##start##_'
    end_string = '_##end##_'
    evn_variable = '${RCM_SERVER_COMMAND}'
    get_rcm_server_command = 'echo ' + start_string + evn_variable + end_string + '\n'
    chan.invoke_shell()
    chan.sendall(get_rcm_server_command)
    stdin.flush()

    chan.settimeout(20)

    loop = True
    output = ''
    rcm_server_command = ''

    while loop:
        try:
            # python3
            if sys.version_info >= (3, 0):
                line = str(stdout.readline(), 'utf-8')
            # python2
            else:
                line = stdout.readline()
            logic_logger.debug("parsing output line: ->" + line + "<-")

            if end_string in line and start_string in line:
                tmp_command = line.split(end_string)[0].split(start_string)[1]
                if not evn_variable in tmp_command:
                    rcm_server_command = tmp_command
                    loop = False
            output += line
        except socket.timeout:
            logic_logger.warning(
                "WARNING TIMEOUT: unable to grab output of -->" +
                get_rcm_server_command + "< on host:" + host)
            loop = False
    return rcm_server_command
Ejemplo n.º 3
0
    def build(self, session, local_portnumber):
        nodelogin = session.hash['nodelogin']
        # local_portnumber = rcm_utils.get_unused_portnumber()

        tunnel = session.hash['tunnel']
        try:
            tunnelling_method = json.loads(parser.get('Settings',
                                                      'ssh_client'))
        except Exception:
            tunnelling_method = "internal"
        logic_logger.info("Using " + str(tunnelling_method) +
                          " ssh tunnelling")

        # Decrypt password
        vncpassword = session.hash.get('vncpassword', '')
        rcm_cipher = cipher.RCMCipher()
        vncpassword_decrypted = rcm_cipher.decrypt(vncpassword)

        # Darwin
        if sys.platform.startswith('darwin'):
            self.add_arg_value(
                "-W", "vnc://:" + vncpassword_decrypted + "@127.0.0.1:" +
                str(local_portnumber))

        # Win64
        elif sys.platform == 'win32':
            self.add_default_arg("/nounixlogin")
            self.add_default_arg("/noreconnect")
            self.add_default_arg("/nonewconn")
            self.add_arg_value("/loglevel", "0")
            self.add_arg_value("/password", vncpassword_decrypted)

        # Linux
        else:
            self.add_arg_value("-quality", "80")
            self.add_arg_value("-password", vncpassword_decrypted)
            self.add_default_arg("-noreconnect")
            self.add_default_arg("-nonewconn")

        if not sys.platform.startswith('darwin'):
            if tunnel == 'y':
                self.add_default_arg("127.0.0.1:" + str(local_portnumber))
            else:
                self.add_default_arg(nodelogin + ":" +
                                     str(session.hash['display']))

        service_command_without_password = self.command
        if vncpassword_decrypted:
            service_command_without_password = service_command_without_password.replace(
                vncpassword_decrypted, "***")
        logic_logger.debug("service cmd: " +
                           str(service_command_without_password))
Ejemplo n.º 4
0
    def vncsession(self, session=None, otp='', gui_cmd=None, configFile=None):
        tunnel_command = ''
        vnc_command = ''
        vncpassword_decrypted = ''
        try:
            tunnelling_method = json.loads(parser.get('Settings',
                                                      'ssh_client'))
        except Exception:
            tunnelling_method = "internal"
        logic_logger.info("Using " + str(tunnelling_method) +
                          " ssh tunnelling")

        if session:
            portnumber = 5900 + int(session.hash['display'])
            local_portnumber = rcm_utils.get_unused_portnumber()
            node = session.hash['node']
            nodelogin = session.hash['nodelogin']
            tunnel = session.hash['tunnel']
            vncpassword = session.hash.get('vncpassword', '')

            # Decrypt password
            rcm_cipher = cipher.RCMCipher()
            vncpassword_decrypted = rcm_cipher.decrypt(vncpassword)

            logic_logger.debug("portnumber --> " + str(portnumber) +
                               " node --> " + str(node) + " nodelogin --> " +
                               str(nodelogin) + " tunnel --> " + str(tunnel))

            if sys.platform.startswith('darwin'):
                vnc_command = self.vnc_cmdline_builder.get_executable_path() + " -quality 80 -subsampling 2X" \
                              + " -password " + vncpassword_decrypted
                vnc_command += " -loglevel " + str(rcm_utils.vnc_loglevel)
            elif sys.platform == 'win32':
                vnc_command = "echo " + vncpassword_decrypted + " | " + self.vnc_cmdline_builder.get_executable_path() \
                              + " -autopass -nounixlogin"
                vnc_command += " -logfile " + os.path.join(
                    rcm_utils.log_folder(), 'vncviewer_' + nodelogin + '_' +
                    session.hash.get('sessionid', '') + '.log')
                vnc_command += " -loglevel " + str(rcm_utils.vnc_loglevel)
            else:
                vnc_command = self.vnc_cmdline_builder.get_executable_path() + " -quality 80 " \
                              + " -password " + vncpassword_decrypted

            if sys.platform == 'win32' or sys.platform.startswith('darwin'):
                if tunnel == 'y':
                    tunnel_command = self.ssh_command + " -L 127.0.0.1:" + str(local_portnumber) + ":" + node + ":" \
                                     + str(portnumber) + " " + self.login_options + "@" + nodelogin
                    if sys.platform.startswith('darwin'):
                        tunnel_command += " echo 'rcm_tunnel'; sleep 20"
                    else:
                        tunnel_command += " echo 'rcm_tunnel'; sleep 10"
                    vnc_command += " 127.0.0.1:" + str(local_portnumber)
                else:
                    vnc_command += " " + nodelogin + ":" + str(portnumber)
            else:
                if tunnel == 'y':
                    if tunnelling_method == 'internal':
                        vnc_command += " 127.0.0.1:" + str(local_portnumber)
                    elif tunnelling_method == 'external':
                        tunnel_command = self.ssh_command + " -L 127.0.0.1:" + str(local_portnumber) + ":" + node + ":" \
                                         + str(portnumber) + " " + self.login_options + "@" + nodelogin
                    elif tunnelling_method == 'via':
                        vnc_command += " -via '" + self.login_options + "@" + nodelogin + "' " \
                                       + node + ":" + str(session.hash['display'])
                    else:
                        logic_logger.error(tunnelling_method +
                                           ' is not a valid option')
                        return
                else:
                    vnc_command += ' ' + nodelogin + ":" + session.hash[
                        'display']
        else:
            vnc_command = self.vnc_cmdline_builder.get_executable_path(
            ) + " -config "

        logic_logger.debug("tunnel->" +
                           tunnel_command.replace(self.passwd, "****") +
                           "< vnc->" + vnc_command + "< conffile->" +
                           str(configFile) + "<")

        st = thread.SessionThread(tunnel_command, vnc_command, self.proxynode,
                                  self.remoteuser, self.passwd,
                                  vncpassword_decrypted, otp, gui_cmd,
                                  configFile, self.auth_method,
                                  local_portnumber, node, portnumber,
                                  tunnelling_method)

        logic_logger.debug("session  thread--->" + str(st) +
                           "<--- num thread:" + str(len(self.session_thread)))
        self.session_thread.append(st)
        st.start()
Ejemplo n.º 5
0
Archivo: thread.py Proyecto: hpcit/RCM
    def execute_vnc_command_with_external_ssh_tunnel(self):
        if sys.platform == 'win32':
            if self.tunnel_command != '':
                tunnel_command_without_password = self.tunnel_command
                if self.auth_method == 'password':
                    tunnel_command_without_password = self.tunnel_command.replace(self.password, "****")

                logic_logger.debug('Thread ' + str(self.threadnum) + " executing " +
                                   tunnel_command_without_password)
                self.tunnel_process = subprocess.Popen(self.tunnel_command,
                                                       bufsize=1,
                                                       stdout=subprocess.PIPE,
                                                       stderr=subprocess.PIPE,
                                                       stdin=subprocess.PIPE,
                                                       shell=True,
                                                       universal_newlines=True)
                self.tunnel_process.stdin.close()
                while True:
                    o = self.tunnel_process.stdout.readline()

                    if o == '' and self.tunnel_process.poll() is not None:
                        continue
                    logic_logger.debug("output from process---->" + o.strip() + "<---")

                    if o.strip() == 'rcm_tunnel':
                        break

            a = self.vnc_command.split("|")

            logic_logger.debug("starting vncviewer")
            logic_logger.debug("splitting" + str(a))

            if len(a) > 1:
                tmppass = a[0].strip().split()[1].strip()
                commandlist = a[1].strip()
            else:
                tmppass = None
                commandlist = self.vnc_command.split()

                logic_logger.debug("vncviewer tmp  pass-->" + tmppass + "<--")
                logic_logger.debug("vncviewer command-->" + str(commandlist) + "<--")

            self.vnc_process = subprocess.Popen(commandlist,
                                                bufsize=1,
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.PIPE,
                                                stdin=subprocess.PIPE,
                                                shell=False,
                                                universal_newlines=True)
            if tmppass:
                self.vnc_process.stdin.write(tmppass)
                o = self.vnc_process.communicate()
                logic_logger.debug("vnc res-->" + str(o) + "<--")

            if self.vnc_process:
                self.vnc_process.stdin.close()
            if self.vnc_process:
                self.vnc_process.wait()

        elif sys.platform.startswith('darwin'):
            if self.tunnel_command != '':
                ssh_newkey = 'Are you sure you want to continue connecting'
                logic_logger.debug('Tunnel commands: ' + str(self.tunnel_command))

                child = pexpect.spawn(self.tunnel_command, timeout=50)
                i = child.expect([ssh_newkey, 'password:'******'rcm_tunnel', pexpect.TIMEOUT, pexpect.EOF])

                logic_logger.info('Tunnel return: ' + str(i))
                if i == 0:
                    # no certificate
                    child.sendline('yes')
                    i = child.expect(['password',
                                      'standard VNC authentication',
                                      'rcm_tunnel',
                                      pexpect.TIMEOUT,
                                      pexpect.EOF])

                if i == 1:
                    # no certificate
                    child.sendline(self.password)

                if i == 0 or i == 3:
                    logic_logger.debug("Timeout connecting to the display.")
                    if self.gui_cmd:
                        self.gui_cmd(active=False)
                    raise Exception("Timeout connecting to the display.")

            commandlist = self.vnc_command.split()
            self.vnc_process = subprocess.Popen(commandlist,
                                                bufsize=1,
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.PIPE,
                                                stdin=subprocess.PIPE,
                                                shell=False,
                                                universal_newlines=True)
            if self.vnc_process:
                self.vnc_process.stdin.close()
            if self.vnc_process:
                self.vnc_process.wait()

        else:
            # linux
            child = pexpect.spawn(self.vnc_command,
                                  timeout=50)
            self.vnc_process = child

            i = child.expect(['continue connecting',
                              'password',
                              'standard VNC authentication',
                              pexpect.EOF],
                             timeout=None)

            if i == 0:
                child.sendline('yes')
                i = child.expect(['continue connecting',
                                  'password',
                                  'standard VNC authentication',
                                  pexpect.EOF],
                                 timeout=None)

            if i == 1:
                child.sendline(self.password)
                i = child.expect(['continue connecting',
                                  'password',
                                  'standard VNC authentication',
                                  pexpect.EOF],
                                 timeout=None)

            if i == 2:
                # Standard VNC authentication
                i = child.expect(['dummy0',
                                  'dummy1',
                                  'Password:'******'Authentication successful',
                              pexpect.EOF],
                             timeout=None)

            if i > 0:
                logic_logger.debug("#REMOVE_FOR_JAVA#Authentication problems.")
                for line in child:
                    logic_logger.debug("#REMOVE_FOR_JAVA#child expect-->" + str(line))

            child.expect(pexpect.EOF,
                         timeout=None)
Ejemplo n.º 6
0
    def prex(self, cmd):
        """
        A wrapper around all the remote command execution;
        accept the input command and
        return the remote server output that comes after
        the rcm.serverOutputString separation string
        """
        if self.commandnode == '':
            host = self.proxynode
        else:
            host = self.commandnode
            self.commandnode = ''

        # build the full command
        if self.preload.strip():
            fullcommand = self.preload.strip()

            # if fullcommand ends with ';' add the preset rcm server command, otherwise use it as is
            if fullcommand[-1] == ';':
                fullcommand += ' ' + self.rcm_server_command
        else:
            fullcommand = self.rcm_server_command

        fullcommand += ' ' + cmd
        logic_logger.info(
            "On " + host +
            " run: <br><span style=\" font-size:5; font-weight:400; color:#101010;\" >"
            + fullcommand + "</span>")

        # ssh full command execution
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(host,
                        username=self.user,
                        password=self.password,
                        timeout=10)
            self.auth_method = ssh.get_transport().auth_handler.auth_method
            stdin, stdout, stderr = ssh.exec_command(fullcommand)
            out = ''.join(stdout)
            err = stderr.readlines()
        except Exception as e:
            ssh.close()
            raise RuntimeError(e)
        finally:
            ssh.close()

        if err:
            logic_logger.warning(err)

        # find where the real server output starts
        index = out.find(rcm.serverOutputString)
        if index != -1:
            index += len(rcm.serverOutputString)
            out = out[index:]
        else:
            logic_logger.error(
                "Missing serverOutputString: {0} in server output".format(
                    rcm.serverOutputString))
            if err:
                raise Exception("Server error: {0}".format(err))

        return out