Mini Shell

Direktori : /proc/self/root/proc/thread-self/root/opt/tier1adv/bin/
Upload File :
Current File : //proc/self/root/proc/thread-self/root/opt/tier1adv/bin/unblock

#!/opt/imh-python/bin/python3
"""Unblocks an IP if the IP is blocked in the firewall"""

import subprocess
from typing import Union
import sys
from argparse import ArgumentParser
import netaddr

sys.path.insert(0, '/opt/support/lib')
from output import err_exit, print_listed
import arg_types
import firewall_tools as fw


def parse_args() -> list[netaddr.IPAddress]:
    """Parse IPs from commandline args"""
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        'ips',
        metavar='IP_ADDRESS',
        nargs='+',
        type=arg_types.ipaddress,
        help='IP to check (may be either IPv4 or IPv6)',
    )
    return parser.parse_args().ips


def main():
    """main function"""
    ips = parse_args()
    fw_name, fw_cmd, fw_data = fw.fw_info()
    print('This server is using', fw_name)
    for ipaddr in ips:
        if fw_name == 'ipset+fail2ban':
            listed, f2b_jail = fw.ipset_fail2ban_check(fw_data, ipaddr)
        else:  # APF or CSF
            listed = str(ipaddr) in fw_data
            print_listed(ipaddr, listed, f'the {fw_name} deny list')
        if not listed:
            print('Not attempting to unblock', ipaddr)
            continue
        if fw_name == 'ipset+fail2ban':
            if f2b_jail:
                unblock('fail2ban', ipaddr, f2b_jail=f2b_jail)
            else:
                unblock('ipset', ipaddr)
        else:
            unblock(fw_name, ipaddr, fw_cmd)


def unblock(
    fw_name: str,
    ipaddr: netaddr.IPAddress,
    fw_cmd: Union[str, None] = None,
    f2b_jail: Union[str, None] = None,
):
    print(f'Attempting to unblock {ipaddr}...')
    if fw_name == 'APF':
        subprocess.call([fw_cmd, '-u', str(ipaddr)])
        print_listed(ipaddr, fw.check_iptables(ipaddr), 'iptables')
    elif fw_name == 'fail2ban':
        subprocess.call(['/usr/bin/fail2ban-client', 'unban', str(ipaddr)])
        print(f'Adding IP to fail2ban ignore list for {f2b_jail} jail...')
        subprocess.call(
            [
                '/usr/bin/fail2ban-client',
                'set',
                f2b_jail,
                'addignoreip',
                str(ipaddr),
            ]
        )
    elif fw_name == 'ipset':
        err_exit(
            f'ERROR: {ipaddr} was manually added to an ipset list. '
            'Please escalate for assistance.'
        )
    else:
        assert fw_name == 'CSF'
        subprocess.call([fw_cmd, '-dr', str(ipaddr)])
        print_listed(ipaddr, fw.check_iptables(ipaddr), 'iptables')


if __name__ == '__main__':
    main()

Zerion Mini Shell 1.0