"Fossies" - the Fresh Open Source Software Archive

Member "fail2ban-0.11.1/setup.py" (11 Jan 2020, 9894 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 "setup.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 #!/usr/bin/env python
    2 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
    3 # vi: set ft=python sts=4 ts=4 sw=4 noet :
    4 
    5 # This file is part of Fail2Ban.
    6 #
    7 # Fail2Ban is free software; you can redistribute it and/or modify
    8 # it under the terms of the GNU General Public License as published by
    9 # the Free Software Foundation; either version 2 of the License, or
   10 # (at your option) any later version.
   11 #
   12 # Fail2Ban is distributed in the hope that it will be useful,
   13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
   14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   15 # GNU General Public License for more details.
   16 #
   17 # You should have received a copy of the GNU General Public License
   18 # along with Fail2Ban; if not, write to the Free Software
   19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
   20 
   21 __author__ = "Cyril Jaquier, Steven Hiscocks, Yaroslav Halchenko"
   22 __copyright__ = "Copyright (c) 2004 Cyril Jaquier, 2008-2016 Fail2Ban Contributors"
   23 __license__ = "GPL"
   24 
   25 import platform
   26 
   27 try:
   28     import setuptools
   29     from setuptools import setup
   30     from setuptools.command.install import install
   31     from setuptools.command.install_scripts import install_scripts
   32 except ImportError:
   33     setuptools = None
   34     from distutils.core import setup
   35 
   36 # all versions
   37 from distutils.command.build_py import build_py
   38 from distutils.command.build_scripts import build_scripts
   39 if setuptools is None:
   40     from distutils.command.install import install
   41     from distutils.command.install_scripts import install_scripts
   42 try:
   43     # python 3.x
   44     from distutils.command.build_py import build_py_2to3
   45     from distutils.command.build_scripts import build_scripts_2to3
   46     _2to3 = True
   47 except ImportError:
   48     # python 2.x
   49     _2to3 = False
   50 
   51 import os
   52 from os.path import isfile, join, isdir, realpath
   53 import re
   54 import sys
   55 import warnings
   56 from glob import glob
   57 
   58 from fail2ban.setup import updatePyExec
   59 
   60 
   61 source_dir = os.path.realpath(os.path.dirname(
   62     # __file__ seems to be overwritten sometimes on some python versions (e.g. bug of 2.6 by running under cProfile, etc.):
   63     sys.argv[0] if os.path.basename(sys.argv[0]) == 'setup.py' else __file__
   64 ))
   65 
   66 # Wrapper to install python binding (to current python version):
   67 class install_scripts_f2b(install_scripts):
   68 
   69     def get_outputs(self):
   70         outputs = install_scripts.get_outputs(self)
   71         # setup.py --dry-run install:
   72         dry_run = not outputs
   73         self.update_scripts(dry_run)
   74         if dry_run:
   75             #bindir = self.install_dir
   76             bindir = self.build_dir
   77             print('creating fail2ban-python binding -> %s (dry-run, real path can be different)' % (bindir,))
   78             print('Copying content of %s to %s' % (self.build_dir, self.install_dir));
   79             return outputs
   80         fn = None
   81         for fn in outputs:
   82             if os.path.basename(fn) == 'fail2ban-server':
   83                 break
   84         bindir = os.path.dirname(fn)
   85         print('creating fail2ban-python binding -> %s' % (bindir,))
   86         updatePyExec(bindir)
   87         return outputs
   88 
   89     def update_scripts(self, dry_run=False):
   90         buildroot = os.path.dirname(self.build_dir)
   91         install_dir = self.install_dir
   92         try:
   93             # remove root-base from install scripts path:
   94             root = self.distribution.command_options['install']['root'][1]
   95             if install_dir.startswith(root):
   96                 install_dir = install_dir[len(root):]
   97         except: # pragma: no cover
   98             print('WARNING: Cannot find root-base option, check the bin-path to fail2ban-scripts in "fail2ban.service".')
   99         print('Creating %s/fail2ban.service (from fail2ban.service.in): @BINDIR@ -> %s' % (buildroot, install_dir))
  100         with open(os.path.join(source_dir, 'files/fail2ban.service.in'), 'r') as fn:
  101             lines = fn.readlines()
  102         fn = None
  103         if not dry_run:
  104             fn = open(os.path.join(buildroot, 'fail2ban.service'), 'w')
  105         try:
  106             for ln in lines:
  107                 ln = re.sub(r'@BINDIR@', lambda v: install_dir, ln)
  108                 if dry_run:
  109                     sys.stdout.write(' | ' + ln)
  110                     continue
  111                 fn.write(ln)
  112         finally:
  113             if fn: fn.close()
  114         if dry_run:
  115             print(' `')
  116 
  117 
  118 # Wrapper to specify fail2ban own options:
  119 class install_command_f2b(install):
  120     user_options = install.user_options + [
  121         ('disable-2to3', None, 'Specify to deactivate 2to3, e.g. if the install runs from fail2ban test-cases.'),
  122         ('without-tests', None, 'without tests files installation'),
  123     ]
  124     def initialize_options(self):
  125         self.disable_2to3 = None
  126         self.without_tests = None
  127         install.initialize_options(self)
  128     def finalize_options(self):
  129         global _2to3
  130         ## in the test cases 2to3 should be already done (fail2ban-2to3):
  131         if self.disable_2to3:
  132             _2to3 = False
  133         if _2to3:
  134             cmdclass = self.distribution.cmdclass
  135             cmdclass['build_py'] = build_py_2to3
  136             cmdclass['build_scripts'] = build_scripts_2to3
  137         if not self.without_tests:
  138             self.distribution.scripts += [
  139                 'bin/fail2ban-testcases',
  140             ]
  141 
  142             self.distribution.packages += [
  143                 'fail2ban.tests',
  144                 'fail2ban.tests.action_d',
  145             ]
  146 
  147             self.distribution.package_data = {
  148                 'fail2ban.tests':
  149                     [ join(w[0], f).replace("fail2ban/tests/", "", 1)
  150                         for w in os.walk('fail2ban/tests/files')
  151                         for f in w[2]] +
  152                     [ join(w[0], f).replace("fail2ban/tests/", "", 1)
  153                         for w in os.walk('fail2ban/tests/config')
  154                         for f in w[2]] +
  155                     [ join(w[0], f).replace("fail2ban/tests/", "", 1)
  156                         for w in os.walk('fail2ban/tests/action_d')
  157                         for f in w[2]]
  158             }
  159         install.finalize_options(self)
  160     def run(self):
  161         install.run(self)
  162 
  163 
  164 # Update fail2ban-python env to current python version (where f2b-modules located/installed)
  165 updatePyExec(os.path.join(source_dir, 'bin'))
  166 
  167 if setuptools and "test" in sys.argv:
  168     import logging
  169     logSys = logging.getLogger("fail2ban")
  170     hdlr = logging.StreamHandler(sys.stdout)
  171     fmt = logging.Formatter("%(asctime)-15s %(message)s")
  172     hdlr.setFormatter(fmt)
  173     logSys.addHandler(hdlr)
  174     if set(["-q", "--quiet"]) & set(sys.argv):
  175         logSys.setLevel(logging.CRITICAL)
  176         warnings.simplefilter("ignore")
  177         sys.warnoptions.append("ignore")
  178     elif set(["-v", "--verbose"]) & set(sys.argv):
  179         logSys.setLevel(logging.DEBUG)
  180     else:
  181         logSys.setLevel(logging.INFO)
  182 elif "test" in sys.argv:
  183     print("python distribute required to execute fail2ban tests")
  184     print("")
  185 
  186 longdesc = '''
  187 Fail2Ban scans log files like /var/log/pwdfail or
  188 /var/log/apache/error_log and bans IP that makes
  189 too many password failures. It updates firewall rules
  190 to reject the IP address or executes user defined
  191 commands.'''
  192 
  193 if setuptools:
  194     setup_extra = {
  195         'test_suite': "fail2ban.tests.utils.gatherTests",
  196         'use_2to3': True,
  197     }
  198 else:
  199     setup_extra = {}
  200 
  201 data_files_extra = []
  202 if os.path.exists('/var/run'):
  203     # if we are on the system with /var/run -- we are to use it for having fail2ban/
  204     # directory there for socket file etc.
  205     # realpath is used to possibly resolve /var/run -> /run symlink
  206     data_files_extra += [(realpath('/var/run/fail2ban'), '')]
  207 
  208 # Installing documentation files only under Linux or other GNU/ systems
  209 # (e.g. GNU/kFreeBSD), since others might have protective mechanisms forbidding
  210 # installation there (see e.g. #1233)
  211 platform_system = platform.system().lower()
  212 doc_files = ['README.md', 'DEVELOP', 'FILTERS', 'doc/run-rootless.txt']
  213 if platform_system in ('solaris', 'sunos'):
  214     doc_files.append('README.Solaris')
  215 if platform_system in ('linux', 'solaris', 'sunos') or platform_system.startswith('gnu'):
  216     data_files_extra.append(
  217         ('/usr/share/doc/fail2ban', doc_files)
  218     )
  219 
  220 # Get version number, avoiding importing fail2ban.
  221 # This is due to tests not functioning for python3 as 2to3 takes place later
  222 exec(open(join("fail2ban", "version.py")).read())
  223 
  224 setup(
  225     name = "fail2ban",
  226     version = version,
  227     description = "Ban IPs that make too many password failures",
  228     long_description = longdesc,
  229     author = "Cyril Jaquier & Fail2Ban Contributors",
  230     author_email = "cyril.jaquier@fail2ban.org",
  231     url = "http://www.fail2ban.org",
  232     license = "GPL",
  233     platforms = "Posix",
  234     cmdclass = {
  235         'build_py': build_py, 'build_scripts': build_scripts,
  236         'install_scripts': install_scripts_f2b, 'install': install_command_f2b
  237     },
  238     scripts = [
  239         'bin/fail2ban-client',
  240         'bin/fail2ban-server',
  241         'bin/fail2ban-regex',
  242         # 'bin/fail2ban-python', -- link (binary), will be installed via install_scripts_f2b wrapper
  243     ],
  244     packages = [
  245         'fail2ban',
  246         'fail2ban.client',
  247         'fail2ban.server',
  248     ],
  249     data_files = [
  250         ('/etc/fail2ban',
  251             glob("config/*.conf")
  252         ),
  253         ('/etc/fail2ban/filter.d',
  254             glob("config/filter.d/*.conf")
  255         ),
  256         ('/etc/fail2ban/filter.d/ignorecommands',
  257             [p for p in glob("config/filter.d/ignorecommands/*") if isfile(p)]
  258         ),
  259         ('/etc/fail2ban/action.d',
  260             glob("config/action.d/*.conf") +
  261             glob("config/action.d/*.py")
  262         ),
  263         ('/etc/fail2ban/fail2ban.d',
  264             ''
  265         ),
  266         ('/etc/fail2ban/jail.d',
  267             ''
  268         ),
  269         ('/var/lib/fail2ban',
  270             ''
  271         ),
  272     ] + data_files_extra,
  273     **setup_extra
  274 )
  275 
  276 # Do some checks after installation
  277 # Search for obsolete files.
  278 obsoleteFiles = []
  279 elements = {
  280     "/etc/":
  281         [
  282             "fail2ban.conf"
  283         ],
  284     "/usr/bin/":
  285         [
  286             "fail2ban.py"
  287         ],
  288     "/usr/lib/fail2ban/":
  289         [
  290             "version.py",
  291             "protocol.py"
  292         ]
  293 }
  294 
  295 for directory in elements:
  296     for f in elements[directory]:
  297         path = join(directory, f)
  298         if isfile(path):
  299             obsoleteFiles.append(path)
  300 
  301 if obsoleteFiles:
  302     print("")
  303     print("Obsolete files from previous Fail2Ban versions were found on "
  304           "your system.")
  305     print("Please delete them:")
  306     print("")
  307     for f in obsoleteFiles:
  308         print("\t" + f)
  309     print("")
  310 
  311 if isdir("/usr/lib/fail2ban"):
  312     print("")
  313     print("Fail2ban is not installed under /usr/lib anymore. The new "
  314           "location is under /usr/share. Please remove the directory "
  315           "/usr/lib/fail2ban and everything under this directory.")
  316     print("")
  317 
  318 # Update config file
  319 if sys.argv[1] == "install":
  320     print("")
  321     print("Please do not forget to update your configuration files.")
  322     print("They are in \"/etc/fail2ban/\".")
  323     print("")
  324     print("You can also install systemd service-unit file from \"build/fail2ban.service\"")
  325     print("resp. corresponding init script from \"files/*-initd\".")
  326     print("")