コード例 #1
0
ファイル: rcm_utils.py プロジェクト: hpcit/RCM
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
コード例 #2
0
    def login_setup(self, host, remoteuser, password=None):
        self.proxynode = host

        if remoteuser == '':
            if sys.version_info >= (3, 0):
                self.remoteuser = input("Remote user: "******"Remote user: "******" -i " + keyfile + " " + self.remoteuser

            else:
                logic_logger.warning(
                    "PASSING PRIVATE KEY FILE NOT IMPLEMENTED ON PLATFORM -->"
                    + sys.platform + "<--")
                self.login_options = " -i " + keyfile + " " + self.remoteuser

        else:
            if sys.platform == 'win32':
                if password is None:
                    self.passwd = getpass.getpass("Get password for " +
                                                  self.remoteuser + "@" +
                                                  self.proxynode + " : ")
                else:
                    self.passwd = password
                self.login_options = " -pw " + self.passwd + " " + self.remoteuser
            else:
                if password is None:
                    self.passwd = getpass.getpass("Get password for " +
                                                  self.remoteuser + "@" +
                                                  self.proxynode + " : ")
                else:
                    self.passwd = password
                self.login_options = self.remoteuser

        self.login_options_withproxy = self.login_options + "@" + self.proxynode
        self.ssh_remote_exec_command = self.ssh_command + " " + self.login_options
        self.ssh_remote_exec_command_withproxy = self.ssh_command + " " + self.login_options_withproxy

        check_cred = self.checkCredential()
        if check_cred:
            self.subnet = '.'.join(
                socket.gethostbyname(self.proxynode).split('.')[0:-1])
            logic_logger.debug("Login host: " + self.proxynode + " subnet: " +
                               self.subnet)
        return check_cred
コード例 #3
0
    def prex(self, cmd, commandnode=''):
        """
        This is the function that wrap all the remote comman execution, accept the input command
        and return the remote server output that comes after the rcm.serverOutputString separation
        string
        """
        if self.commandnode == '':
            commandnode = self.proxynode
        else:
            commandnode = self.commandnode
            self.commandnode = ''
        fullcommand = self.ssh_remote_exec_command + "@" + commandnode + ' ' + cmd

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        logic_logger.debug("on " + commandnode + " run-->" +
                           self.config['remote_rcm_server'] + ' ' + cmd + "<")

        try:
            ssh.connect(commandnode,
                        username=self.remoteuser,
                        password=self.passwd,
                        timeout=10)
        except Exception as e:
            logic_logger.warning("ERROR {0}: ".format(e) +
                                 "in ssh.connect to node->" + commandnode +
                                 "< user->" + self.remoteuser + "<")
            return ('')

        self.auth_method = ssh.get_transport().auth_handler.auth_method

        stdin, stdout, stderr = ssh.exec_command(
            self.config['remote_rcm_server'] + ' ' + cmd)
        myout = ''.join(stdout)
        myerr = stderr.readlines()
        if myerr:
            logic_logger.error(myerr)
            raise Exception("Server error: {0}".format(myerr))

        # find where the real server output starts
        index = myout.find(rcm.serverOutputString)
        if index != -1:
            index += len(rcm.serverOutputString)
            myout = myout[index:]
        return myout
コード例 #4
0
ファイル: cipher.py プロジェクト: hpcit/RCM
def vnc_crypt(vncpass, decrypt=False):
    if decrypt:
        try:
            if sys.version_info >= (3, 0):
                import binascii
                passpadd = binascii.unhexlify(vncpass)
            else:
                passpadd = vncpass.decode('hex')
        except TypeError as e:
            if e.message == 'Odd-length string':
                logic_logger.warning(
                    'WARN: %s . Chopping last char off... "%s"' %
                    (e.message, vncpass[:-1]))
                passpadd = vncpass[:-1].decode('hex')
            else:
                raise
    else:
        passpadd = (vncpass + '\x00' * 8)[:8]
        passpadd = passpadd.encode('utf-8')
    strkey = u''.join([chr(x) for x in d3des.vnckey])

    if sys.version_info >= (3, 0):
        # python3
        key = d3des.deskey(strkey.encode('utf-8'), decrypt)
        crypted = d3des.desfunc(passpadd, key)
    else:
        key = d3des.deskey(strkey, decrypt)
        crypted = d3des.desfunc(passpadd, key)

    if decrypt:
        if sys.version_info >= (3, 0):
            import binascii
            hex_crypted = binascii.unhexlify(
                binascii.hexlify(crypted)).decode('utf-8')
        else:
            hex_crypted = crypted.encode('hex').decode('hex')
        return hex_crypted
    else:
        if sys.version_info >= (3, 0):
            import binascii
            hex_crypted = binascii.hexlify(crypted).decode('utf-8')
        else:
            hex_crypted = crypted.encode('hex')
        return hex_crypted
コード例 #5
0
def copytree(src, dst, symlinks=False, ignore=None):
    if not os.path.exists(dst):
        logic_logger.debug("Creating folder " + dst)
        os.makedirs(dst)
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            copytree(s, d, symlinks, ignore)
        else:
            if not os.path.exists(d):
                logic_logger.debug("Copy: " + s + " >> " + d)
                shutil.copy2(s, d)
            else:
                source_hash = compute_checksum(s)
                dest_hash = compute_checksum(d)
                if source_hash == dest_hash:
                    logic_logger.debug("Found previous: " + d)
                else:
                    logic_logger.warning("Update previous: " + s + " >> " + d)
                    shutil.copy2(s, d)
コード例 #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