Passed
Pull Request — master (#244)
by
unknown
01:25
created

update-task-target.gmp.error_and_exit()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
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
import time
21
22
23
def check_args(args):
24
    len_args = len(args.script) - 1
25
    if len_args != 2:
26
        message = """
27
        This script will update target hosts information for a desired task.
28
        Two parameters after the script name are required.
29
30
        1. <hosts_file>  -- .csv file containing desired target hosts separated by ','
31
        2. <task_uuid>   -- uuid of task to be modified
32
33
        Example for starting up the routine:
34
            $ gvm-script --gmp-username name --gmp-password pass \
35
    ssh --hostname <gsm> scripts/update-task-target.gmp.py hosts_file.csv \
36
    "303fa0a6-aa9b-43c4-bac0-66ae0b2d1698"
37
38
        """
39
        print(message)
40
        quit()
41
42
43
def error_and_exit(msg):
44
    sys.stderr.write("Error: {}\n".format(msg))
45
    sys.exit(1)
46
47
48
def load_host_file(filename):
49
    host_list = list()
50
51
    try:
52
        f = open(filename)
53
        for line in f:
54
            host = line.split(",")[0]
55
            host = host.strip()
56
            if len(host) == 0:
57
                continue
58
            host_list.append(host)
59
60
    except IOError as e:
61
        error_and_exit("Failed to read host_file: {} (exit)".format(str(e)))
62
63
    if len(host_list) == 0:
64
        error_and_exit("Host file is empty (exit)")
65
66
    hosts_string = ', '.join(map(str, host_list))
67
68
    return hosts_string
69
70
71
def copy_send_target(gmp, hosts_file, old_target_id):
72
    hosts_string = load_host_file(hosts_file)
73
    keywords = {'hosts': hosts_string}
74
75
    keywords['comment'] = 'This target was automatically modified: {}'.format(
76
        time.strftime("%Y/%m/%d-%H:%M:%S")
77
    )
78
79
    old_target = gmp.get_target(target_id=old_target_id)[0]
80
81
    objects = ('reverse_lookup_only', 'reverse_lookup_unify', 'name')
82
    for obj in objects:
83
        var = old_target.xpath('{}/text()'.format(obj))[0]
84
        if var is '0':
85
            var = ''
86
        keywords['{}'.format(obj)] = var
87
88
    port_list = {}
89
    port_list = old_target.xpath('port_list/@id')[0]
90
    keywords['port_list_id'] = port_list
91
92
    keywords['name'] += "_copy"  # the name must differ from existing names
93
94
    new_target_id = gmp.create_target(**keywords).xpath('@id')[0]
95
96
    print('\n  New target created!\n')
97
    print('Target_id:   {}'.format(new_target_id))
98
    print('Target_name: {}\n'.format(keywords['name']))
99
100
    return new_target_id
101
102
103
def create_target_hosts(gmp, host_file, task_id, old_target_id):
104
    new_target_id = copy_send_target(gmp, host_file, old_target_id)
105
106
    gmp.modify_task(task_id=task_id, target_id=new_target_id)
107
108
    print('  Task successfully modified!\n')
109
110
111
def check_to_delete(gmp, target_id):
112
    target = gmp.get_target(target_id=target_id)[0]
113
    if '0' in target.xpath("in_use/text()"):
114
        gmp.delete_target(target_id=target_id)
115
116
117
def main(gmp, args):
118
    # pylint: disable=undefined-variable
119
120
    check_args(args)
121
122
    hosts_file = args.script[1]
123
    task_id = args.script[2]
124
125
    task = gmp.get_task(task_id=task_id)[1]
126
    old_target_id = task.xpath('target/@id')[0]
127
128
    create_target_hosts(gmp, hosts_file, task_id, old_target_id)
129
    check_to_delete(gmp, old_target_id)
130
131
132
if __name__ == '__gmp__':
133
    main(gmp, args)
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...
134