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

send-tasks.gmp.interactive_options()   B

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