"Fossies" - the Fresh Open Source Software Archive

Member "fail2ban-0.11.1/fail2ban/client/beautifier.py" (11 Jan 2020, 7162 Bytes) of package /linux/misc/fail2ban-0.11.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "beautifier.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 0.10.5_vs_0.11.1.

    1 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
    2 # vi: set ft=python sts=4 ts=4 sw=4 noet :
    3 
    4 # This file is part of Fail2Ban.
    5 #
    6 # Fail2Ban is free software; you can redistribute it and/or modify
    7 # it under the terms of the GNU General Public License as published by
    8 # the Free Software Foundation; either version 2 of the License, or
    9 # (at your option) any later version.
   10 #
   11 # Fail2Ban is distributed in the hope that it will be useful,
   12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
   13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   14 # GNU General Public License for more details.
   15 #
   16 # You should have received a copy of the GNU General Public License
   17 # along with Fail2Ban; if not, write to the Free Software
   18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
   19 
   20 __author__ = "Cyril Jaquier, Yaroslav Halchenko"
   21 __copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2013- Yaroslav Halchenko"
   22 __license__ = "GPL"
   23 
   24 from ..exceptions import UnknownJailException, DuplicateJailException
   25 from ..helpers import getLogger, logging
   26 
   27 # Gets the instance of the logger.
   28 logSys = getLogger(__name__)
   29 
   30 
   31 ##
   32 # Beautify the output of the client.
   33 #
   34 # Fail2ban server only return unformatted return codes which need to be
   35 # converted into user readable messages.
   36 
   37 class Beautifier:
   38 
   39     def __init__(self, cmd = None):
   40         self.__inputCmd = cmd
   41 
   42     def setInputCmd(self, cmd):
   43         self.__inputCmd = cmd
   44 
   45     def getInputCmd(self):
   46         return self.__inputCmd
   47 
   48     def beautify(self, response):
   49         logSys.log(5,
   50             "Beautify " + repr(response) + " with " + repr(self.__inputCmd))
   51         inC = self.__inputCmd
   52         msg = response
   53         try:
   54             if inC[0] == "ping":
   55                 msg = "Server replied: " + response
   56             elif inC[0] == "version":
   57                 msg = response
   58             elif inC[0] == "start":
   59                 msg = "Jail started"
   60             elif inC[0] == "stop":
   61                 if len(inC) == 1:
   62                     if response is None:
   63                         msg = "Shutdown successful"
   64                 else:
   65                     if response is None:
   66                         msg = "Jail stopped"
   67             elif inC[0] == "add":
   68                 msg = "Added jail " + response
   69             elif inC[0] == "flushlogs":
   70                 msg = "logs: " + response
   71             elif inC[0] == "echo":
   72                 msg = ' '.join(msg)
   73             elif inC[0:1] == ['status']:
   74                 if len(inC) > 1:
   75                     # Display information
   76                     msg = ["Status for the jail: %s" % inC[1]]
   77                     for n, res1 in enumerate(response):
   78                         prefix1 = "`-" if n == len(response) - 1 else "|-"
   79                         msg.append("%s %s" % (prefix1, res1[0]))
   80                         prefix1 = "   " if n == len(response) - 1 else "|  "
   81                         for m, res2 in enumerate(res1[1]):
   82                             prefix2 = prefix1 + ("`-" if m == len(res1[1]) - 1 else "|-")
   83                             val = " ".join(map(str, res2[1])) if isinstance(res2[1], list) else res2[1]
   84                             msg.append("%s %s:\t%s" % (prefix2, res2[0], val))
   85                 else:
   86                     msg = ["Status"]
   87                     for n, res1 in enumerate(response):
   88                         prefix1 = "`-" if n == len(response) - 1 else "|-"
   89                         val = " ".join(map(str, res1[1])) if isinstance(res1[1], list) else res1[1]
   90                         msg.append("%s %s:\t%s" % (prefix1, res1[0], val))
   91                 msg = "\n".join(msg)
   92             elif len(inC) < 2:
   93                 pass # to few cmd args for below
   94             elif inC[1] == "syslogsocket":
   95                 msg = "Current syslog socket is:\n"
   96                 msg += "`- " + response
   97             elif inC[1] == "logtarget":
   98                 msg = "Current logging target is:\n"
   99                 msg += "`- " + response
  100             elif inC[1:2] == ['loglevel']:
  101                 msg = "Current logging level is "
  102                 msg += repr(logging.getLevelName(response) if isinstance(response, int) else response)
  103             elif inC[1] == "dbfile":
  104                 if response is None:
  105                     msg = "Database currently disabled"
  106                 else:
  107                     msg = "Current database file is:\n"
  108                     msg += "`- " + response
  109             elif inC[1] == "dbpurgeage":
  110                 if response is None:
  111                     msg = "Database currently disabled"
  112                 else:
  113                     msg = "Current database purge age is:\n"
  114                     msg += "`- %iseconds" % response
  115             elif len(inC) < 3:
  116                 pass # to few cmd args for below
  117             elif inC[2] in ("logpath", "addlogpath", "dellogpath"):
  118                 if len(response) == 0:
  119                     msg = "No file is currently monitored"
  120                 else:
  121                     msg = "Current monitored log file(s):\n"
  122                     for path in response[:-1]:
  123                         msg += "|- " + path + "\n"
  124                     msg += "`- " + response[-1]
  125             elif inC[2] == "logencoding":
  126                 msg = "Current log encoding is set to:\n"
  127                 msg += response
  128             elif inC[2] in ("journalmatch", "addjournalmatch", "deljournalmatch"):
  129                 if len(response) == 0:
  130                     msg = "No journal match filter set"
  131                 else:
  132                     msg = "Current match filter:\n"
  133                     msg += ' + '.join(" ".join(res) for res in response)
  134             elif inC[2] == "datepattern":
  135                 msg = "Current date pattern set to: "
  136                 if response is None:
  137                     msg += "Not set/required"
  138                 elif response[0] is None:
  139                     msg += "%s" % response[1]
  140                 else:
  141                     msg += "%s (%s)" % response
  142             elif inC[2] in ("ignoreip", "addignoreip", "delignoreip"):
  143                 if len(response) == 0:
  144                     msg = "No IP address/network is ignored"
  145                 else:
  146                     msg = "These IP addresses/networks are ignored:\n"
  147                     for ip in response[:-1]:
  148                         msg += "|- " + ip + "\n"
  149                     msg += "`- " + response[-1]
  150             elif inC[2] in ("failregex", "addfailregex", "delfailregex",
  151                             "ignoreregex", "addignoreregex", "delignoreregex"):
  152                 if len(response) == 0:
  153                     msg = "No regular expression is defined"
  154                 else:
  155                     msg = "The following regular expression are defined:\n"
  156                     c = 0
  157                     for l in response[:-1]:
  158                         msg += "|- [" + str(c) + "]: " + l + "\n"
  159                         c += 1
  160                     msg += "`- [" + str(c) + "]: " + response[-1]
  161             elif inC[2] == "actions":
  162                 if len(response) == 0:
  163                     msg = "No actions for jail %s" % inC[1]
  164                 else:
  165                     msg = "The jail %s has the following actions:\n" % inC[1]
  166                     msg += ", ".join(response)
  167             elif inC[2] == "actionproperties":
  168                 if len(response) == 0:
  169                     msg = "No properties for jail %s action %s" % (
  170                         inC[1], inC[3])
  171                 else:
  172                     msg = "The jail %s action %s has the following " \
  173                         "properties:\n" % (inC[1], inC[3])
  174                     msg += ", ".join(response)
  175             elif inC[2] == "actionmethods":
  176                 if len(response) == 0:
  177                     msg = "No methods for jail %s action %s" % (
  178                         inC[1], inC[3])
  179                 else:
  180                     msg = "The jail %s action %s has the following " \
  181                         "methods:\n" % (inC[1], inC[3])
  182                     msg += ", ".join(response)
  183             elif inC[2] == "banip" and inC[0] == "get":
  184                 if isinstance(response, list):
  185                     sep = " " if len(inC) <= 3 else inC[3]
  186                     if sep == "--with-time":
  187                         sep = "\n"
  188                     msg = sep.join(response)
  189         except Exception:
  190             logSys.warning("Beautifier error. Please report the error")
  191             logSys.error("Beautify %r with %r failed", response, self.__inputCmd,
  192                 exc_info=logSys.getEffectiveLevel()<=logging.DEBUG)
  193             msg = repr(msg) + repr(response)
  194         return msg
  195 
  196     def beautifyError(self, response):
  197         logSys.debug("Beautify (error) %r with %r", response, self.__inputCmd)
  198         msg = response
  199         if isinstance(response, UnknownJailException):
  200             msg = "Sorry but the jail '" + response.args[0] + "' does not exist"
  201         elif isinstance(response, IndexError):
  202             msg = "Sorry but the command is invalid"
  203         elif isinstance(response, DuplicateJailException):
  204             msg = "The jail '" + response.args[0] + "' already exists"
  205         return msg