Completed
Push — master ( 922c4e...42fcf2 )
by Björn
13s queued 11s
created

send-tasks.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-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
import sys
20
from gvmtools.helper import create_xml_tree, error_and_exit, yes_or_no
21
22
23
def check_args(args):
24
    len_args = len(args.script) - 1
25
    if len_args is not 1:
26
        message = """
27
        This script pulls tasks 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 tasks
32
33
        Example:
34
            $ gvm-script --gmp-username name --gmp-password pass \
35
    ssh --hostname <gsm> scripts/send-tasks.gmp.py example_file.xml
36
        """
37
38
        print(message)
39
        sys.exit()
40
41
42
def numerical_option(statement, list_range):
43
    choice = int(input(statement))
44
45
    if choice in range(1, list_range + 1):
46
        return choice
47
    else:
48
        return numerical_option(
49
            "Please enter valid number from {} to {}...".format(1, list_range),
50
            list_range,
51
        )
52
53
54
def interactive_options(gmp, task, keywords):
55
    options_dict = {}
56
    options_dict['config'] = gmp.get_configs()
57
    options_dict['scanner'] = gmp.get_scanners()
58
    options_dict['target'] = gmp.get_targets()
59
60
    for option in options_dict:
61
        object_dict, object_list = {}, []
62
        object_id = task.xpath('{}/@id'.format(option))[0]
63
        object_xml = options_dict[option]
64
65
        for i in object_xml.xpath('{}'.format(option)):
66
            object_dict[i.find('name').text] = i.xpath('@id')[0]
67
            object_list.append(i.find('name').text)
68
69
        if object_id in object_dict.values():
70
            keywords['{}_id'.format(option)] = object_id
71
        elif object_id not in object_dict.values() and len(object_dict) != 0:
72
            response = yes_or_no(
73
                "\nRequired Field: failed to detect {}_id: {}... "
74
                "\nWould you like to select from available options, or exit "
75
                "the script?".format(
76
                    option, task.xpath('{}/@id'.format(option))[0]
77
                )
78
            )
79
80
            if response is True:
81
                counter = 1
82
                print("{} options:".format(option.capitalize()))
83
                for j in object_list:
84
                    print("    {} - {}".format(counter, j))
85
                    counter += 1
86
                answer = numerical_option(
87
                    "\nPlease enter the number of your choice.",
88
                    len(object_list),
89
                )
90
                keywords['{}_id'.format(option)] = object_dict[
91
                    object_list[answer - 1]
92
                ]
93
            else:
94
                print("\nTerminating...")
95
                quit()
96
        else:
97
            error_and_exit(
98
                "Failed to detect {}_id"
99
                "\nThis field is required therefore the script is unable to "
100
                "continue.\n".format(option)
101
            )
102
103
104
def parse_send_xml_tree(gmp, xml_tree):
105
    for task in xml_tree.xpath('task'):
106
        keywords = {'name': task.find('name').text}
107
108
        if task.find('comment').text is not None:
109
            keywords['comment'] = task.find('comment').text
110
111
        interactive_options(gmp, task, keywords)
112
113
        new_task = gmp.create_task(**keywords)
114
115
        mod_keywords = {'task_id': new_task.xpath('//@id')[0]}
116
117
        if task.find('schedule_periods') is not None:
118
            mod_keywords['schedule_periods'] = int(
119
                task.find('schedule_periods').text
120
            )
121
122
        if task.find('observers').text:
123
            mod_keywords['observers'] = task.find('observers').text
124
125
        if task.xpath('schedule/@id')[0]:
126
            mod_keywords['schedule_id'] = task.xpath('schedule/@id')[0]
127
128
        if task.xpath('preferences/preference'):
129
            preferences, scanner_name_list, value_list = {}, [], []
130
131
            for preference in task.xpath('preferences/preference'):
132
                scanner_name_list.append(preference.find('scanner_name').text)
133
                if preference.find('value').text is not None:
134
                    value_list.append(preference.find('value').text)
135
                else:
136
                    value_list.append('')
137
            preferences['scanner_name'] = scanner_name_list
138
            preferences['value'] = value_list
139
            mod_keywords['preferences'] = preferences
140
141
        if task.xpath('file/@name'):
142
            file = dict(
143
                name=task.xpath('file/@name'), action=task.xpath('file/@action')
144
            )
145
146
            mod_keywords['file'] = file
147
148
        if len(mod_keywords) > 1:
149
            gmp.modify_task(**mod_keywords)
150
151
152
def main(gmp, args):
153
    # pylint: disable=undefined-variable
154
    check_args(args)
155
    xml_doc = args.script[1]
156
157
    print('\nSending task(s)...')
158
159
    xml_tree = create_xml_tree(xml_doc)
160
    parse_send_xml_tree(gmp, xml_tree)
161
162
    print('\n  Task(s) sent!\n')
163
164
165
if __name__ == '__gmp__':
166
    main(gmp, args)  # pylint: disable=undefined-variable
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable args does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable gmp does not seem to be defined.
Loading history...
167