Пример #1
0
def cfg_read_poller(watch_file, folder='data', class_method=False):
    '''Automate Class configuration file poll decorator. apply this decorator to all functions
    that will update configurations loaded in memory from json files. config file must be sent
    in via decorator argument. set class_method argument to true if being used with a class method.'''

    if not isinstance(watch_file, str):
        raise TypeError('watch file must be a string.')

    if (not watch_file.endswith('.json')):
        watch_file = str_join([watch_file, '.json'])

    def decorator(function_to_wrap):
        if (not class_method):

            def wrapper(*args):
                watcher = Watcher(watch_file,
                                  folder,
                                  callback=function_to_wrap)
                watcher.watch(*args)

        else:

            @classmethod
            def wrapper(*args):
                watcher = Watcher(watch_file,
                                  folder,
                                  callback=function_to_wrap)
                watcher.watch(*args)

        return wrapper

    return decorator
Пример #2
0
def configure_webui():
    cert_subject = str_join([
        '/C=US', '/ST=Arizona', '/L=cyberspace', '/O=dnxfirewall',
        '/OU=security', '/CN=dnx.firewall',
        '/[email protected]'
    ])

    generate_cert_commands = [
        f'sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048',
        f'-keyout {SYSTEM_DIR}/ssl/dnx-web.key',
        f'-out {SYSTEM_DIR}/ssl/dnx-web.crt', f'-subj {cert_subject}'
    ]

    commands = [
        (' '.join(generate_cert_commands),
         'generating dnx webui ssl certificate'),
        (f'sudo cp {UTILITY_DIR}/dnx_web /etc/nginx/sites-available/',
         'configuring management webui'),
        ('ln -s /etc/nginx/sites-available/dnx_web /etc/nginx/sites-enabled/',
         None), ('sudo rm /etc/nginx/sites-enabled/default', None)
    ]

    for command, desc in commands:

        # this allows some commands to ride off of the previous status message and completion %.
        if (desc):
            progress(desc)

        dnx_run(command)
Пример #3
0
    def generate_syslog_message(log):
        message = [
            f'src.ip={log.src_ip}; request={log.request}; category={log.category}; ',
            f'filter={log.reason}; action={log.action}'
        ]

        return str_join(message)
Пример #4
0
def write_configuration(data, filename, *, filepath='dnx_system/data/usr'):
    '''write json data object to file.'''

    if (not filename.endswith('.json')):
        filename = str_join([filename, '.json'])

    with open(f'{HOME_DIR}/{filepath}/{filename}', 'w') as settings:
        json.dump(data, settings, indent=4)
Пример #5
0
def progress(desc):
    global completed_count

    completed_count += 1

    bar_len = 30

    filled_len = int(round(bar_len * completed_count / float(p_total)))
    percents = round(100.0 * completed_count / float(p_total), 1)

    bar = str_join(['#' * filled_len, '=' * (bar_len - filled_len)])
    sys.stdout.write(f'{" "*90}\r')
    sys.stdout.write(
        f'{completed_count}/{p_total} || [{bar}] {percents}% || {desc}\r')
    sys.stdout.flush()
Пример #6
0
    def date(timestamp=None, string=False):
        '''
        return list of year, month, day of current system time as a list of strings. ['2019', '06', '24']

        use timestamp argument to override current date with date of timestamp.

        setting string=True with return join the list before returning.

        '''
        dt = datetime.now()
        if (timestamp):
            dt = datetime.fromtimestamp(timestamp)

        dt_list = [f'{dt.year}', f'{dt.month:02}', f'{dt.day:02}']
        if (string):
            return str_join(dt_list)

        return dt_list
Пример #7
0
def load_configuration(filename, *, filepath='dnx_system/data'):
    '''load json data from file, convert it to a python dict, then return as object.'''
    if (not filename.endswith('.json')):
        filename = str_join([filename, '.json'])

    # loading system default configs
    with open(f'{HOME_DIR}/{filepath}/{filename}', 'r') as system_settings:
        system_settings = json.load(system_settings)

    if os.path.exists(f'{HOME_DIR}/{filepath}/usr/{filename}'):

        # loading user configurations (if exists)
        with open(f'{HOME_DIR}/{filepath}/usr/{filename}',
                  'r') as usr_settings:
            usr_settings = json.load(usr_settings)

        # updating system settings dict with user settings to be used in memory/ by modules only.
        system_settings.update(usr_settings)

    return system_settings
Пример #8
0
 def generate_syslog_message(log):
     return str_join([
         f'local.ip={log.local_ip}; tracked.ip={log.tracked_ip}; category={str_join(log.category)}; ',
         f'direction={log.direction}; action={log.action}'
     ])