Skip to content
Snippets Groups Projects
0_setup.py 1.72 KiB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

import utils


def setup(interactive=True):
    # install fail2ban
    utils.log('Install fail2ban')
    cmds = [
        'apt-get update',
        'apt-get install -y fail2ban',
    ]
    utils.run_commands(cmds)
    # configure fail2ban
    utils.log('Configure fail2ban')
    os.makedirs('/etc/fail2ban/filter.d', exist_ok=True)
    os.makedirs('/etc/fail2ban/jail.d', exist_ok=True)
    os.makedirs('/etc/fail2ban/action.d', exist_ok=True)
    dir_path = utils.get_dir(__file__)
    action = 'action_mwl' if utils.get_conf('FAIL2BAN_SEND_EMAIL', '') == '1' else 'action_'
    sender = utils.get_conf('EMAIL_SENDER', 'root@localhost')
    destemail = utils.get_conf('FAIL2BAN_DEST_EMAIL', '') or utils.get_conf('EMAIL_ADMINS', 'root@localhost')
    maxretry = utils.get_conf('FAIL2BAN_MAXRETRY', '6')
    bantime = utils.get_conf('FAIL2BAN_BANTIME', '30')
    cmds = [
        dict(
            line='write',
            template='%s/filter.d/mediaserver.conf' % dir_path,
            target='/etc/fail2ban/filter.d/mediaserver.conf'
        ),
        dict(
            line='write',
            template='%s/jail.d/mediaserver.conf' % dir_path,
            target='/etc/fail2ban/jail.d/mediaserver.conf',
            params=(
                ('{{ action }}', action),
                ('{{ sender }}', sender),
                ('{{ destemail }}', destemail),
                ('{{ maxretry }}', maxretry),
                ('{{ bantime }}', bantime),
            )
        ),
    ]
    utils.run_commands(cmds)
    # restart fail2ban
    utils.log('Enable and restart fail2ban')
    cmds = [
        'systemctl enable fail2ban',
        'systemctl restart fail2ban',
    ]
    utils.run_commands(cmds)