summaryrefslogtreecommitdiffstats
path: root/cli/utils.py
blob: 2922f782ff9ee7fbf657832ad1199b5f0bd36c7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# Copyright (C) 2020-2024 Soleta Networks <opengnsys@soleta.eu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.

import unicodedata
import json
import ipaddress
import hashlib
import re
import os

def scope_lookup(scope_id, scope_type, d):
    if scope_id == d.get('id') and scope_type == d.get('type'):
        return d
    for scope in d['scope']:
        lookup = scope_lookup(scope_id, scope_type, scope)
        if lookup is not None:
            return lookup
    return None


def ips_in_scope(scope):
    if scope is None:
        return []
    if 'ip' in scope:
        return [scope['ip']]
    ips = []
    for child in scope['scope']:
        ips += ips_in_scope(child)
    return ips

def reorder_json_tree(payload):
    if isinstance(payload, list):
        elements = payload[:]
        for val in elements:
            if isinstance(val, (dict, list)):
                payload.remove(val)
                payload.append(val)
                reorder_json_tree(val)
    elif isinstance(payload, dict):
        keys = list(payload.keys())
        for k in keys:
            val = payload[k]
            if isinstance(val, (dict, list)):
                del payload[k]
                payload[k] = val
                reorder_json_tree(val)

def print_json(data):
    if isinstance(data, (dict, list)):
        payload = data
    else:
        payload = json.loads(data)
    reorder_json_tree(payload)
    print(json.dumps(payload, indent=2, ensure_ascii=False))

def check_address(addr):
    try:
        ip = ipaddress.ip_address(addr)
        return True
    except:
        return False

def check_mac_address(addr):
    if re.match("[a-f0-9]{2}(:[a-f0-9]{2}){5}$", addr.lower()):
        return True
    else:
        print(addr.lower())
        return False

def remove_accents(text):
    normalized_text = unicodedata.normalize('NFD', text)
    return ''.join(c for c in normalized_text if unicodedata.category(c) != 'Mn')

def compute_md5(path, bs=2**20):
    if not os.path.exists(path):
        print(f"Failed to calculate checksum, image file {path} does not exist")
        return None

    m = hashlib.md5()
    try:
        with open(path, 'rb') as f:
            while True:
                buf = f.read(bs)
                if not buf:
                    break
                m.update(buf)
    except Exception as e:
        print(f'Failed to calculate checksum for {path}: {e}')
        return None
    return m.hexdigest()