Completed
Push — master ( a56b87...e3de6b )
by
unknown
21s queued 11s
created

gvmtools.helper   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 146
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 23
eloc 71
dl 0
loc 146
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A Table._create_row() 0 2 1
A Table.__init__() 0 4 1
A Table._calculate_dimensions() 0 15 5
A Table.__str__() 0 29 4
A Table._create_column() 0 2 1

3 Functions

Rating   Name   Duplication   Size   Complexity  
A do_not_run_as_root() 0 3 3
B authenticate() 0 36 6
A run_script() 0 14 2
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018 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 getpass
20
import os
21
import sys
22
23
from gvm.errors import GvmError
24
from gvm.xml import pretty_print
25
26
27
__all__ = ['authenticate', 'pretty_print', 'run_script']
28
29
30
class Table:
31
    def __init__(self, heading=None, rows=None, divider=' | '):
32
        self.heading = heading or []
33
        self.rows = rows or []
34
        self.divider = divider
35
36
    def _calculate_dimensions(self):
37
        column_sizes = []
38
39
        for column in self.heading:
40
            column_sizes.append(len(column))
41
42
        for row in self.rows:
43
            for i, column in enumerate(row):
44
                dim = column_sizes[i]
45
                column_size = len(column)
46
47
                if dim < column_size:
48
                    column_sizes[i] = column_size
49
50
        return column_sizes
51
52
    def _create_column(self, column, size):
53
        return '{}{}'.format(column, ' ' * (size - len(column)))
54
55
    def _create_row(self, columns):
56
        return self.divider.join(columns)
57
58
    def __str__(self):
59
        column_sizes = self._calculate_dimensions()
60
61
        row_strings = []
62
63
        heading_columns = []
64
        heading_divider_columns = []
65
66
        for i, column in enumerate(self.heading):
67
            column_size = column_sizes[i]
68
69
            heading_columns.append(self._create_column(column, column_size))
70
            heading_divider_columns.append(
71
                self._create_column('-' * column_size, column_size)
72
            )
73
74
        row_strings.append(self._create_row(heading_columns))
75
        row_strings.append(self._create_row(heading_divider_columns))
76
77
        for row in self.rows:
78
            row_columns = []
79
80
            for i, column in enumerate(row):
81
                column_size = column_sizes[i]
82
                row_columns.append(self._create_column(column, column_size))
83
84
            row_strings.append(self._create_row(row_columns))
85
86
        return "\n".join(row_strings)
87
88
89
def do_not_run_as_root():
90
    if hasattr(os, 'geteuid') and os.geteuid() == 0:
91
        raise RuntimeError('This tool MUST NOT be run as root user.')
92
93
94
def authenticate(gmp, username=None, password=None):
95
    """Authentication helper
96
97
    Tries to get authentication username and password from arguments and if not
98
    present asks the username and/or password from the terminal.
99
100
    Arguments:
101
        gmp: A protocol instance
102
        username (:obj:`str`, optional): Username to authenticate with. If None,
103
            username will be read from terminal.
104
        password (:obj:`str`, optional): Password to authenticate with. If None,
105
            password will be read from the terminal.
106
107
    Returns:
108
        tuple: (username, password) tuple
109
110
    Raises:
111
        GmpError: Raises GmpError if authentication fails.
112
    """
113
    if gmp.is_authenticated():
114
        return
115
116
    # Ask for login credentials if none are given.
117
    if not username:
118
        while len(username) == 0:
119
            username = input('Enter username: ')
120
121
    if not password:
122
        password = getpass.getpass('Enter password for {0}: '.format(username))
123
124
    try:
125
        gmp.authenticate(username, password)
126
        return (username, password)
127
    except GvmError as e:
128
        print('Could not authenticate. Please check your credentials.')
129
        raise e
130
131
132
def run_script(path, global_vars):
133
    """Loads and executes a file as a python script
134
135
    Arguments:
136
        path (str): Path to the script file
137
        vars (dict): Variables passed as globals to the script
138
    """
139
    try:
140
        file = open(path, 'r', newline='').read()
141
    except FileNotFoundError:
142
        print('Script {path} does not exist'.format(path=path), file=sys.stderr)
143
        sys.exit(2)
144
145
    exec(file, global_vars)  # pylint: disable=exec-used
146