Beispiel #1
0
 def _command_failure(self, line):
     if self._regex_helper.search_compiled(Su._re_command_fail, line):
         self.set_exception(CommandFailure(self, "ERROR: {}".format(self._regex_helper.group("OPTION"))))
         raise ParsingDone
     elif self._regex_helper.search_compiled(Su._re_wrong_username, line):
         self.set_exception(CommandFailure(self, "ERROR: {}".format(self._regex_helper.group("USERNAME"))))
         raise ParsingDone
Beispiel #2
0
    def _validate_passed_object_or_command_parameters(self):
        """
        Validates passed parameters to create embedded command object.

        :return: None
        :raise: CommandFailure if command parameters are wrong.
        """
        if self._validated_embedded_parameters:
            return  # Validate parameters only once
        if not self.cmd_class_name and not self.cmd_object:
            # _validate_start is called before running command on connection, so we raise exception
            # instead of setting it
            raise CommandFailure(
                self,
                "Neither 'cmd_class_name' nor 'cmd_object' was provided to Sudo constructor."
                "Please specific parameter.")
        if self.cmd_object and self.cmd_class_name:
            # _validate_start is called before running command on connection, so we raise exception instead
            # of setting it
            raise CommandFailure(
                self,
                "both 'cmd_object' and 'cmd_class_name' parameters provided. Please specify only one."
            )
        if self.cmd_object and self.cmd_object.done():
            # _validate_start is called before running command on connection, so we raise exception
            # instead of setting it
            raise CommandFailure(
                self,
                "Not allowed to run again the embedded command (embedded command is done): {}."
                .format(self.cmd_object))
        self._validated_embedded_parameters = True
Beispiel #3
0
    def on_new_line(self, line, is_full_line):
        if self.is_failure_indication(line):
            self.set_exception(
                CommandFailure(self,
                               "command failed in line '{}'".format(line)))
            return
        self.get_hosts_file_if_displayed(line)
        self.push_yes_if_needed(line)
        self.send_password_if_requested(line)

        if Ssh._re_id_dsa.search(line):
            self.connection.sendlineline("")
        elif self._regex_helper.search_compiled(
                Ssh._re_host_key_verification_failed, line):
            if self._hosts_file:
                self.handle_failed_host_key_verification()
            else:
                self.set_exception(
                    CommandFailure(self,
                                   "command failed in line '{}'".format(line)))
        else:
            sent = self.send_after_login_settings(line)
            if (not sent) and self.is_target_prompt(line) and (
                    not is_full_line):
                if self.all_after_login_settings_sent(
                ) or self.no_after_login_settings_needed():
                    if not self.done():
                        self.set_result({})
Beispiel #4
0
    def __init__(self, connection, sudo_password, cmd_object=None, cmd_class_name=None, cmd_params=None, prompt=None,
                 newline_chars=None, runner=None):
        super(Sudo, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)
        self.sudo_password = sudo_password
        self.cmd_object = cmd_object
        self._sent_sudo_password = False
        self._sent_command_string = False
        self.newline_seq = "\r\n"
        if cmd_object and cmd_class_name:
            self.set_exception(CommandFailure(self, "both 'cmd_object' and 'cmd_class_name' parameters provided. Please specify only one. "))
            return

        if cmd_class_name:
            params = dict()
            if cmd_params is not None:
                params = cmd_params.copy()
            params["connection"] = connection
            params['prompt'] = prompt
            params["newline_chars"] = newline_chars
            try:
                self.cmd_object = create_object_from_name(cmd_class_name, cmd_params)
            except Exception as ex:
                self.set_exception(ex)
        else:
            if not self.cmd_object:
                self.set_exception(CommandFailure(self,
                                                  "Neither 'cmd_class_name' nor 'cmd_object' was provided to Sudo constructor. Please specific parameter."))
Beispiel #5
0
 def _command_error(self, line):
         if self._regex_helper.search_compiled(Userdel._re_command_error, line):
             self.set_exception(CommandFailure(self, "ERROR: {}".format(self._regex_helper.group("ERROR"))))
             raise ParsingDone
         if self._regex_helper.search_compiled(Userdel._re_wrong_syntax, line):
             self.set_exception(CommandFailure(self, "ERROR: wrong syntax, should be: {}".format(
                 self._regex_helper.group("HELP_MSG"))))
             raise ParsingDone
Beispiel #6
0
 def _command_error(self, line):
     if self._regex_helper.search_compiled(Sftp._re_help, line):
         self.set_exception(CommandFailure(self, "ERROR: invalid command syntax"))
         raise ParsingDone
     for _re_error in Sftp._error_regex_compiled:
         if self._regex_helper.search_compiled(_re_error, line):
             self.set_exception(CommandFailure(self, "ERROR: {}".format(line)))
             raise ParsingDone
Beispiel #7
0
    def __init__(self,
                 connection,
                 password,
                 cmd_object=None,
                 cmd_class_name=None,
                 cmd_params=None,
                 prompt=None,
                 newline_chars=None,
                 runner=None,
                 encrypt_password=True):
        """
        Constructs object for Unix command sudo.

        :param connection: Moler connection to device, terminal when command is executed.
        :param password: password for sudo.
        :param cmd_object: object of command. Pass this object or cmd_class_name.
        :param cmd_class_name: full (with package) class name. Pass this name or cmd_object.
        :param cmd_params: params for cmd_class_name. If cmd_object is passed this parameter is ignored.
        :param prompt: prompt (on system where command runs).
        :param newline_chars: Characters to split lines - list.
        :param runner: Runner to run command.
        :param encrypt_password: If True then * will be in logs when password is sent, otherwise plain text.
        """
        super(Sudo, self).__init__(connection=connection,
                                   prompt=prompt,
                                   newline_chars=newline_chars,
                                   runner=runner)
        self.password = password
        self.cmd_object = cmd_object
        self.encrypt_password = encrypt_password
        self._sent_sudo_password = False
        self._sent_command_string = False
        self.newline_seq = "\n"
        if cmd_object and cmd_class_name:
            self.set_exception(
                CommandFailure(
                    self,
                    "both 'cmd_object' and 'cmd_class_name' parameters provided. Please specify only one. "
                ))
            return

        if cmd_class_name:
            params = copy_dict(cmd_params)
            params["connection"] = connection
            params['prompt'] = prompt
            params["newline_chars"] = newline_chars
            try:
                self.cmd_object = create_object_from_name(
                    cmd_class_name, params)
            except Exception as ex:
                self.set_exception(ex)
        else:
            if not self.cmd_object:
                self.set_exception(
                    CommandFailure(
                        self,
                        "Neither 'cmd_class_name' nor 'cmd_object' was provided to Sudo constructor. Please specific parameter."
                    ))
Beispiel #8
0
 def _command_error(self, line):
     if self._regex_helper.search_compiled(Useradd._re_error, line):
         self.set_exception(
             CommandFailure(
                 self,
                 "ERROR: {}".format(self._regex_helper.group("ERROR"))))
         raise ParsingDone
     elif self._regex_helper.search_compiled(Useradd._re_invalid_syntax,
                                             line):
         self.set_exception(
             CommandFailure(self, "ERROR: invalid command syntax"))
         raise ParsingDone
Beispiel #9
0
    def _command_error(self, line):

        if self._regex_helper.search_compiled(Uname._re_invalid_option, line):
            self.set_exception(
                CommandFailure(
                    self,
                    "ERROR: {}".format(self._regex_helper.group("OPTION"))))
            raise ParsingDone

        elif self._regex_helper.search_compiled(Uname._re_command_fail, line):
            self.set_exception(
                CommandFailure(
                    self,
                    "ERROR: {}".format(self._regex_helper.group("COMMAND"))))
            raise ParsingDone
Beispiel #10
0
    def _authentication_failure(self, line):
        if self._regex_helper.search_compiled(Su._re_authentication_fail, line):
            self.set_exception(CommandFailure(self, "ERROR: {}, {}, {}".format(self._regex_helper.group("AUTH"),
                                                                               self._regex_helper.group("PERM"),
                                                                               self._regex_helper.group("PASS"))))

            raise ParsingDone
Beispiel #11
0
 def _command_failure(self, line):
     if self._regex_helper.search_compiled(Iperf._re_command_failure, line):
         self.set_exception(
             CommandFailure(
                 self, "ERROR: {}".format(
                     self._regex_helper.group("FAILURE_MSG"))))
         raise ParsingDone
Beispiel #12
0
 def _host_key_verification(self, line):
     if self._regex_helper.search_compiled(Ssh._re_host_key_verification_failed, line):
         if self._hosts_file:
             self._handle_failed_host_key_verification()
         else:
             self.set_exception(CommandFailure(self, "command failed in line '{}'".format(line)))
         raise ParsingDone()
Beispiel #13
0
    def _parse_sent_password(self, line):
        """
        Sends password if necessary.

        :param line: Line from device.
        :return: None.
        :raises  ParsingDone: if password was sent.
        """
        if (not self._sent_password) and self._is_password_requested(line):
            try:
                pwd = self._passwords.pop(0)
                self._last_password = pwd
                self.connection.sendline(pwd, encrypt=self.encrypt_password)
            except IndexError:
                if self.repeat_password:
                    self.connection.sendline(self._last_password,
                                             encrypt=self.encrypt_password)
                else:
                    self.set_exception(
                        CommandFailure(
                            self,
                            "Password was requested but no more passwords provided."
                        ))
                    self.break_cmd()
            self._sent_password = True
            raise ParsingDone()
Beispiel #14
0
 def _calculate_seconds(self, val_str, line):
     """
     Calculates seconds from fragment of output with time.
     :param val_str: Fragment with time.
     :param line: Line from device.
     :return: Int of seconds, converted from passed time.
     """
     seconds = 0
     if self._regex_helper.search_compiled(Uptime._re_days, val_str):
         seconds = 24 * 3600 * int(
             self._regex_helper.group("DAYS")) + 3600 * int(
                 self._regex_helper.group("HRS")) + 60 * int(
                     self._regex_helper.group("MINS"))
     elif self._regex_helper.search_compiled(Uptime._re_days_minutes,
                                             val_str):
         seconds = 24 * 3600 * int(self._regex_helper.group(
             "DAYS")) + 60 * int(self._regex_helper.group("MINS"))
     elif self._regex_helper.search_compiled(Uptime._re_hours_minutes,
                                             val_str):
         seconds = 3600 * int(self._regex_helper.group("HRS")) + 60 * int(
             self._regex_helper.group("MINS"))
     elif self._regex_helper.search_compiled(self._re_minutes, val_str):
         seconds = 60 * int(self._regex_helper.group("MINS"))
     else:
         self.set_exception(
             CommandFailure(
                 self,
                 "Unsupported string format in line '{}'".format(line)))
     return seconds
Beispiel #15
0
    def _send_password_if_requested(self, line):
        """
        Sends server if requested by server.

        :param line: Line from device.
        :return: None but raises ParsingDone if password was sent.
        """
        if (not self._sent) and self._is_password_requested(line):
            try:
                pwd = self._passwords.pop(0)
                self._last_password = pwd
                self.connection.send("{}{}".format(pwd, self.target_newline),
                                     encrypt=self.encrypt_password)
            except IndexError:
                if self.repeat_password:
                    self.connection.send("{}{}".format(self._last_password,
                                                       self.target_newline),
                                         encrypt=self.encrypt_password)
                else:
                    self.set_exception(
                        CommandFailure(
                            self,
                            "Password was requested but no more passwords provided."
                        ))
                    self.break_cmd()
            self._sent_login = False
            self._sent = True
            raise ParsingDone()
Beispiel #16
0
 def on_new_line(self, line, is_full_line):
     if self._cmd_output_started and self._regex_helper.search(
             r'(cp\: cannot access)', line):
         self.set_exception(
             CommandFailure(self, "ERROR: {}".format(
                 self._regex_helper.group(1))))
     return super(Cp, self).on_new_line(line, is_full_line)
Beispiel #17
0
        def secure_data_received(data, timestamp):
            try:
                if connection_observer.done() or self._in_shutdown:
                    return  # even not unsubscribed secure_data_received() won't pass data to done observer
                with observer_lock:
                    connection_observer.data_received(data, timestamp)
                    connection_observer.life_status.last_feed_time = time.time(
                    )

            except Exception as exc:  # TODO: handling stacktrace
                # observers should not raise exceptions during data parsing
                # but if they do so - we fix it
                with observer_lock:
                    self.logger.warning(
                        "Unhandled exception from '{} 'caught by runner. '{}' : '{}'."
                        .format(connection_observer, exc, repr(exc)))
                    ex_msg = "Unexpected exception from {} caught by runner when processing data >>{}<< at '{}':" \
                             " >>>{}<<< -> repr: >>>{}<<<".format(connection_observer, data, timestamp, exc, repr(exc))
                    if connection_observer.is_command():
                        ex = CommandFailure(command=connection_observer,
                                            message=ex_msg)
                    else:
                        ex = MolerException(ex_msg)
                    connection_observer.set_exception(ex)
            finally:
                if connection_observer.done(
                ) and not connection_observer.cancelled():
                    if connection_observer._exception:
                        self.logger.debug("{} raised: {!r}".format(
                            connection_observer,
                            connection_observer._exception))
                    else:
                        self.logger.debug("{} returned: {}".format(
                            connection_observer, connection_observer._result))
Beispiel #18
0
 def on_new_line(self, line, is_full_line):
     if self.error_regex and self._regex_helper.search_compiled(
             self.error_regex, line):
         self.set_exception(
             CommandFailure(self,
                            "Found error regex in line '{}'".format(line)))
     return super(RunScript, self).on_new_line(line, is_full_line)
Beispiel #19
0
 def _parse_error(self, line):
     if self._regex_helper.search_compiled(Tail._re_parse_error, line):
         self.set_exception(
             CommandFailure(
                 self,
                 "ERROR: {}".format(self._regex_helper.group("ERROR"))))
         raise ParsingDone
Beispiel #20
0
    def _handle_failed_host_key_verification(self):
        """
        Handles situation when failed host key verification.

        :return: Nothing.
        """
        exception = None
        if "rm" == self.known_hosts_on_failure:
            self.connection.sendline("\nrm -f {}".format(self._hosts_file))
        elif "keygen" == self.known_hosts_on_failure:
            self.connection.sendline("\nssh-keygen -R {}".format(self.host))
        else:
            exception = CommandFailure(self,
                                       "Bad value of parameter known_hosts_on_failure '{}'. "
                                       "Supported values: rm or keygen.".format(
                                           self.known_hosts_on_failure))
        if exception:
            self.set_exception(exception=exception)
        else:
            self._cmd_output_started = False
            self._sent_continue_connecting = False
            self._sent_prompt = False
            self._sent_timeout = False
            self._sent = False
            self.connection.sendline(self.command_string)
Beispiel #21
0
 def _command_failure(self, line):
     if self._regex_helper.search_compiled(Chgrp._re_error, line):
         self.set_exception(
             CommandFailure(
                 self,
                 "ERROR: {}".format(self._regex_helper.group("ERROR_MSG"))))
         raise ParsingDone
Beispiel #22
0
 def _is_done(self, value):
     if value is True and len(self.success_regexes) > 0:
         self._set_exception_without_done(
             CommandFailure(
                 self,
                 "Not found all regex for success. Left: '{}'.".format(
                     self.success_regexes)))
     super(RunScript, self.__class__)._is_done.fset(self, value)
Beispiel #23
0
 def _is_input_file(self):
     is_empty = True
     for file in self.input_files:
         if file and not file.isspace():
             is_empty = False
     if is_empty:
         raise CommandFailure(
             self, "No input file given in: {}".format(self.input_files))
Beispiel #24
0
 def _parse_error(self, line):
     if self._regex_helper.search(Chown._reg_fail, line):
         self.set_exception(
             CommandFailure(
                 self, "ERROR: {}or {}".format(
                     self._regex_helper.group("ERROR"),
                     self._regex_helper.group("ERROR1"))))
         raise ParsingDone
Beispiel #25
0
 def _parse_error_via_output_line(self, line):
     if self._cmd_output_started and self._regex_helper.search_compiled(
             Zip._re_zip_line, line):
         self.set_exception(
             CommandFailure(
                 self,
                 "ERROR: {}".format(self._regex_helper.group("error"))))
         raise ParsingDone
Beispiel #26
0
 def _set_result(self):
     if not self._result_set:
         for name in self.names:
             if not name:
                 raise CommandFailure(self, "ERROR: name is empty")
             else:
                 self.current_ret[name] = list()
         self._result_set = True
Beispiel #27
0
 def _container_name_error(self, line):
     if self._regex_helper.search_compiled(LxcInfo._re_container_name_error,
                                           line):
         self.set_exception(
             CommandFailure(
                 self, "NODE_ERROR: {}".format(
                     self._regex_helper.group("NODE_ERROR"))))
         raise ParsingDone
Beispiel #28
0
 def _find_error(self, line):
     for error_regex in self.error_regexes:
         if self._regex_helper.search_compiled(error_regex, line):
             self.set_exception(
                 CommandFailure(
                     self, "Found error regex '{}' in line '{}'".format(
                         error_regex, line)))
             raise ParsingDone()
Beispiel #29
0
 def _command_failure(self, line):
     """
     Checks if line has info about command failure.
     :param line: Line from device.
     :return: Nothing but raises ParsingDone if regex matches.
     """
     if self._regex_helper.search_compiled(Su._re_command_fail, line):
         self.set_exception(
             CommandFailure(
                 self,
                 "ERROR: {}".format(self._regex_helper.group("OPTION"))))
         raise ParsingDone
     elif self._regex_helper.search_compiled(Su._re_wrong_username, line):
         self.set_exception(
             CommandFailure(
                 self,
                 "ERROR: {}".format(self._regex_helper.group("USERNAME"))))
         raise ParsingDone
Beispiel #30
0
 def _command_failure(self, line):
     """
     Checks if line contains information about failure of command
     :param line: Line from device
     :return: Nothing but raises ParsingDone if regex matches.
     """
     if self._regex_helper.search_compiled(Find._re_error, line):
         self.set_exception(CommandFailure(self, "ERROR: {}".format(self._regex_helper.group("ERROR_MSG_FIND"))))
         raise ParsingDone()