send-tasks.gmp.interactive_options()   B
last analyzed

Complexity

Conditions 8

Size

Total Lines 47
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 35
nop 3
dl 0
loc 47
rs 7.1733
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018-2021 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 argparse import ArgumentParser, RawTextHelpFormatter
21
22
from gvmtools.helper import create_xml_tree, error_and_exit, yes_or_no
23
24
HELP_TEXT = """
25
        This script pulls tasks data from an xml document and feeds it to \
26
            a desired GSM
27
        Usage examples: 
28
            $ gvm-script --gmp-username name --gmp-password pass ssh --hostname
29
            ... send-task.gmp.py +h
30
            ... send-task.gmp.py ++x xml_file
31
    """
32
33
34
def numerical_option(statement, list_range):
35
    choice = int(input(statement))
36
37
    if choice in range(1, list_range + 1):
38
        return choice
39
    else:
40
        return numerical_option(
41
            "Please enter valid number from {} to {}...".format(1, list_range),
42
            list_range,
43
        )
44
45
46
def interactive_options(gmp, task, keywords):
47
    options_dict = {}
48
    options_dict['config'] = gmp.get_configs()
49
    options_dict['scanner'] = gmp.get_scanners()
50
    options_dict['target'] = gmp.get_targets()
51
52
    for option in options_dict:
53
        object_dict, object_list = {}, []
54
        object_id = task.find(option).get('id')
55
        object_xml = options_dict[option]
56
57
        for i in object_xml.findall(option):
58
            object_dict[i.find('name').text] = i.xpath('@id')[0]
59
            object_list.append(i.find('name').text)
60
61
        if object_id in object_dict.values():
62
            keywords['{}_id'.format(option)] = object_id
63
        elif object_id not in object_dict.values() and len(object_dict) != 0:
64
            response = yes_or_no(
65
                "\nRequired Field: failed to detect {}_id: {}... "
66
                "\nWould you like to select from available options, or exit "
67
                "the script?".format(
68
                    option, task.xpath('{}/@id'.format(option))[0]
69
                )
70
            )
71
72
            if response is True:
73
                counter = 1
74
                print("{} options:".format(option.capitalize()))
75
                for j in object_list:
76
                    print("    {} - {}".format(counter, j))
77
                    counter += 1
78
                answer = numerical_option(
79
                    "\nPlease enter the number of your choice.",
80
                    len(object_list),
81
                )
82
                keywords['{}_id'.format(option)] = object_dict[
83
                    object_list[answer - 1]
84
                ]
85
            else:
86
                print("\nTerminating...")
87
                sys.exit()
88
        else:
89
            error_and_exit(
90
                "Failed to detect {}_id"
91
                "\nThis field is required therefore the script is unable to "
92
                "continue.\n".format(option)
93
            )
94
95
96
def parse_send_xml_tree(gmp, xml_tree):
97
    task_xml_elements = xml_tree.xpath('task')
98
    print(task_xml_elements)
99
    if not task_xml_elements:
100
        error_and_exit("No tasks found.")
101
    tasks = []
102
    for task in task_xml_elements:
103
        keywords = {'name': task.find('name').text}
104
105
        if task.find('comment').text is not None:
106
            keywords['comment'] = task.find('comment').text
107
108
        interactive_options(gmp, task, keywords)
109
110
        if task.find('schedule_periods') is not None:
111
            keywords['schedule_periods'] = int(
112
                task.find('schedule_periods').text
113
            )
114
115
        if task.find('observers').text:
116
            keywords['observers'] = task.find('observers').text
117
118
        if task.xpath('schedule/@id')[0]:
119
            keywords['schedule_id'] = task.xpath('schedule/@id')[0]
120
121
        if task.xpath('preferences/preference'):
122
            preferences, scanner_name_list, value_list = {}, [], []
123
124
            for preference in task.xpath('preferences/preference'):
125
                scanner_name_list.append(preference.find('scanner_name').text)
126
                if preference.find('value').text is not None:
127
                    value_list.append(preference.find('value').text)
128
                else:
129
                    value_list.append('')
130
            preferences['scanner_name'] = scanner_name_list
131
            preferences['value'] = value_list
132
            keywords['preferences'] = preferences
133
134
        new_task = gmp.create_task(**keywords)
135
136
        tasks.append(new_task.xpath('//@id')[0])
137
    return tasks
138
139
140
def main(gmp, args):
141
    # pylint: disable=undefined-variable, unused-argument
142
143
    parser = ArgumentParser(
144
        prefix_chars="+",
145
        add_help=False,
146
        formatter_class=RawTextHelpFormatter,
147
        description=HELP_TEXT,
148
    )
149
150
    parser.add_argument(
151
        "+h",
152
        "++help",
153
        action="help",
154
        help="Show this help message and exit.",
155
    )
156
157
    parser.add_argument(
158
        "+x",
159
        "++xml-file",
160
        dest='xml',
161
        type=str,
162
        required=True,
163
        help='xml file containing tasks',
164
    )
165
166
    script_args, _ = parser.parse_known_args()
167
168
    # check_args(args)
169
170
    print('\nSending task(s)...')
171
172
    xml_tree = create_xml_tree(script_args.xml)
173
    tasks = parse_send_xml_tree(gmp, xml_tree)
174
    for task in tasks:
175
        print(task)
176
    print('\nTask(s) sent!\n')
177
178
179
if __name__ == '__gmp__':
180
    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...
181