Passed
Pull Request — master (#152)
by
unknown
01:10
created

gvmtools.pyshell.main()   C

Complexity

Conditions 11

Size

Total Lines 79
Code Lines 56

Duplication

Lines 13
Ratio 16.46 %

Importance

Changes 0
Metric Value
eloc 56
dl 13
loc 79
rs 5.22
c 0
b 0
f 0
cc 11
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like gvmtools.pyshell.main() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 code
20
import logging
21
import os
22
import sys
23
24
from argparse import Namespace
25
26
from gvm import get_version as get_gvm_version
27
from gvm.protocols.latest import Gmp, Osp
28
from gvm.transforms import EtreeCheckCommandTransform
29
30
from gvmtools import get_version
31
from gvmtools.helper import authenticate, run_script
32
from gvmtools.parser import create_parser, create_connection, PROTOCOL_OSP
33
34
__version__ = get_version()
35
__api_version__ = get_gvm_version()
36
37
logger = logging.getLogger(__name__)
38
39
HELP_TEXT = """
40
    Command line tool to access services via GMP (Greenbone Management
41
    Protocol) and OSP (Open Scanner Protocol)
42
43
    gvm-pyshell provides an interactive shell for GMP and OSP services
44
    and can be used to execute custom OSP/GMP scripts.
45
46
    Example:
47
        >>> tasks = gmp.get_tasks()
48
        >>> task_names = tasks.xpath('task/name/text()')
49
        >>> print(task_names)
50
        ['Scan Task']
51
52
    The interactive shell can be exited with:
53
        Ctrl + D on Linux  or
54
        Ctrl + Z on Windows
55
56
    The protocol specifications for GMP and OSP are available at:
57
      https://docs.greenbone.net/index.html#api_documentation"""
58
59
60
class Help(object):
61
    """Help class to overwrite the help function from python itself.
62
    """
63
64
    def __call__(self):
65
        return print(HELP_TEXT)
66
67
    def __repr__(self):
68
        # do pwd command
69
        return HELP_TEXT
70
71
72
def main():
73
    parser = create_parser(
74
        description=HELP_TEXT, logfilename='gvm-pyshell.log')
75
76
    parser.add_protocol_argument()
77
78
    parser.add_argument(
79
        '-i', '--interactive', action='store_true', default=False,
80
        help='Start an interactive Python shell')
81
82
    parser.add_argument(
83
        'scriptname', nargs='?', metavar="SCRIPT",
84
        help='Path to script to be preloaded (example: myscript.gmp)')
85
    parser.add_argument(
86
        'scriptargs', nargs='*', metavar="ARG",
87
        help='Arguments for preloaded script')
88
89
    args = parser.parse_args()
90
91
    if 'socket' in args.connection_type and args.sockpath:
92
        print('The --sockpath parameter has been deprecated. Please use '
93
              '--socketpath instead', file=sys.stderr)
94
95
    connection = create_connection(**vars(args))
96
97
    transform = EtreeCheckCommandTransform()
98
99
    global_vars = {
100
        'help': Help(),
101
        '__version__': __version__,
102
        '__api_version__': __api_version__,
103
    }
104
105
    username = None
106
    password = None
107
108 View Code Duplication
    if args.protocol == PROTOCOL_OSP:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
109
        protocol = Osp(connection, transform=transform)
110
        global_vars['osp'] = protocol
111
        global_vars['__name__'] = '__osp__'
112
    else:
113
        protocol = Gmp(connection, transform=transform)
114
        global_vars['gmp'] = protocol
115
        global_vars['__name__'] = '__gmp__'
116
117
        if args.gmp_username:
118
            (username, password) = authenticate(
119
                protocol, username=args.gmp_username,
120
                password=args.gmp_password)
121
122
    shell_args = Namespace(
123
        username=username, password=password)
124
125
    global_vars['args'] = shell_args
126
127
    with_script = args.scriptname and len(args.scriptname) > 0
128
129
    if with_script:
130
        argv = [os.path.abspath(args.scriptname), *args.scriptargs]
131
        shell_args.argv = argv
132
        # for backwards compatibility we add script here
133
        shell_args.script = argv
134
135
    no_script_no_interactive = not args.interactive and not with_script
136
    script_and_interactive = args.interactive and with_script
137
    only_interactive = not with_script and args.interactive
138
    only_script = not args.interactive and with_script
139
140
    if only_interactive or no_script_no_interactive:
141
        enter_interactive_mode(global_vars)
142
143
    if script_and_interactive or only_script:
144
        script_name = args.scriptname
145
        run_script(script_name, global_vars)
146
147
        if not only_script:
148
            enter_interactive_mode(global_vars)
149
150
    protocol.disconnect()
151
152
153
def enter_interactive_mode(global_vars):
154
    code.interact(
155
        banner='GVM Interactive Console. Type "help" to get information \
156
about functionality.',
157
        local=dict(global_vars))
158
159
160
if __name__ == '__main__':
161
    main()
162