Passed
Pull Request — master (#248)
by
unknown
01:20
created

send-targets.gmp.create_xml_tree()   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 10

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 1
dl 12
loc 12
rs 9.9
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018-2019 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
import sys
20
21
from lxml import etree as e
22
23
24
def check_args(args):
25
    len_args = len(args.script) - 1
26
    if len_args is not 1:
27
        message = """
28
        This script pulls target data from an xml document and feeds it to \
29
    a desired GSM
30
        One parameter after the script name is required.
31
32
        1. <xml_doc>  -- .xml file containing targets
33
34
        Example:
35
            $ gvm-script --gmp-username name --gmp-password pass \
36
    ssh --hostname <gsm> scripts/send-targets.gmp.py example_file.xml
37
        """
38
        print(message)
39
        quit()
40
41
42
def error_and_exit(msg):
43
    print("Error: {}\n".format(msg), file=sys.stderr)
44
    sys.exit(1)
45
46
47
def yes_or_no(question):
48
    reply = str(input(question + ' (y/n): ')).lower().strip()
49
    if reply[0] == ('y'):
50
        return True
51
    if reply[0] == ('n'):
52
        return False
53
    else:
54
        return yes_or_no("Please enter 'y' or 'n'")
55
56
57 View Code Duplication
def create_xml_tree(xml_doc):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
58
    try:
59
        xml_tree = e.parse(xml_doc)
60
        xml_tree = e.tostring(xml_tree)
61
        xml_tree = e.XML(xml_tree)
62
    except IOError as err:
63
        error_and_exit("Failed to read xml_file: {} (exit)".format(str(err)))
64
65
    if len(xml_tree) == 0:
66
        error_and_exit("XML file is empty (exit)")
67
68
    return xml_tree
69
70
71
def parse_send_xml_tree(gmp, xml_tree):
72
    credential_options = [
73
        'ssh_credential',
74
        'smb_credential',
75
        'esxi_credential',
76
        'snmp_credential',
77
    ]
78
    counter = 1
79
80
    for target in xml_tree.xpath('target'):
81
        keywords = {}  # {'make_unique': True}
82
83
        keywords['name'] = target.find('name').text
84
85
        keywords['hosts'] = target.find('hosts').text.split(',')
86
87
        exclude_hosts = target.find('exclude_hosts').text
88
        if exclude_hosts is not None:
89
            keywords['exclude_hosts'] = exclude_hosts.split(',')
90
91
        comment = target.find('comment').text
92
        if comment is not None:
93
            keywords['comment'] = comment
94
95
        credentials = gmp.get_credentials()[0].xpath("//credential/@id")
96
97
        for credential in credential_options:
98
            cred_id = target.find(credential).xpath('@id')[0]
99
            if cred_id == '':
100
                continue
101
            if cred_id not in credentials:
102
                response = yes_or_no(
103
                    "\nThe credential '{}' for 'target {}' could not be "
104
                    "located...\nWould you like to continue?".format(
105
                        credential, counter
106
                    )
107
                )
108
109
                if response is False:
110
                    print("Terminating...\n")
111
                    quit()
112
                else:
113
                    continue
114
115
            temp_dict = {}
116
            temp_dict['id'] = cred_id
117
            elem_path = target.find(credential)
118
            if elem_path.find('port').text is not None:
119
                temp_dict['port'] = elem_path.find('port').text
120
121
            keywords[credential] = temp_dict
122
123
        alive_test = target.find('alive_test')
124
125
        if alive_test is not None:
126
            keywords['alive_test'] = alive_test
127
128
        reverse_lookup_only = target.find('reverse_lookup_only').text
129
        if reverse_lookup_only == '1':
130
            keywords['reverse_lookup_only'] = 1
131
132
        reverse_lookup_unify = target.find('reverse_lookup_unify').text
133
        if reverse_lookup_unify == '1':
134
            keywords['reverse_lookup_unify'] = 1
135
136
        port_range = target.find('port_range')
137
        if port_range is not None:
138
            keywords['port_range'] = port_range.text
139
140
        if target.xpath('port_list/@id') is not None:
141
            port_list = {}
142
            port_list = target.xpath('port_list/@id')[0]
143
            keywords['port_list_id'] = port_list
144
145
        print(keywords)
146
147
        gmp.create_target(**keywords)
148
149
        counter += 1
150
151
152
def main(gmp, args):
153
    # pylint: disable=undefined-variable
154
155
    check_args(args)
156
157
    xml_doc = args.script[1]
158
159
    print('\nSending targets...')
160
161
    xml_tree = create_xml_tree(xml_doc)
162
    parse_send_xml_tree(gmp, xml_tree)
163
164
    print('\n  Target(s) created!\n')
165
166
167
if __name__ == '__gmp__':
168
    main(gmp, args)
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...
169