systemd.journal.Reader

Here are the examples of the python api systemd.journal.Reader taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

25 Examples 7

Example 1

Project: journal-brief
Source File: test_main.py
View license
    def test_dry_run(self):
        (flexmock(journal.Reader, add_match=None, add_disjunction=None)
            .should_receive('get_next')
            .and_return({'__CURSOR': '1',
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'message'})
            .and_return({}))

        with NamedTemporaryFile(mode='wt') as configfile:
            with NamedTemporaryFile(mode='rt') as cursorfile:
                configfile.write('cursor-file: {0}\n'.format(cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name, '--dry-run'])
                cli.run()
                assert not cursorfile.read()

Example 2

Project: journal-brief
Source File: test_main.py
View license
    def test_log_level(self):
        flexmock(journal.Reader, add_match=None, add_disjunction=None)
        (flexmock(journal.Reader)
            .should_receive('log_level')
            .with_args(journal.LOG_ERR)
            .once())
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({}))

        with NamedTemporaryFile(mode='wt') as configfile:
            with NamedTemporaryFile(mode='rt') as cursorfile:
                configfile.write('cursor-file: {0}\n'.format(cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name, '-p', 'err'])
                cli.run()

Example 3

Project: journal-brief
Source File: test_main.py
View license
    def test_debrief_no_input(self, capsys):
        """
        Check it handles there being no input
        """
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({}))

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("cursor-file: {0}".format(cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name, 'debrief'])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        assert not out

Example 4

Project: journal-brief
Source File: test_filter.py
View license
    def test_no_exclusions(self):
        entries = [{'MESSAGE': 'message 1'},
                   {'MESSAGE': 'message 2'}]
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return(entries[0])
            .and_return(entries[1])
            .and_return({}))

        formatter = EntryFormatter()
        jfilter = JournalFilter(journal.Reader(), [formatter])
        output = StringIO()
        jfilter.format(output)
        output.seek(0)
        lines = output.read().splitlines()
        assert lines == [entry['MESSAGE'] for entry in entries]

Example 5

Project: journal-brief
Source File: test_filter.py
View license
    def test_statistics(self):
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({'MESSAGE': 'exclude'})
            .and_return({'MESSAGE': 'include'})
            .and_return({}))

        exclusions = [{'MESSAGE': ['exclude']}]
        formatter = EntryFormatter()
        jfilter = JournalFilter(journal.Reader(), [formatter],
                                default_exclusions=exclusions)
        output = StringIO()
        jfilter.format(output)
        statistics = jfilter.get_statistics()
        assert len(statistics) == 1
        assert statistics[0].hits == 1

Example 6

Project: journal-brief
Source File: test_journal_brief.py
View license
    def watch_reader(self):
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({}))
        watcher = Watcher()
        for func in ['add_match',
                     'add_conjunction',
                     'add_disjunction',
                     'log_level',
                     'this_boot']:
            (flexmock(journal.Reader)
                .should_receive(func)
                .replace_with(watcher.watch_call(func)))

        return watcher

Example 7

Project: journal-brief
Source File: test_journal_brief.py
View license
    def test_without_cursor(self, tmpdir):
        final_cursor = '2'
        (flexmock(journal.Reader)
            .should_receive('seek_cursor')
            .never())
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({'__CURSOR': '1'})
            .and_return({'__CURSOR': final_cursor})
            .and_return({}))

        cursor_file = os.path.join(str(tmpdir), 'cursor')
        with LatestJournalEntries(cursor_file=cursor_file) as entries:
            e = list(entries)

        assert len(e) == 2
        with open(cursor_file, 'rt') as fp:
            assert fp.read() == final_cursor

Example 8

Project: fail2ban
Source File: filtersystemd.py
View license
	def __init__(self, jail, **kwargs):
		jrnlargs = FilterSystemd._getJournalArgs(kwargs)
		JournalFilter.__init__(self, jail, **kwargs)
		self.__modified = 0
		# Initialise systemd-journal connection
		self.__journal = journal.Reader(**jrnlargs)
		self.__matches = []
		self.setDatePattern(None)
		logSys.debug("Created FilterSystemd")

Example 9

View license
def find_boots(message_id):
    """Find all boots with this message id.

    Returns the entries of all found boots.
    """
    j = journal.Reader()
    j.add_match(MESSAGE_ID=message_id.hex,  # identify the message
                _UID=0)                     # prevent spoofing of logs

    oldboot = None
    for entry in j:
        boot = entry['_BOOT_ID']
        if boot == oldboot:
            continue
        oldboot = boot
        yield entry

Example 10

Project: journal-brief
Source File: journal_brief.py
View license
    def __init__(self, cursor_file=None, reader=None, dry_run=False,
                 seek_cursor=True):
        """
        Constructor

        :param cursor_file: str, filename of cursor bookmark file
        :param reader: systemd.journal.Reader instance
        :param dry_run: bool, whether to update the cursor file
        :param seek_cursor: bool, whether to seek to bookmark first
        """
        super(LatestJournalEntries, self).__init__()

        self.cursor_file = cursor_file
        try:
            with open(self.cursor_file, "rt") as fp:
                self.cursor = fp.read()
        except IOError as ex:
            if ex.errno == errno.ENOENT:
                self.cursor = None
            else:
                raise

        if reader is None:
            reader = journal.Reader()

        if seek_cursor and self.cursor:
            log.debug("Seeking to %s", self.cursor)
            reader.seek_cursor(self.cursor)
            reader.get_next()

        self.reader = reader
        self.dry_run = dry_run

Example 11

Project: journal-brief
Source File: test_main.py
View license
    def test_normal_run(self, capsys):
        (flexmock(journal.Reader, add_match=None, add_disjunction=None)
            .should_receive('get_next')
            .and_return({'__CURSOR': '1',
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'message1'})
            .and_return({'__CURSOR': '2',
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'message2'})
            .and_return({}))

        with NamedTemporaryFile(mode='wt') as configfile:
            with NamedTemporaryFile(mode='rt') as cursorfile:
                configfile.write('cursor-file: {0}\n'.format(cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        assert len(out.splitlines()) == 2

Example 12

Project: journal-brief
Source File: test_main.py
View license
    def test_this_boot(self):
        final_cursor = '1'
        flexmock(journal.Reader, add_match=None, add_disjunction=None)
        (flexmock(journal.Reader)
            .should_receive('this_boot')
            .once())
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({'__CURSOR': final_cursor,
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'message'})
            .and_return({}))

        with NamedTemporaryFile(mode='wt') as configfile:
            with NamedTemporaryFile(mode='w+t') as cursorfile:
                configfile.write('cursor-file: {0}\n'.format(cursorfile.name))
                configfile.flush()
                cursorfile.write(final_cursor)
                cursorfile.flush()
                cli = CLI(args=['--conf', configfile.name, '-b'])
                cli.run()
                cursorfile.seek(0)
                assert cursorfile.read() == final_cursor

Example 13

Project: journal-brief
Source File: test_main.py
View license
    def test_stats(self, capsys):
        (flexmock(journal.Reader, add_match=None, add_disjunction=None)
            .should_receive('get_next')
            .and_return({'__CURSOR': '1',
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'exclude'})
            .and_return({'__CURSOR': '2',
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'include'})
            .and_return({}))

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("""
cursor-file: {cursor}
exclusions:
- MESSAGE: [exclude]
""".format(cursor=cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name, 'stats'])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        assert out == "\n".join([" FREQUENCY  EXCLUSION",
                                 "         1  {'MESSAGE': ['exclude']}",
                                 ""])

Example 14

Project: journal-brief
Source File: test_main.py
View license
    def test_debrief(self, capsys):
        entries = [
            {'__CURSOR': '1',
             'MESSAGE': 'message 1',
             'KEY': 'multiple',
             '__REALTIME_TIMESTAMP': datetime.now()},
            {'__CURSOR': '2',
             'MESSAGE': 'message 1',
             'KEY': 'multiple',
             '__REALTIME_TIMESTAMP': datetime.now()},
            {'__CURSOR': '3',
             'MESSAGE': 'message 1',
             '__REALTIME_TIMESTAMP': datetime.now()},
            {'__CURSOR': '4',
             'MESSAGE': 'message 1',
             '__REALTIME_TIMESTAMP': datetime.now()},
            {'__CURSOR': '5',
             'MESSAGE': 'message 2',
             'KEY': 'multiple',
             '__REALTIME_TIMESTAMP': datetime.now()},
            {'__CURSOR': '6',
             'MESSAGE': 'message 2',
             'KEY': 'single',
             '__REALTIME_TIMESTAMP': datetime.now()},
        ]
        expectation = (flexmock(journal.Reader).should_receive('get_next'))
        for entry in entries:
            expectation = expectation.and_return(entry)

        expectation.and_return({})

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("cursor-file: {0}".format(cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name, 'debrief'])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        assert out == "\n".join([
            "exclusions:",
            "  # 4 occurrences (out of 6)",
            "  - MESSAGE:",
            "    - message 1",
            "  # 2 occurrences (out of 2)",
            "  - MESSAGE:",
            "    - message 2",
            ''])

Example 15

Project: journal-brief
Source File: test_main.py
View license
    def test_exclusions_yaml(self, capsys):
        (flexmock(journal.Reader, add_match=None, add_disjunction=None)
            .should_receive('get_next')
            .and_return({'__CURSOR': '1',
                         '__REALTIME_TIMESTAMP': datetime.now(),
                         'MESSAGE': 'message'})
            .and_return({}))

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("""
cursor-file: {cursor}
exclusions:
- MESSAGE: [1]
""".format(cursor=cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        assert 'message' in out

Example 16

Project: journal-brief
Source File: test_main.py
View license
    def test_inclusions_yaml(self):
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return({}))
        watcher = Watcher()
        (flexmock(journal.Reader)
            .should_receive('add_match')
            .replace_with(watcher.watch_call('add_match')))
        (flexmock(journal.Reader)
            .should_receive('add_conjunction')
            .replace_with(watcher.watch_call('add_conjunction')))
        (flexmock(journal.Reader)
            .should_receive('add_disjunction')
            .replace_with(watcher.watch_call('add_disjunction')))

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("""
cursor-file: {cursor}
inclusions:
- PRIORITY: [0, 1, 2, 3]
- PRIORITY: [4, 5, 6]
  _SYSTEMD_UNIT: [myservice.service]
""".format(cursor=cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name])
                cli.run()

        # Should add matches for all of the first group
        assert set(watcher.calls[:4]) == set([
            ('add_match', (), "{'PRIORITY': '0'}"),
            ('add_match', (), "{'PRIORITY': '1'}"),
            ('add_match', (), "{'PRIORITY': '2'}"),
            ('add_match', (), "{'PRIORITY': '3'}"),
        ])

        # Then a disjunction
        assert watcher.calls[4] == ('add_disjunction', (), '{}')

        # Then matches for all of the second group
        assert set(watcher.calls[5:9]) == set([
            ('add_match', (), "{'PRIORITY': '4'}"),
            ('add_match', (), "{'PRIORITY': '5'}"),
            ('add_match', (), "{'PRIORITY': '6'}"),
            ('add_match', (), "{'_SYSTEMD_UNIT': 'myservice.service'}"),
        ])

        # And nothing else
        assert len(watcher.calls) == 9

Example 17

Project: journal-brief
Source File: test_main.py
View license
    def test_multiple_output_formats(self, capsys):
        entry = {
            '__CURSOR': '1',
            '__REALTIME_TIMESTAMP': datetime.now(),
            'MESSAGE': 'message',
        }

        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return(entry)
            .and_return({}))

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("""
cursor-file: {cursor}
""".format(cursor=cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name,
                                '-o', 'cat,cat,json'])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        lines = out.splitlines()
        assert len(lines) == 3
        assert lines[0] == lines[1] == 'message'
        output = json.loads(lines[2])
        del entry['__REALTIME_TIMESTAMP']
        del output['__REALTIME_TIMESTAMP']
        assert output == entry

Example 18

Project: journal-brief
Source File: test_main.py
View license
    def test_formatter_filter(self, capsys):
        """
        Just a coverage test
        """
        entry = {
            '__CURSOR': '1',
            '__REALTIME_TIMESTAMP': datetime.now(),
            'PRIORITY': 6,
            'MESSAGE': 'login session started',
            'MESSAGE_ID': uuid.UUID('8d45620c1a4348dbb17410da57c60c66'),
            '_COMM': 'systemd-logind',
            'USER_ID': 'abc',
        }

        (flexmock(journal.Reader, add_match=None, add_disjunction=None)
            .should_receive('get_next')
            .and_return(entry)
            .and_return({}))

        with NamedTemporaryFile(mode='rt') as cursorfile:
            with NamedTemporaryFile(mode='wt') as configfile:
                configfile.write("""
cursor-file: {cursor}
""".format(cursor=cursorfile.name))
                configfile.flush()
                cli = CLI(args=['--conf', configfile.name,
                                '-p', 'err', '-o', 'login'])
                cli.run()

        (out, err) = capsys.readouterr()
        assert not err
        assert out

Example 19

Project: journal-brief
Source File: test_filter.py
View license
    def test_exclusion_regexp(self):
        entries = [{'MESSAGE': 'exclude this'},
                   {'MESSAGE': 'message 1'},
                   {'MESSAGE': 'exclude that'},
                   {'MESSAGE': 'message 2'}]

        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return(entries[0])
            .and_return(entries[1])
            .and_return(entries[2])
            .and_return(entries[3])
            .and_return({}))
        exclusions = [{'MESSAGE': ['/1/']},  # shouldn't exclude anything
                      {'MESSAGE': ['/exclude th/']},
                      {'MESSAGE': ['/exclude/']}]
        formatter = EntryFormatter()
        jfilter = JournalFilter(journal.Reader(), [formatter],
                                default_exclusions=exclusions)
        output = StringIO()
        jfilter.format(output)
        output.seek(0)
        lines = output.read().splitlines()
        assert lines == [entry['MESSAGE']
                         for entry in [entries[1]] + [entries[3]]]
        stats = jfilter.get_statistics()
        for stat in stats:
            if stat.exclusion['MESSAGE'] == ['/1/']:
                assert stat.hits == 0
                break

Example 20

Project: journal-brief
Source File: test_filter.py
View license
    def test_formatter_filters(self):
        incl_entries = [
            {
                'TEST': 'yes',
                'MESSAGE': 'message',
            },
            {
                'TEST': 'yes',
                'MESSAGE': 'message',
                'OUTPUT': None,  # Test returning None from format()
            },
        ]
        excl_entries = [
            {
                'TEST': 'no',
                'MESSAGE': 'message',
            },
            {
                'TEST': 'yes',
                'MESSAGE': 'ignore',
            },
        ]
        (flexmock(journal.Reader, add_match=None, add_disjunction=None)
            .should_receive('get_next')
            .and_return(incl_entries[0])
            .and_return(incl_entries[1])
            .and_return(excl_entries[0])
            .and_return(excl_entries[1])
            .and_return({}))

        formatter = MySpecialFormatter()
        jfilter = JournalFilter(journal.Reader(), [formatter])
        jfilter.format(StringIO())
        assert formatter.entries_received == incl_entries

Example 21

Project: journal-brief
Source File: test_journal_brief.py
View license
    def test_with_cursor(self, tmpdir):
        last_cursor = '2'
        final_cursor = '4'
        results = [{'__CURSOR': last_cursor},
                   {'__CURSOR': '3'},
                   {'__CURSOR': final_cursor}]
        (flexmock(journal.Reader)
            .should_receive('seek_cursor')
            .with_args(last_cursor)
            .once())
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return(results[0])
            .and_return(results[1])
            .and_return(results[2])
            .and_return({}))

        cursor_file = os.path.join(str(tmpdir), 'cursor')
        with open(cursor_file, 'wt') as fp:
            fp.write(last_cursor)

        with LatestJournalEntries(cursor_file=cursor_file) as entries:
            e = list(entries)

        assert e == results[1:]
        with open(cursor_file, 'rt') as fp:
            assert fp.read() == final_cursor

Example 22

Project: journal-brief
Source File: test_journal_brief.py
View license
    def test_no_seek_cursor(self, tmpdir):
        last_cursor = '2'
        final_cursor = '3'
        results = [{'__CURSOR': '1'},
                   {'__CURSOR': last_cursor},
                   {'__CURSOR': final_cursor}]

        (flexmock(journal.Reader)
            .should_receive('seek_cursor')
            .never())
        (flexmock(journal.Reader)
            .should_receive('get_next')
            .and_return(results[0])
            .and_return(results[1])
            .and_return(results[2])
            .and_return({}))

        cursor_file = os.path.join(str(tmpdir), 'cursor')
        with open(cursor_file, 'wt') as fp:
            fp.write(last_cursor)

        with LatestJournalEntries(cursor_file=cursor_file,
                                  seek_cursor=False) as entries:
            e = list(entries)

        assert e == results
        with open(cursor_file, 'rt') as fp:
            assert fp.read() == final_cursor

Example 23

View license
    def collect_answer (self):
        answers = self.troubleshooter.answers
        if not answers['cups_queue_listed']:
            return {}

        parent = self.troubleshooter.get_window ()
        self.answers.update (self.persistent_answers)
        if 'error_log_checkpoint' in self.answers:
            return self.answers

        with NamedTemporaryFile () as tmpf:
            try:
                self.op = TimedOperation (self.authconn.getFile,
                                          args=('/admin/log/error_log',
                                                tmpf.file),
                                          parent=parent)
                self.op.run ()
            except (RuntimeError, cups.IPPError) as e:
                self.answers['error_log_checkpoint_exc'] = e
            except cups.HTTPError as e:
                self.answers['error_log_checkpoint_exc'] = e

                # Abandon the CUPS connection and make another.
                answers = self.troubleshooter.answers
                factory = answers['_authenticated_connection_factory']
                self.authconn = factory.get_connection ()
                self.answers['_authenticated_connection'] = self.authconn

            try:
                statbuf = os.stat (tmpf.file)
            except OSError:
                statbuf = [0, 0, 0, 0, 0, 0, 0]

        self.answers['error_log_checkpoint'] = statbuf[6]
        self.persistent_answers['error_log_checkpoint'] = statbuf[6]

        if journal:
            j = journal.Reader ()
            j.seek_tail ()
            cursor = j.get_previous ()['__CURSOR']
            self.answers['error_log_cursor'] = cursor
            self.persistent_answers['error_log_cursor'] = cursor
            now = datetime.datetime.fromtimestamp (time.time ())
            timestamp = now.strftime ("%F %T")
            self.answers['error_log_timestamp'] = timestamp
            self.persistent_answers['error_log_timestamp'] = timestamp

        return self.answers

Example 24

View license
    def display (self):
        answers = self.troubleshooter.answers
        parent = self.troubleshooter.get_window ()
        self.answers = {}
        checkpoint = answers.get ('error_log_checkpoint')
        cursor = answers.get ('error_log_cursor')
        timestamp = answers.get ('error_log_timestamp')

        if ('error_log' in self.persistent_answers or
            'journal' in self.persistent_answers):
            checkpoint = None
            cursor = None

        def fetch_log (c):
            prompt = c._get_prompt_allowed ()
            c._set_prompt_allowed (False)
            c._connect ()
            with NamedTemporaryFile (delete=False) as tmpf:
                success = False
                try:
                    c.getFile ('/admin/log/error_log', tmpf.file)
                    success = True
                except cups.HTTPError:
                    try:
                        os.remove (tmpf.file)
                    except OSError:
                        pass

                c._set_prompt_allowed (prompt)
                if success:
                    return tmpf.file

            return None

        now = datetime.datetime.fromtimestamp (time.time ()).strftime ("%F %T")
        self.authconn = self.troubleshooter.answers['_authenticated_connection']
        if 'error_log_debug_logging_set' in answers:
            try:
                self.op = TimedOperation (self.authconn.adminGetServerSettings,
                                          parent=parent)
                settings = self.op.run ()
            except cups.IPPError:
                return False

            settings[cups.CUPS_SERVER_DEBUG_LOGGING] = '0'
            orig_settings = answers['cups_server_settings']
            settings['MaxLogSize'] = orig_settings.get ('MaxLogSize', '2000000')
            success = False
            def set_settings (connection, settings):
                connection.adminSetServerSettings (settings)

                # Now reconnect.
                attempt = 1
                while attempt <= 5:
                    try:
                        time.sleep (1)
                        connection._connect ()
                        break
                    except RuntimeError:
                        # Connection failed
                        attempt += 1

            try:

                self.op = TimedOperation (set_settings,
                                          (self.authconn, settings),
                                          parent=parent)
                self.op.run ()
                self.persistent_answers['error_log_debug_logging_unset'] = True
            except cups.IPPError:
                pass

        self.answers = {}
        if journal and cursor is not None:
            def journal_format (x):
                try:
                    priority = "XACEWNIDd"[x['PRIORITY']]
                except (IndexError, TypeError):
                    priority = " "

                return (priority + " " +
                        x['__REALTIME_TIMESTAMP'].strftime("[%m/%b/%Y:%T]") +
                        " " + x['MESSAGE'])

            r = journal.Reader ()
            r.seek_cursor (cursor)
            r.add_match (_SYSTEMD_UNIT="cups.service")
            self.answers['journal'] = [journal_format (x) for x in r]

        if checkpoint is not None:
            self.op = TimedOperation (fetch_log,
                                      (self.authconn,),
                                      parent=parent)
            tmpfname = self.op.run ()
            if tmpfname is not None:
                f = open (tmpfname)
                f.seek (checkpoint)
                lines = f.readlines ()
                os.remove (tmpfname)
                self.answers = { 'error_log': [x.strip () for x in lines] }

        if (len (self.answers.get ('journal', [])) +
            len (self.answers.get ('error_log', []))) == 0:
            cmd = ("su -c 'journalctl -u cups.service "
                   "--since=\"%s\" --until=\"%s\"' > troubleshoot-logs.txt" %
                   (timestamp, now))
            self.entry.set_text (cmd)
            return True

        return False

Example 25

Project: fail2ban
Source File: fail2banregex.py
View license
	def start(self, opts, args):

		cmd_log, cmd_regex = args[:2]

		try:
			if not self.readRegex(cmd_regex, 'fail'):
				return False
			if len(args) == 3 and not self.readRegex(args[2], 'ignore'):
				return False
		except RegexException as e:
			output( 'ERROR: %s' % e )
			return False

		if os.path.isfile(cmd_log):
			try:
				hdlr = open(cmd_log, 'rb')
				output( "Use         log file : %s" % cmd_log )
				output( "Use         encoding : %s" % self.encoding )
				test_lines = self.file_lines_gen(hdlr)
			except IOError as e:
				output( e )
				return False
		elif cmd_log == "systemd-journal": # pragma: no cover
			if not journal:
				output( "Error: systemd library not found. Exiting..." )
				return False
			myjournal = journal.Reader(converters={'__CURSOR': lambda x: x})
			journalmatch = self._journalmatch
			self.setDatePattern(None)
			if journalmatch:
				try:
					for element in journalmatch:
						if element == "+":
							myjournal.add_disjunction()
						else:
							myjournal.add_match(element)
				except ValueError:
					output( "Error: Invalid journalmatch: %s" % shortstr(" ".join(journalmatch)) )
					return False
			output( "Use    journal match : %s" % " ".join(journalmatch) )
			test_lines = journal_lines_gen(myjournal)
		else:
			output( "Use      single line : %s" % shortstr(cmd_log) )
			test_lines = [ cmd_log ]
		output( "" )

		self.process(test_lines)

		if not self.printStats():
			return False

		return True