Passed
Pull Request — master (#317)
by Jaspar
01:16
created

send-targets.gmp.parse_send_xml_tree()   F

Complexity

Conditions 15

Size

Total Lines 79
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 57
nop 2
dl 0
loc 79
rs 2.9998
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like send-targets.gmp.parse_send_xml_tree() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018-2020 Greenbone Networks GmbH
3
#
4
# SPDX-License-Identifier: GPL-3.0-or-later
5
#
6
# This program is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 3 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
from gvm.protocols.gmpv9.types import get_alive_test_from_string
20
from gvmtools.helper import create_xml_tree, yes_or_no
21
22
23
def check_args(args):
24
    len_args = len(args.script) - 1
25
    if len_args != 1:
26
        message = """
27
        This script pulls target data from an xml document and feeds it to \
28
    a desired GSM
29
        One parameter after the script name is required.
30
31
        1. <xml_doc>  -- .xml file containing targets
32
33
        Example:
34
            $ gvm-script --gmp-username name --gmp-password pass \
35
    ssh --hostname <gsm> scripts/send-targets.gmp.py example_file.xml
36
        """
37
        print(message)
38
        quit()
39
40
41
def parse_send_xml_tree(gmp, xml_tree):
42
    credential_options = [
43
        'ssh_credential',
44
        'smb_credential',
45
        'esxi_credential',
46
        'snmp_credential',
47
    ]
48
    counter = 1
49
50
    for target in xml_tree.xpath('target'):
51
        keywords = {}  # {'make_unique': True}
52
53
        keywords['name'] = target.find('name').text
54
55
        keywords['hosts'] = target.find('hosts').text.split(',')
56
57
        exclude_hosts = target.find('exclude_hosts').text
58
        if exclude_hosts is not None:
59
            keywords['exclude_hosts'] = exclude_hosts.split(',')
60
61
        comment = target.find('comment').text
62
        if comment is not None:
63
            keywords['comment'] = comment
64
65
        credentials = gmp.get_credentials()[0].xpath("//credential/@id")
66
67
        for credential in credential_options:
68
            cred_id = target.find(credential).xpath('@id')[0]
69
            if cred_id == '':
70
                continue
71
            if cred_id not in credentials:
72
                response = yes_or_no(
73
                    "\nThe credential '{}' for 'target {}' could not be "
74
                    "located...\nWould you like to continue?".format(
75
                        credential, counter
76
                    )
77
                )
78
79
                if response is False:
80
                    print("Terminating...\n")
81
                    quit()
82
                else:
83
                    continue
84
85
            key = '{}_id'.format(credential)
86
            keywords[key] = cred_id
87
            elem_path = target.find(credential)
88
            port = elem_path.find('port')
89
            if port is not None and port.text is not None:
90
                port_key = '{}_port'.format(credential)
91
                keywords[port_key] = elem_path.find('port').text
92
93
        alive_test = get_alive_test_from_string(target.find('alive_tests').text)
94
95
        if alive_test is not None:
96
            keywords['alive_test'] = alive_test
97
98
        reverse_lookup_only = target.find('reverse_lookup_only').text
99
        if reverse_lookup_only == '1':
100
            keywords['reverse_lookup_only'] = 1
101
102
        reverse_lookup_unify = target.find('reverse_lookup_unify').text
103
        if reverse_lookup_unify == '1':
104
            keywords['reverse_lookup_unify'] = 1
105
106
        port_range = target.find('port_range')
107
        if port_range is not None:
108
            keywords['port_range'] = port_range.text
109
110
        if target.xpath('port_list/@id') is not None:
111
            port_list = {}
112
            port_list = target.xpath('port_list/@id')[0]
113
            keywords['port_list_id'] = port_list
114
115
        print(keywords)
116
117
        gmp.create_target(**keywords)
118
119
        counter += 1
120
121
122
def main(gmp, args):
123
    # pylint: disable=undefined-variable
124
125
    check_args(args)
126
127
    xml_doc = args.script[1]
128
129
    print('\nSending targets...')
130
131
    xml_tree = create_xml_tree(xml_doc)
132
    parse_send_xml_tree(gmp, xml_tree)
133
134
    print('\n  Target(s) created!\n')
135
136
137
if __name__ == '__gmp__':
138
    main(gmp, args)  # pylint: disable=undefined-variable
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable gmp does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable args does not seem to be defined.
Loading history...
139