Passed
Pull Request — master (#139)
by
unknown
02:35
created

gvm.protocols.gmpv7.get_alive_test_from_string()   C

Complexity

Conditions 11

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 25
nop 1
dl 0
loc 38
rs 5.4
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like gvm.protocols.gmpv7.get_alive_test_from_string() 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
# pylint: disable=too-many-lines,redefined-builtin
20
"""
21
Module for communication with gvmd in `Greenbone Management Protocol version 7`_
22
23
.. _Greenbone Management Protocol version 7:
24
    https://docs.greenbone.net/API/GMP/gmp-7.0.html
25
"""
26
import base64
27
import collections
28
import logging
29
import numbers
30
31
from enum import Enum
32
from typing import Any, List, Optional, Callable
33
34
from lxml import etree
35
36
from gvm.connections import GvmConnection
37
from gvm.errors import InvalidArgument, RequiredArgument
38
from gvm.utils import get_version_string, deprecation
39
from gvm.xml import XmlCommand, create_parser
40
41
from .base import GvmProtocol
42
43
logger = logging.getLogger(__name__)
44
45
Severity = numbers.Real
46
47
PROTOCOL_VERSION = (7,)
48
49
50
class AlertEvent(Enum):
51
    """ Enum for alert event types """
52
53
    TASK_RUN_STATUS_CHANGED = 'Task run status changed'
54
    UPDATED_SECINFO_ARRIVED = 'Updated SecInfo arrived'
55
    NEW_SECINFO_ARRIVED = 'New SecInfo arrived'
56
57
58
def get_alert_event_from_string(
59
    alert_event: Optional[str]
60
) -> Optional[AlertEvent]:
61
    """ Convert an alert event string into a AlertEvent instance """
62
    if not alert_event:
63
        return None
64
65
    alert_event = alert_event.lower()
66
67
    if alert_event == 'task run status changed':
68
        return AlertEvent.TASK_RUN_STATUS_CHANGED
69
70
    if alert_event == 'updated secinfo arrived':
71
        return AlertEvent.UPDATED_SECINFO_ARRIVED
72
73
    if alert_event == 'new secinfo arrived':
74
        return AlertEvent.NEW_SECINFO_ARRIVED
75
76
    raise InvalidArgument(
77
        argument='alert_event', function=get_alert_event_from_string.__name__
78
    )
79
80
81
class AlertCondition(Enum):
82
    """ Enum for alert condition types """
83
84
    ALWAYS = 'Always'
85
    SEVERITY_AT_LEAST = 'Severity at least'
86
    FILTER_COUNT_CHANGED = 'Filter count changed'
87
    FILTER_COUNT_AT_LEAST = 'Filter count at least'
88
89
90
def get_alert_condition_from_string(
91
    alert_condition: Optional[str]
92
) -> Optional[AlertCondition]:
93
    """ Convert an alert condition string into a AlertCondition instance """
94
    if not alert_condition:
95
        return None
96
97
    alert_condition = alert_condition.lower()
98
99
    if alert_condition == 'always':
100
        return AlertCondition.ALWAYS
101
102
    if alert_condition == 'filter count changed':
103
        return AlertCondition.FILTER_COUNT_CHANGED
104
105
    if alert_condition == 'filter count at least':
106
        return AlertCondition.FILTER_COUNT_AT_LEAST
107
108
    raise InvalidArgument(
109
        argument='alert_condition',
110
        function=get_alert_condition_from_string.__name__,
111
    )
112
113
114
class AlertMethod(Enum):
115
    """ Enum for alert method type"""
116
117
    SCP = "SCP"
118
    SEND = "Send"
119
    SMB = "SMB"
120
    SNMP = "SNMP"
121
    SYSLOG = "Syslog"
122
    EMAIL = "Email"
123
    START_TASK = "Start Task"
124
    HTTP_GET = "HTTP Get"
125
    SOURCEFIRE_CONNECTOR = "Sourcefire Connector"
126
    VERINICE_CONNECTOR = "verinice Connector"
127
128
129
def get_alert_method_from_string(
130
    alert_method: Optional[str]
131
) -> Optional[AlertMethod]:
132
    """ Convert an alert method string into a AlertCondition instance """
133
    if not alert_method:
134
        return None
135
136
    alert_method = alert_method.upper()
137
138
    if alert_method == 'START TASK':
139
        return AlertMethod.START_TASK
140
141
    if alert_method == 'HTTP GET':
142
        return AlertMethod.HTTP_GET
143
144
    if alert_method == 'SOURCEFIRE CONNECTOR':
145
        return AlertMethod.SOURCEFIRE_CONNECTOR
146
147
    if alert_method == 'VERINICE CONNECTOR':
148
        return AlertMethod.VERINICE_CONNECTOR
149
150
    try:
151
        return AlertMethod[alert_method]
152
    except KeyError:
153
        raise InvalidArgument(
154
            argument='alert_method',
155
            function=get_alert_method_from_string.__name__,
156
        )
157
158
159
class AliveTest(Enum):
160
    """ Enum for choosing an alive test """
161
162
    ICMP_PING = 'ICMP Ping'
163
    TCP_ACK_SERVICE_PING = 'TCP-ACK Service Ping'
164
    TCP_SYN_SERVICE_PING = 'TCP-SYN Service Ping'
165
    APR_PING = 'ARP Ping'
166
    ICMP_AND_TCP_ACK_SERVICE_PING = 'ICMP & TCP-ACK Service Ping'
167
    ICMP_AND_ARP_PING = 'ICMP & ARP Ping'
168
    TCP_ACK_SERVICE_AND_ARP_PING = 'TCP-ACK Service & ARP Ping'
169
    ICMP_TCP_ACK_SERVICE_AND_ARP_PING = (  # pylint: disable=invalid-name
170
        'ICMP, TCP-ACK Service & ARP Ping'
171
    )
172
    CONSIDER_ALIVE = 'Consider Alive'
173
174
175
def get_alive_test_from_string(
0 ignored issues
show
best-practice introduced by
Too many return statements (10/6)
Loading history...
176
    alive_test: Optional[str]
177
) -> Optional[AliveTest]:
178
    """ Convert an alive test string into a AliveTest instance """
179
    if not alive_test:
180
        return None
181
182
    alive_test = alive_test.lower()
183
184
    if alive_test == 'icmp ping':
185
        return AliveTest.ICMP_PING
186
187
    if alive_test == 'tcp-ack service ping':
188
        return AliveTest.TCP_ACK_SERVICE_PING
189
190
    if alive_test == 'tcp-syn service ping':
191
        return AliveTest.TCP_SYN_SERVICE_PING
192
193
    if alive_test == 'arp ping':
194
        return AliveTest.APR_PING
195
196
    if alive_test == 'icmp & tcp-ack service ping':
197
        return AliveTest.ICMP_AND_TCP_ACK_SERVICE_PING
198
199
    if alive_test == 'icmp & arp ping':
200
        return AliveTest.ICMP_AND_ARP_PING
201
202
    if alive_test == 'tcp-ack service & arp ping':
203
        return AliveTest.TCP_ACK_SERVICE_AND_ARP_PING
204
205
    if alive_test == 'icmp, tcp-ack service & arp ping':
206
        return AliveTest.ICMP_TCP_ACK_SERVICE_AND_ARP_PING
207
208
    if alive_test == 'consider alive':
209
        return AliveTest.CONSIDER_ALIVE
210
211
    raise InvalidArgument(
212
        argument='alive_test', function=get_alive_test_from_string.__name__
213
    )
214
215
216
class AssetType(Enum):
217
    """" Enum for asset types """
218
219
    OPERATING_SYSTEM = 'os'
220
    HOST = 'host'
221
222
223
def get_asset_type_from_string(
224
    asset_type: Optional[str]
225
) -> Optional[AssetType]:
226
    if not asset_type:
227
        return None
228
229
    if asset_type == 'os':
230
        return AssetType.OPERATING_SYSTEM
231
232
    try:
233
        return AssetType[asset_type.upper()]
234
    except KeyError:
235
        raise InvalidArgument(
236
            argument='asset_type', function=get_asset_type_from_string.__name__
237
        )
238
239
240
class CredentialFormat(Enum):
241
    """ Enum for credential format """
242
243
    KEY = 'key'
244
    RPM = 'rpm'
245
    DEB = 'deb'
246
    EXE = 'exe'
247
    PEM = 'pem'
248
249
250
def get_credential_format_from_string(
251
    credential_format: Optional[str]
252
) -> Optional[CredentialFormat]:
253
    if not credential_format:
254
        return None
255
256
    try:
257
        return CredentialFormat[credential_format.upper()]
258
    except KeyError:
259
        raise InvalidArgument(
260
            argument='credential_format',
261
            function=get_credential_format_from_string.__name__,
262
        )
263
264
265
class CredentialType(Enum):
266
    """ Enum for credential types """
267
268
    CLIENT_CERTIFICATE = 'cc'
269
    SNMP = 'snmp'
270
    USERNAME_PASSWORD = 'up'
271
    USERNAME_SSH_KEY = 'usk'
272
273
274 View Code Duplication
def get_credential_type_from_string(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
275
    credential_type: Optional[str]
276
) -> Optional[CredentialType]:
277
    """ Convert a credential type string into a CredentialType instance
278
    """
279
    if not credential_type:
280
        return None
281
282
    try:
283
        return CredentialType[credential_type.upper()]
284
    except KeyError:
285
        raise InvalidArgument(
286
            argument='credential_type',
287
            function=get_credential_type_from_string.__name__,
288
        )
289
290
291 View Code Duplication
class EntityType(Enum):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
292
    """ Enum for entity types """
293
294
    AGENT = "note"
295
    ALERT = "alert"
296
    ASSET = "asset"
297
    CERT_BUND_ADV = "cert_bund_adv"
298
    CPE = "cpe"
299
    CREDENTIAL = "credential"
300
    CVE = "cve"
301
    DFN_CERT_ADV = "dfn_cert_adv"
302
    FILTER = "filter"
303
    GROUP = "group"
304
    HOST = "host"
305
    INFO = "info"
306
    NOTE = "note"
307
    NVT = "nvt"
308
    OPERATING_SYSTEM = "os"
309
    OVALDEF = "ovaldef"
310
    OVERRIDE = "override"
311
    PERMISSION = "permission"
312
    PORT_LIST = "port_list"
313
    REPORT = "report"
314
    REPORT_FORMAT = "report_format"
315
    RESULT = "result"
316
    ROLE = "role"
317
    SCAN_CONFIG = "config"
318
    SCANNER = "scanner"
319
    SCHEDULE = "schedule"
320
    TAG = "tag"
321
    TARGET = "target"
322
    TASK = "task"
323
    USER = "user"
324
325
326 View Code Duplication
def get_entity_type_from_string(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
327
    entity_type: Optional[str]
328
) -> Optional[EntityType]:
329
    """ Convert a entity type string to an actual EntityType instance
330
331
    Arguments:
332
        entity_type: Resource type string to convert to a EntityType
333
    """
334
    if not entity_type:
335
        return None
336
337
    if entity_type == 'config':
338
        return EntityType.SCAN_CONFIG
339
    if entity_type == 'os':
340
        return EntityType.OPERATING_SYSTEM
341
342
    try:
343
        return EntityType[entity_type.upper()]
344
    except KeyError:
345
        raise InvalidArgument(
346
            argument='entity_type',
347
            function=get_entity_type_from_string.__name__,
348
        )
349
350
351
class FeedType(Enum):
352
    """ Enum for feed types """
353
354
    NVT = "NVT"
355
    CERT = "CERT"
356
    SCAP = "SCAP"
357
358
359
def get_feed_type_from_string(feed_type: Optional[str]) -> Optional[FeedType]:
360
    """ Convert a feed type string into a FeedType instance
361
    """
362
    if not feed_type:
363
        return None
364
365
    try:
366
        return FeedType[feed_type.upper()]
367
    except KeyError:
368
        raise InvalidArgument(
369
            argument='feed_type', function=get_feed_type_from_string.__name__
370
        )
371
372
373 View Code Duplication
class FilterType(Enum):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
374
    """ Enum for filter types """
375
376
    AGENT = "agent"
377
    ALERT = "alert"
378
    ASSET = "asset"
379
    SCAN_CONFIG = "config"
380
    CREDENTIAL = "credential"
381
    FILTER = "filter"
382
    GROUP = "group"
383
    HOST = "host"
384
    NOTE = "note"
385
    OPERATING_SYSTEM = "os"
386
    OVERRIDE = "override"
387
    PERMISSION = "permission"
388
    PORT_LIST = "port_list"
389
    REPORT = "report"
390
    REPORT_FORMAT = "report_format"
391
    RESULT = "result"
392
    ROLE = "role"
393
    SCHEDULE = "schedule"
394
    ALL_SECINFO = "secinfo"
395
    TAG = "tag"
396
    TARGET = "target"
397
    TASK = "task"
398
    USER = "user"
399
400
401 View Code Duplication
def get_filter_type_from_string(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
402
    filter_type: Optional[str]
403
) -> Optional[FilterType]:
404
    """ Convert a filter type string to an actual FilterType instance
405
406
    Arguments:
407
        filter_type: Filter type string to convert to a FilterType
408
    """
409
    if not filter_type:
410
        return None
411
412
    if filter_type == 'os':
413
        return FilterType.OPERATING_SYSTEM
414
415
    if filter_type == 'config':
416
        return FilterType.SCAN_CONFIG
417
418
    if filter_type == 'secinfo':
419
        return FilterType.ALL_SECINFO
420
421
    try:
422
        return FilterType[filter_type.upper()]
423
    except KeyError:
424
        raise InvalidArgument(
425
            argument='filter_type',
426
            function=get_filter_type_from_string.__name__,
427
        )
428
429
430
class HostsOrdering(Enum):
431
    """ Enum for host ordering during scans """
432
433
    SEQUENTIAL = "sequential"
434
    RANDOM = "random"
435
    REVERSE = "reverse"
436
437
438
def get_hosts_ordering_from_string(
439
    hosts_ordering: Optional[str]
440
) -> Optional[HostsOrdering]:
441
    """ Convert a hosts ordering string to an actual HostsOrdering instance
442
443
    Arguments:
444
        hosts_ordering: Host ordering string to convert to a HostsOrdering
445
    """
446
    if not hosts_ordering:
447
        return None
448
    try:
449
        return HostsOrdering[hosts_ordering.upper()]
450
    except KeyError:
451
        raise InvalidArgument(
452
            argument='hosts_ordering',
453
            function=get_hosts_ordering_from_string.__name__,
454
        )
455
456
457
class InfoType(Enum):
458
    """ Enum for info types """
459
460
    CERT_BUND_ADV = "CERT_BUND_ADV"
461
    CPE = "CPE"
462
    CVE = "CVE"
463
    DFN_CERT_ADV = "DFN_CERT_ADV"
464
    OVALDEF = "OVALDEF"
465
    NVT = "NVT"
466
    ALLINFO = "ALLINFO"
467
468
469
def get_info_type_from_string(info_type: Optional[str]) -> Optional[InfoType]:
470
    """ Convert a info type string to an actual InfoType instance
471
472
    Arguments:
473
        info_type: Info type string to convert to a InfoType
474
    """
475
    if not info_type:
476
        return None
477
    try:
478
        return InfoType[info_type.upper()]
479
    except KeyError:
480
        raise InvalidArgument(
481
            argument='info_type', function=get_info_type_from_string.__name__
482
        )
483
484
485
class PermissionSubjectType(Enum):
486
    """ Enum for permission subject type """
487
488
    USER = 'user'
489
    GROUP = 'group'
490
    ROLE = 'role'
491
492
493
def get_permission_subject_type_from_string(
494
    subject_type: Optional[str]
495
) -> Optional[PermissionSubjectType]:
496
    """ Convert a permission subject type string to an actual
497
    PermissionSubjectType instance
498
499
    Arguments:
500
        subject_type: Permission subject type string to convert to a
501
            PermissionSubjectType
502
    """
503
    if not subject_type:
504
        return None
505
506
    try:
507
        return PermissionSubjectType[subject_type.upper()]
508
    except KeyError:
509
        raise InvalidArgument(
510
            argument='subject_type',
511
            function=get_permission_subject_type_from_string.__name__,
512
        )
513
514
515
class PortRangeType(Enum):
516
    """ Enum for port range type """
517
518
    TCP = 'TCP'
519
    UDP = 'UDP'
520
521
522
def get_port_range_type_from_string(
523
    port_range_type: Optional[str]
524
) -> Optional[PortRangeType]:
525
    """ Convert a port range type string to an actual PortRangeType instance
526
527
    Arguments:
528
        port_range_type: Port range type string to convert to a PortRangeType
529
    """
530
    if not port_range_type:
531
        return None
532
533
    try:
534
        return PortRangeType[port_range_type.upper()]
535
    except KeyError:
536
        raise InvalidArgument(
537
            argument='port_range_type',
538
            function=get_port_range_type_from_string.__name__,
539
        )
540
541
542
class ScannerType(Enum):
543
    """ Enum for scanner type """
544
545
    OSP_SCANNER_TYPE = "1"
546
    OPENVAS_SCANNER_TYPE = "2"
547
    CVE_SCANNER_TYPE = "3"
548
    GMP_SCANNER_TYPE = "4"  # formerly slave scanner
549
550
551
def get_scanner_type_from_string(
552
    scanner_type: Optional[str]
553
) -> Optional[ScannerType]:
554
    """ Convert a scanner type string to an actual ScannerType instance
555
556
    Arguments:
557
        scanner_type: Scanner type string to convert to a ScannerType
558
    """
559
    if not scanner_type:
560
        return None
561
562
    scanner_type = scanner_type.lower()
563
564
    if (
565
        scanner_type == ScannerType.OSP_SCANNER_TYPE.value
0 ignored issues
show
Unused Code introduced by
Consider merging these comparisons with "in" to "scanner_type in (ScannerType.OSP_SCANNER_TYPE.value, 'osp')"
Loading history...
566
        or scanner_type == 'osp'
567
    ):
568
        return ScannerType.OSP_SCANNER_TYPE
569
570
    if (
571
        scanner_type == ScannerType.OPENVAS_SCANNER_TYPE.value
0 ignored issues
show
Unused Code introduced by
Consider merging these comparisons with "in" to "scanner_type in (ScannerType.OPENVAS_SCANNER_TYPE.value, 'openvas')"
Loading history...
572
        or scanner_type == 'openvas'
573
    ):
574
        return ScannerType.OPENVAS_SCANNER_TYPE
575
576
    if (
577
        scanner_type == ScannerType.CVE_SCANNER_TYPE.value
0 ignored issues
show
Unused Code introduced by
Consider merging these comparisons with "in" to "scanner_type in (ScannerType.CVE_SCANNER_TYPE.value, 'cve')"
Loading history...
578
        or scanner_type == 'cve'
579
    ):
580
        return ScannerType.CVE_SCANNER_TYPE
581
582
    if (
583
        scanner_type == ScannerType.GMP_SCANNER_TYPE.value
0 ignored issues
show
Unused Code introduced by
Consider merging these comparisons with "in" to "scanner_type in (ScannerType.GMP_SCANNER_TYPE.value, 'gmp')"
Loading history...
584
        or scanner_type == 'gmp'
585
    ):
586
        return ScannerType.GMP_SCANNER_TYPE
587
588
    raise InvalidArgument(
589
        argument='scanner_type', function=get_scanner_type_from_string.__name__
590
    )
591
592
593
class SnmpAuthAlgorithm(Enum):
594
    """ Enum for SNMP auth algorithm """
595
596
    SHA1 = 'sha1'
597
    MD5 = 'md5'
598
599
600
def get_snmp_auth_algorithm_from_string(
601
    algorithm: Optional[str]
602
) -> Optional[SnmpAuthAlgorithm]:
603
    """ Convert a SNMP auth algorithm string into a SnmpAuthAlgorithm instance
604
    """
605
    if not algorithm:
606
        return None
607
608
    try:
609
        return SnmpAuthAlgorithm[algorithm.upper()]
610
    except KeyError:
611
        raise InvalidArgument(
612
            argument='algorithm',
613
            function=get_snmp_auth_algorithm_from_string.__name__,
614
        )
615
616
617
class SnmpPrivacyAlgorithm(Enum):
618
    """ Enum for SNMP privacy algorithm """
619
620
    AES = 'aes'
621
    DES = 'des'
622
623
624
def get_snmp_privacy_algorithm_from_string(
625
    algorithm: Optional[str]
626
) -> Optional[SnmpPrivacyAlgorithm]:
627
    """ Convert a SNMP privacy algorithm string into a SnmpPrivacyAlgorithm
628
        instance
629
    """
630
    if not algorithm:
631
        return None
632
633
    try:
634
        return SnmpPrivacyAlgorithm[algorithm.upper()]
635
    except KeyError:
636
        raise InvalidArgument(
637
            argument='algorithm',
638
            function=get_snmp_privacy_algorithm_from_string.__name__,
639
        )
640
641
642
class SeverityLevel(Enum):
643
    """ Enum for severity levels """
644
645
    HIGH = "High"
646
    MEDIUM = "Medium"
647
    LOW = "Low"
648
    LOG = "Log"
649
    ALARM = "Alarm"
650
    DEBUG = "Debug"
651
652
653
def get_severity_level_from_string(
654
    severity_level: Optional[str]
655
) -> Optional[SeverityLevel]:
656
    """ Convert a severity level string into a SeverityLevel instance """
657
    if not severity_level:
658
        return None
659
660
    try:
661
        return SeverityLevel[severity_level.upper()]
662
    except KeyError:
663
        raise InvalidArgument(
664
            argument='severity_level',
665
            function=get_severity_level_from_string.__name__,
666
        )
667
668
669
class TimeUnit(Enum):
670
    """ Enum for time units """
671
672
    SECOND = "second"
673
    MINUTE = "minute"
674
    HOUR = "hour"
675
    DAY = "day"
676
    WEEK = "week"
677
    MONTH = "month"
678
    YEAR = "year"
679
    DECADE = "decade"
680
681
682
def get_time_unit_from_string(
683
    time_unit: Optional[str]
684
) -> Optional[SeverityLevel]:
685
    """ Convert a time unit string into a TimeUnit instance """
686
    if not time_unit:
687
        return None
688
689
    try:
690
        return TimeUnit[time_unit.upper()]
691
    except KeyError:
692
        raise InvalidArgument(
693
            argument='severity_level',
694
            function=get_severity_level_from_string.__name__,
695
        )
696
697
698
def _check_command_status(xml: str) -> bool:
699
    """Check gmp response
700
701
    Look into the gmp response and check for the status in the root element
702
703
    Arguments:
704
        xml: XML-Source
705
706
    Returns:
707
        True if valid, otherwise False
708
    """
709
710
    if xml is 0 or xml is None:
0 ignored issues
show
introduced by
Comparison to literal
Loading history...
711
        logger.error("XML Command is empty")
712
        return False
713
714
    try:
715
        root = etree.XML(xml, parser=create_parser())
716
        status = root.attrib["status"]
717
        return status is not None and status[0] == "2"
718
719
    except etree.Error as e:
720
        logger.error("etree.XML(xml): %s", e)
721
        return False
722
723
724
def _to_bool(value: bool) -> str:
725
    return "1" if value else "0"
726
727
728
def _to_base64(value: bytes) -> str:
729
    return base64.b64encode(value.encode("utf-8"))
730
731
732
def _to_comma_list(value: List) -> str:
733
    return ",".join(value)
734
735
736
def _add_filter(cmd, filter, filter_id):
737
    if filter:
738
        cmd.set_attribute("filter", filter)
739
740
    if filter_id:
741
        cmd.set_attribute("filt_id", filter_id)
742
743
744
def _check_event(
745
    event: AlertEvent, condition: AlertCondition, method: AlertMethod
746
):
747
    if event == AlertEvent.TASK_RUN_STATUS_CHANGED:
748
        if condition not in (
749
            AlertCondition.ALWAYS,
750
            AlertCondition.FILTER_COUNT_CHANGED,
751
            AlertCondition.FILTER_COUNT_AT_LEAST,
752
            AlertCondition.SEVERITY_AT_LEAST,
753
        ):
754
            raise InvalidArgument(
755
                "Invalid condition {} for event {}".format(
756
                    condition.name, event.name
757
                )
758
            )
759
        if method not in (
760
            AlertMethod.SCP,
761
            AlertMethod.SEND,
762
            AlertMethod.SMB,
763
            AlertMethod.SNMP,
764
            AlertMethod.SYSLOG,
765
            AlertMethod.EMAIL,
766
            AlertMethod.START_TASK,
767
            AlertMethod.HTTP_GET,
768
            AlertMethod.SOURCEFIRE_CONNECTOR,
769
            AlertMethod.VERINICE_CONNECTOR,
770
        ):
771
            raise InvalidArgument(
772
                "Invalid method {} for event {}".format(method.name, event.name)
773
            )
774
    elif event in (
775
        AlertEvent.NEW_SECINFO_ARRIVED,
776
        AlertEvent.UPDATED_SECINFO_ARRIVED,
777
    ):
778
        if condition not in (AlertCondition.ALWAYS,):
779
            raise InvalidArgument(
780
                "Invalid condition {} for event {}".format(
781
                    condition.name, event.name
782
                )
783
            )
784
        if method not in (
785
            AlertMethod.SCP,
786
            AlertMethod.SEND,
787
            AlertMethod.SNMP,
788
            AlertMethod.SYSLOG,
789
            AlertMethod.EMAIL,
790
        ):
791
            raise InvalidArgument(
792
                "Invalid method {} for event {}".format(method.name, event.name)
793
            )
794
    elif event is not None:
795
        raise InvalidArgument('Invalid event "{}"'.format(event.name))
796
797
798
def _is_list_like(value: Any) -> bool:
799
    return isinstance(value, (list, tuple))
800
801
802
class Gmp(GvmProtocol):
0 ignored issues
show
best-practice introduced by
Too many public methods (162/30)
Loading history...
803
    """Python interface for Greenbone Management Protocol
804
805
    This class implements the `Greenbone Management Protocol version 7`_
806
807
    Arguments:
808
        connection: Connection to use to talk with the gvmd daemon. See
809
            :mod:`gvm.connections` for possible connection types.
810
        transform: Optional transform `callable`_ to convert response data.
811
            After each request the callable gets passed the plain response data
812
            which can be used to check the data and/or conversion into different
813
            representations like a xml dom.
814
815
            See :mod:`gvm.transforms` for existing transforms.
816
817
    .. _Greenbone Management Protocol version 7:
818
        https://docs.greenbone.net/API/GMP/gmp-7.0.html
819
    .. _callable:
820
        https://docs.python.org/3/library/functions.html#callable
821
    """
822
823
    _filter_type = FilterType
824
    _entity_type = EntityType
825
826
    def __init__(
827
        self,
828
        connection: GvmConnection,
829
        *,
830
        transform: Optional[Callable[[str], Any]] = None
831
    ):
832
        super().__init__(connection, transform=transform)
833
834
        # Is authenticated on gvmd
835
        self._authenticated = False
836
837
    @staticmethod
838
    def get_protocol_version() -> str:
839
        """Determine the Greenbone Management Protocol version.
840
841
        Returns:
842
            Implemented version of the Greenbone Management Protocol
843
        """
844
        return get_version_string(PROTOCOL_VERSION)
845
846
    def is_authenticated(self) -> bool:
847
        """Checks if the user is authenticated
848
849
        If the user is authenticated privileged GMP commands like get_tasks
850
        may be send to gvmd.
851
852
        Returns:
853
            bool: True if an authenticated connection to gvmd has been
854
            established.
855
        """
856
        return self._authenticated
857
858
    def authenticate(self, username: str, password: str) -> Any:
859
        """Authenticate to gvmd.
860
861
        The generated authenticate command will be send to server.
862
        Afterwards the response is read, transformed and returned.
863
864
        Arguments:
865
            username: Username
866
            password: Password
867
868
        Returns:
869
            Transformed response from server.
870
        """
871
        cmd = XmlCommand("authenticate")
872
873
        if not username:
874
            raise RequiredArgument("authenticate requires username")
875
876
        if not password:
877
            raise RequiredArgument("authenticate requires password")
878
879
        credentials = cmd.add_element("credentials")
880
        credentials.add_element("username", username)
881
        credentials.add_element("password", password)
882
883
        self._send(cmd.to_string())
884
        response = self._read()
885
886
        if _check_command_status(response):
887
            self._authenticated = True
888
889
        return self._transform(response)
890
891
    def create_agent(
892
        self,
893
        installer: str,
894
        signature: str,
895
        name: str,
896
        *,
897
        comment: Optional[str] = None,
898
        howto_install: Optional[str] = None,
899
        howto_use: Optional[str] = None
900
    ) -> Any:
901
        """Create a new agent
902
903
        Arguments:
904
            installer: A base64 encoded file that installs the agent on a
905
                target machine
906
            signature: A detached OpenPGP signature of the installer
907
            name: A name for the agent
908
            comment: A comment for the agent
909
            howto_install: A file that describes how to install the agent
910
            howto_use: A file that describes how to use the agent
911
912
        Returns:
913
            The response. See :py:meth:`send_command` for details.
914
        """
915
        if not name:
916
            raise RequiredArgument("create_agent requires name argument")
917
918
        if not installer:
919
            raise RequiredArgument("create_agent requires installer argument")
920
921
        if not signature:
922
            raise RequiredArgument("create_agent requires signature argument")
923
924
        cmd = XmlCommand("create_agent")
925
        cmd.add_element("installer", installer)
926
        cmd.add_element("signature", signature)
927
        cmd.add_element("name", name)
928
929
        if comment:
930
            cmd.add_element("comment", comment)
931
932
        if howto_install:
933
            cmd.add_element("howto_install", howto_install)
934
935
        if howto_use:
936
            cmd.add_element("howto_use", howto_use)
937
938
        return self._send_xml_command(cmd)
939
940
    def clone_agent(self, agent_id: str) -> Any:
941
        """Clone an existing agent
942
943
        Arguments:
944
            agent_id: UUID of an existing agent to clone from
945
946
        Returns:
947
            The response. See :py:meth:`send_command` for details.
948
        """
949
        if not agent_id:
950
            raise RequiredArgument("clone_agent requires a agent_id argument")
951
952
        cmd = XmlCommand("create_agent")
953
        cmd.add_element("copy", agent_id)
954
        return self._send_xml_command(cmd)
955
956
    def create_alert(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (18/15).
Loading history...
957
        self,
958
        name: str,
959
        condition: AlertCondition,
960
        event: AlertEvent,
961
        method: AlertMethod,
962
        *,
963
        method_data: Optional[dict] = None,
964
        event_data: Optional[dict] = None,
965
        condition_data: Optional[dict] = None,
966
        filter_id: Optional[int] = None,
967
        comment: Optional[str] = None
968
    ) -> Any:
969
        """Create a new alert
970
971
        Arguments:
972
            name: Name of the new Alert
973
            condition: The condition that must be satisfied for the alert
974
                to occur; if the event is either 'Updated SecInfo arrived' or
975
                'New SecInfo arrived', condition must be 'Always'. Otherwise,
976
                condition can also be on of 'Severity at least', 'Filter count
977
                changed' or 'Filter count at least'.
978
            event: The event that must happen for the alert to occur, one
979
                of 'Task run status changed', 'Updated SecInfo arrived' or 'New
980
                SecInfo arrived'
981
            method: The method by which the user is alerted, one of 'SCP',
982
                'Send', 'SMB', 'SNMP', 'Syslog' or 'Email'; if the event is
983
                neither 'Updated SecInfo arrived' nor 'New SecInfo arrived',
984
                method can also be one of 'Start Task', 'HTTP Get', 'Sourcefire
985
                Connector' or 'verinice Connector'.
986
            condition_data: Data that defines the condition
987
            event_data: Data that defines the event
988
            method_data: Data that defines the method
989
            filter_id: Filter to apply when executing alert
990
            comment: Comment for the alert
991
992
        Returns:
993
            The response. See :py:meth:`send_command` for details.
994
        """
995
        if not name:
996
            raise RequiredArgument("create_alert requires name argument")
997
998
        if not condition:
999
            raise RequiredArgument("create_alert requires condition argument")
1000
1001
        if not event:
1002
            raise RequiredArgument("create_alert requires event argument")
1003
1004
        if not method:
1005
            raise RequiredArgument("create_alert requires method argument")
1006
1007
        if not isinstance(condition, AlertCondition):
1008
            raise InvalidArgument(function="create_alert", argument="condition")
1009
1010
        if not isinstance(event, AlertEvent):
1011
            raise InvalidArgument(function="create_alert", argument="event")
1012
1013
        if not isinstance(method, AlertMethod):
1014
            raise InvalidArgument(function="create_alert", argument="method")
1015
1016
        _check_event(event, condition, method)
1017
1018
        cmd = XmlCommand("create_alert")
1019
        cmd.add_element("name", name)
1020
1021
        conditions = cmd.add_element("condition", condition.value)
1022
1023
        if not condition_data is None:
1024
            for key, value in condition_data.items():
1025
                _data = conditions.add_element("data", value)
1026
                _data.add_element("name", key)
1027
1028
        events = cmd.add_element("event", event.value)
1029
1030
        if not event_data is None:
1031
            for key, value in event_data.items():
1032
                _data = events.add_element("data", value)
1033
                _data.add_element("name", key)
1034
1035
        methods = cmd.add_element("method", method.value)
1036
1037
        if not method_data is None:
1038
            for key, value in method_data.items():
1039
                _data = methods.add_element("data", value)
1040
                _data.add_element("name", key)
1041
1042
        if filter_id:
1043
            cmd.add_element("filter", attrs={"id": filter_id})
1044
1045
        if comment:
1046
            cmd.add_element("comment", comment)
1047
1048
        return self._send_xml_command(cmd)
1049
1050
    def clone_alert(self, alert_id: str) -> Any:
1051
        """Clone an existing alert
1052
1053
        Arguments:
1054
            alert_id: UUID of an existing alert to clone from
1055
1056
        Returns:
1057
            The response. See :py:meth:`send_command` for details.
1058
        """
1059
        if not alert_id:
1060
            raise RequiredArgument("clone_alert requires a alert_id argument")
1061
1062
        cmd = XmlCommand("create_alert")
1063
        cmd.add_element("copy", alert_id)
1064
        return self._send_xml_command(cmd)
1065
1066
    def create_config(self, config_id: str, name: str) -> Any:
1067
        """Create a new scan config from an existing one
1068
1069
        Arguments:
1070
            config_id: UUID of the existing scan config
1071
            name: Name of the new scan config
1072
1073
        Returns:
1074
            The response. See :py:meth:`send_command` for details.
1075
        """
1076
        if not name:
1077
            raise RequiredArgument("create_config requires name argument")
1078
1079
        if not config_id:
1080
            raise RequiredArgument("create_config requires config_id argument")
1081
1082
        cmd = XmlCommand("create_config")
1083
        cmd.add_element("copy", config_id)
1084
        cmd.add_element("name", name)
1085
        return self._send_xml_command(cmd)
1086
1087
    def clone_config(self, config_id: str) -> Any:
1088
        """Clone a scan config from an existing one
1089
1090
        Arguments:
1091
            config_id: UUID of the existing scan config
1092
1093
        Returns:
1094
            The response. See :py:meth:`send_command` for details.
1095
        """
1096
        if not config_id:
1097
            raise RequiredArgument("clone_config requires config_id argument")
1098
1099
        cmd = XmlCommand("create_config")
1100
        cmd.add_element("copy", config_id)
1101
        return self._send_xml_command(cmd)
1102
1103
    def import_config(self, config: str) -> Any:
1104
        """Import a scan config from XML
1105
1106
        Arguments:
1107
            config: Scan Config XML as string to import. This XML must
1108
                contain a :code:`<get_configs_response>` root element.
1109
1110
        Returns:
1111
            The response. See :py:meth:`send_command` for details.
1112
        """
1113
        if not config:
1114
            raise RequiredArgument("import_config requires config argument")
1115
1116
        cmd = XmlCommand("create_config")
1117
1118
        try:
1119
            cmd.append_xml_str(config)
1120
        except etree.XMLSyntaxError as e:
1121
            raise InvalidArgument(
1122
                "Invalid xml passed as config to import_config {}".format(e)
1123
            )
1124
1125
        return self._send_xml_command(cmd)
1126
1127
    def create_credential(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (18/15).
Loading history...
1128
        self,
1129
        name: str,
1130
        credential_type: CredentialType,
1131
        *,
1132
        comment: Optional[str] = None,
1133
        allow_insecure: Optional[bool] = None,
1134
        certificate: Optional[str] = None,
1135
        key_phrase: Optional[str] = None,
1136
        private_key: Optional[str] = None,
1137
        login: Optional[str] = None,
1138
        password: Optional[str] = None,
1139
        auth_algorithm: Optional[SnmpAuthAlgorithm] = None,
1140
        community: Optional[str] = None,
1141
        privacy_algorithm: Optional[SnmpPrivacyAlgorithm] = None,
1142
        privacy_password: Optional[str] = None
1143
    ) -> Any:
1144
        """Create a new credential
1145
1146
        Create a new credential e.g. to be used in the method of an alert.
1147
1148
        Currently the following credential types are supported:
1149
1150
            - Username + Password
1151
            - Username + private SSH-Key
1152
            - Client Certificates
1153
            - SNMPv1 or SNMPv2c protocol
1154
1155
        Arguments:
1156
            name: Name of the new credential
1157
            credential_type: The credential type.
1158
            comment: Comment for the credential
1159
            allow_insecure: Whether to allow insecure use of the credential
1160
            certificate: Certificate for the credential.
1161
                Required for cc credential type.
1162
            key_phrase: Key passphrase for the private key.
1163
                Used for the usk credential type.
1164
            private_key: Private key to use for login. Required
1165
                for usk credential type. Also used for the cc credential type.
1166
                The supported key types (dsa, rsa, ecdsa, ...) and formats (PEM,
1167
                PKC#12, OpenSSL, ...) depend on your installed GnuTLS version.
1168
            login: Username for the credential. Required for
1169
                up, usk and snmp credential type.
1170
            password: Password for the credential. Used for
1171
                up and snmp credential types.
1172
            community: The SNMP community.
1173
            auth_algorithm: The SNMP authentication algorithm.
1174
                Required for snmp credential type.
1175
            privacy_algorithm: The SNMP privacy algorithm.
1176
            privacy_password: The SNMP privacy password
1177
1178
        Examples:
1179
            Creating a Username + Password credential
1180
1181
            .. code-block:: python
1182
1183
                gmp.create_credential(
1184
                    name='UP Credential',
1185
                    credential_type=CredentialType.USENAME_PASSWORD,
1186
                    login='foo',
1187
                    password='bar',
1188
                );
1189
1190
            Creating a Username + SSH Key credential
1191
1192
            .. code-block:: python
1193
1194
                with open('path/to/private-ssh-key') as f:
1195
                    key = f.read()
1196
1197
                gmp.create_credential(
1198
                    name='USK Credential',
1199
                    credential_type=CredentialType.USERNAME_SSH_KEY,
1200
                    login='foo',
1201
                    key_phrase='foobar',
1202
                    private_key=key,
1203
                )
1204
1205
        Returns:
1206
            The response. See :py:meth:`send_command` for details.
1207
        """
1208
        if not name:
1209
            raise RequiredArgument("create_credential requires name argument")
1210
1211
        if not isinstance(credential_type, CredentialType):
1212
            raise InvalidArgument(
1213
                "create_credential requires type to be a CredentialType "
1214
                "instance",
1215
                function="create_credential",
1216
                argument="credential_type",
1217
            )
1218
1219
        cmd = XmlCommand("create_credential")
1220
        cmd.add_element("name", name)
1221
1222
        cmd.add_element("type", credential_type.value)
1223
1224
        if comment:
1225
            cmd.add_element("comment", comment)
1226
1227
        if allow_insecure is not None:
1228
            cmd.add_element("allow_insecure", _to_bool(allow_insecure))
1229
1230
        if credential_type == CredentialType.CLIENT_CERTIFICATE:
1231
            if not certificate:
1232
                raise RequiredArgument(
1233
                    "create_credential requires certificate argument for "
1234
                    "credential_type {0}".format(credential_type.name),
1235
                    function="create_credential",
1236
                    argument="certificate",
1237
                )
1238
1239
            cmd.add_element("certificate", certificate)
1240
1241 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1242
            credential_type == CredentialType.USERNAME_PASSWORD
0 ignored issues
show
Unused Code introduced by
Consider merging these comparisons with "in" to 'credential_type in (CredentialType.USERNAME_PASSWORD, CredentialType.USERNAME_SSH_KEY, CredentialType.SNMP)'
Loading history...
1243
            or credential_type == CredentialType.USERNAME_SSH_KEY
1244
            or credential_type == CredentialType.SNMP
1245
        ):
1246
            if not login:
1247
                raise RequiredArgument(
1248
                    "create_credential requires login argument for "
1249
                    "credential_type {0}".format(credential_type.name),
1250
                    function="create_credential",
1251
                    argument="login",
1252
                )
1253
1254
            cmd.add_element("login", login)
1255
1256
        if (
1257
            credential_type == CredentialType.USERNAME_PASSWORD
0 ignored issues
show
Unused Code introduced by
Consider merging these comparisons with "in" to 'credential_type in (CredentialType.USERNAME_PASSWORD, CredentialType.SNMP)'
Loading history...
1258
            or credential_type == CredentialType.SNMP
1259
        ) and password:
1260
            cmd.add_element("password", password)
1261
1262 View Code Duplication
        if credential_type == CredentialType.USERNAME_SSH_KEY:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1263
            if not private_key:
1264
                raise RequiredArgument(
1265
                    "create_credential requires private_key argument for "
1266
                    "credential_type {0}".format(credential_type.name),
1267
                    function="create_credential",
1268
                    argument="private_key",
1269
                )
1270
1271
            _xmlkey = cmd.add_element("key")
1272
            _xmlkey.add_element("private", private_key)
1273
1274
            if key_phrase:
1275
                _xmlkey.add_element("phrase", key_phrase)
1276
1277
        if credential_type == CredentialType.CLIENT_CERTIFICATE and private_key:
1278
            _xmlkey = cmd.add_element("key")
1279
            _xmlkey.add_element("private", private_key)
1280
1281 View Code Duplication
        if credential_type == CredentialType.SNMP:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1282
            if not isinstance(auth_algorithm, SnmpAuthAlgorithm):
1283
                raise InvalidArgument(
1284
                    "create_credential requires auth_algorithm to be a "
1285
                    "SnmpAuthAlgorithm instance",
1286
                    function="create_credential",
1287
                    argument="auth_algorithm",
1288
                )
1289
1290
            cmd.add_element("auth_algorithm", auth_algorithm.value)
1291
1292
            if community:
1293
                cmd.add_element("community", community)
1294
1295
            if privacy_algorithm is not None or privacy_password:
1296
                _xmlprivacy = cmd.add_element("privacy")
1297
1298
                if privacy_algorithm is not None:
1299
                    if not isinstance(privacy_algorithm, SnmpPrivacyAlgorithm):
1300
                        raise InvalidArgument(
1301
                            "create_credential requires algorithm to be a "
1302
                            "SnmpPrivacyAlgorithm instance",
1303
                            function="create_credential",
1304
                            argument="privacy_algorithm",
1305
                        )
1306
1307
                    _xmlprivacy.add_element(
1308
                        "algorithm", privacy_algorithm.value
1309
                    )
1310
1311
                if privacy_password:
1312
                    _xmlprivacy.add_element("password", privacy_password)
1313
1314
        return self._send_xml_command(cmd)
1315
1316
    def clone_credential(self, credential_id: str) -> Any:
1317
        """Clone an existing credential
1318
1319
        Arguments:
1320
            credential_id: UUID of an existing credential to clone from
1321
1322
        Returns:
1323
            The response. See :py:meth:`send_command` for details.
1324
        """
1325
        if not credential_id:
1326
            raise RequiredArgument(
1327
                "clone_credential requires a credential_id argument"
1328
            )
1329
1330
        cmd = XmlCommand("create_credential")
1331
        cmd.add_element("copy", credential_id)
1332
        return self._send_xml_command(cmd)
1333
1334 View Code Duplication
    def create_filter(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1335
        self,
1336
        name: str,
1337
        *,
1338
        make_unique: Optional[bool] = None,
1339
        filter_type: Optional[FilterType] = None,
1340
        comment: Optional[str] = None,
1341
        term: Optional[str] = None
1342
    ) -> Any:
1343
        """Create a new filter
1344
1345
        Arguments:
1346
            name: Name of the new filter
1347
            make_unique:
1348
            filter_type: Filter for entity type
1349
            comment: Comment for the filter
1350
            term: Filter term e.g. 'name=foo'
1351
1352
        Returns:
1353
            The response. See :py:meth:`send_command` for details.
1354
        """
1355
        if not name:
1356
            raise RequiredArgument(function="create_filter", argument="name")
1357
1358
        cmd = XmlCommand("create_filter")
1359
        _xmlname = cmd.add_element("name", name)
1360
1361
        if comment:
1362
            cmd.add_element("comment", comment)
1363
1364
        if term:
1365
            cmd.add_element("term", term)
1366
1367
        if make_unique is not None:
1368
            cmd.add_element("make_unique", _to_bool(make_unique))
1369
1370
        if filter_type:
1371
            if not isinstance(filter_type, self._filter_type):
1372
                raise InvalidArgument(
1373
                    "create_filter requires filter_type to be a FilterType "
1374
                    "instance. was {}".format(filter_type),
1375
                    function="create_filter",
1376
                    argument="filter_type",
1377
                )
1378
1379
            cmd.add_element("type", filter_type.value)
1380
1381
        return self._send_xml_command(cmd)
1382
1383
    def clone_filter(self, filter_id: str) -> Any:
1384
        """Clone an existing filter
1385
1386
        Arguments:
1387
            filter_id: UUID of an existing filter to clone from
1388
1389
        Returns:
1390
            The response. See :py:meth:`send_command` for details.
1391
        """
1392
        if not filter_id:
1393
            raise RequiredArgument("clone_filter requires a filter_id argument")
1394
1395
        cmd = XmlCommand("create_filter")
1396
        cmd.add_element("copy", filter_id)
1397
        return self._send_xml_command(cmd)
1398
1399
    def create_group(
1400
        self,
1401
        name: str,
1402
        *,
1403
        comment: Optional[str] = None,
1404
        special: Optional[bool] = False,
1405
        users: Optional[List[str]] = None
1406
    ) -> Any:
1407
        """Create a new group
1408
1409
        Arguments:
1410
            name: Name of the new group
1411
            comment: Comment for the group
1412
            special: Create permission giving members full access to each
1413
                other's entities
1414
            users: List of user names to be in the group
1415
1416
        Returns:
1417
            The response. See :py:meth:`send_command` for details.
1418
        """
1419
        if not name:
1420
            raise RequiredArgument("create_group requires a name argument")
1421
1422
        cmd = XmlCommand("create_group")
1423
        cmd.add_element("name", name)
1424
1425
        if comment:
1426
            cmd.add_element("comment", comment)
1427
1428
        if special:
1429
            _xmlspecial = cmd.add_element("specials")
1430
            _xmlspecial.add_element("full")
1431
1432
        if users:
1433
            cmd.add_element("users", _to_comma_list(users))
1434
1435
        return self._send_xml_command(cmd)
1436
1437
    def clone_group(self, group_id: str) -> Any:
1438
        """Clone an existing group
1439
1440
        Arguments:
1441
            group_id: UUID of an existing group to clone from
1442
1443
        Returns:
1444
            The response. See :py:meth:`send_command` for details.
1445
        """
1446
        if not group_id:
1447
            raise RequiredArgument("clone_group requires a group_id argument")
1448
1449
        cmd = XmlCommand("create_group")
1450
        cmd.add_element("copy", group_id)
1451
        return self._send_xml_command(cmd)
1452
1453
    def create_host(self, name: str, *, comment: Optional[str] = None) -> Any:
1454
        """Create a new host asset
1455
1456
        Arguments:
1457
            name: Name for the new host asset
1458
            comment: Comment for the new host asset
1459
1460
        Returns:
1461
            The response. See :py:meth:`send_command` for details.
1462
        """
1463
        if not name:
1464
            raise RequiredArgument("create_host requires name argument")
1465
1466
        cmd = XmlCommand("create_asset")
1467
        asset = cmd.add_element("asset")
1468
        asset.add_element("type", "host")  # ignored for gmp7, required for gmp8
1469
        asset.add_element("name", name)
1470
1471
        if comment:
1472
            asset.add_element("comment", comment)
1473
1474
        return self._send_xml_command(cmd)
1475
1476 View Code Duplication
    def create_note(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1477
        self,
1478
        text: str,
1479
        nvt_oid: str,
1480
        *,
1481
        seconds_active: Optional[int] = None,
1482
        hosts: Optional[List[str]] = None,
1483
        port: Optional[int] = None,
1484
        result_id: Optional[str] = None,
1485
        severity: Optional[Severity] = None,
1486
        task_id: Optional[str] = None,
1487
        threat: Optional[SeverityLevel] = None
1488
    ) -> Any:
1489
        """Create a new note
1490
1491
        Arguments:
1492
            text: Text of the new note
1493
            nvt_id: OID of the nvt to which note applies
1494
            seconds_active: Seconds note will be active. -1 on
1495
                always, 0 off
1496
            hosts: A list of hosts addresses
1497
            port: Port to which the note applies
1498
            result_id: UUID of a result to which note applies
1499
            severity: Severity to which note applies
1500
            task_id: UUID of task to which note applies
1501
            threat: Severity level to which note applies. Will be converted to
1502
                severity.
1503
1504
        Returns:
1505
            The response. See :py:meth:`send_command` for details.
1506
        """
1507
        if not text:
1508
            raise RequiredArgument("create_note requires a text argument")
1509
1510
        if not nvt_oid:
1511
            raise RequiredArgument("create_note requires a nvt_oid argument")
1512
1513
        cmd = XmlCommand("create_note")
1514
        cmd.add_element("text", text)
1515
        cmd.add_element("nvt", attrs={"oid": nvt_oid})
1516
1517
        if not seconds_active is None:
1518
            cmd.add_element("active", str(seconds_active))
1519
1520
        if hosts:
1521
            cmd.add_element("hosts", _to_comma_list(hosts))
1522
1523
        if port:
1524
            cmd.add_element("port", str(port))
1525
1526
        if result_id:
1527
            cmd.add_element("result", attrs={"id": result_id})
1528
1529
        if severity:
1530
            cmd.add_element("severity", str(severity))
1531
1532
        if task_id:
1533
            cmd.add_element("task", attrs={"id": task_id})
1534
1535
        if threat is not None:
1536
            if not isinstance(threat, SeverityLevel):
1537
                raise InvalidArgument(
1538
                    "create_note threat argument {0} is invalid. threat must "
1539
                    "be a SeverityLevel instance",
1540
                    function="create_note",
1541
                    argument="threat",
1542
                )
1543
1544
            cmd.add_element("threat", threat.value)
1545
1546
        return self._send_xml_command(cmd)
1547
1548
    def clone_note(self, note_id: str) -> Any:
1549
        """Clone an existing note
1550
1551
        Arguments:
1552
            note_id: UUID of an existing note to clone from
1553
1554
        Returns:
1555
            The response. See :py:meth:`send_command` for details.
1556
        """
1557
        if not note_id:
1558
            raise RequiredArgument("clone_note requires a note_id argument")
1559
1560
        cmd = XmlCommand("create_note")
1561
        cmd.add_element("copy", note_id)
1562
        return self._send_xml_command(cmd)
1563
1564 View Code Duplication
    def create_override(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1565
        self,
1566
        text: str,
1567
        nvt_oid: str,
1568
        *,
1569
        seconds_active: Optional[int] = None,
1570
        hosts: Optional[List[str]] = None,
1571
        port: Optional[int] = None,
1572
        result_id: Optional[str] = None,
1573
        severity: Optional[Severity] = None,
1574
        new_severity: Optional[Severity] = None,
1575
        task_id: Optional[str] = None,
1576
        threat: Optional[SeverityLevel] = None,
1577
        new_threat: Optional[SeverityLevel] = None
1578
    ) -> Any:
1579
        """Create a new override
1580
1581
        Arguments:
1582
            text: Text of the new override
1583
            nvt_id: OID of the nvt to which override applies
1584
            seconds_active: Seconds override will be active. -1 on always, 0 off
1585
            hosts: A list of host addresses
1586
            port: Port to which the override applies
1587
            result_id: UUID of a result to which override applies
1588
            severity: Severity to which override applies
1589
            new_severity: New severity for result
1590
            task_id: UUID of task to which override applies
1591
            threat: Severity level to which override applies. Will be converted
1592
                to severity.
1593
            new_threat: New severity level for results. Will be converted to
1594
                new_severity.
1595
1596
        Returns:
1597
            The response. See :py:meth:`send_command` for details.
1598
        """
1599
        if not text:
1600
            raise RequiredArgument("create_override requires a text argument")
1601
1602
        if not nvt_oid:
1603
            raise RequiredArgument(
1604
                "create_override requires a nvt_oid " "argument"
1605
            )
1606
1607
        cmd = XmlCommand("create_override")
1608
        cmd.add_element("text", text)
1609
        cmd.add_element("nvt", attrs={"oid": nvt_oid})
1610
1611
        if not seconds_active is None:
1612
            cmd.add_element("active", str(seconds_active))
1613
1614
        if hosts:
1615
            cmd.add_element("hosts", _to_comma_list(hosts))
1616
1617
        if port:
1618
            cmd.add_element("port", str(port))
1619
1620
        if result_id:
1621
            cmd.add_element("result", attrs={"id": result_id})
1622
1623
        if severity:
1624
            cmd.add_element("severity", str(severity))
1625
1626
        if new_severity:
1627
            cmd.add_element("new_severity", str(new_severity))
1628
1629
        if task_id:
1630
            cmd.add_element("task", attrs={"id": task_id})
1631
1632
        if threat is not None:
1633
            if not isinstance(threat, SeverityLevel):
1634
                raise InvalidArgument(
1635
                    "create_override threat argument {0} is invalid. threat "
1636
                    "must be a SeverityLevel instance".format(threat),
1637
                    function="create_override",
1638
                    argument="threat",
1639
                )
1640
1641
            cmd.add_element("threat", threat.value)
1642
1643
        if new_threat is not None:
1644
            if not isinstance(new_threat, SeverityLevel):
1645
                raise InvalidArgument(
1646
                    "create_override new_threat argument {0} is invalid. "
1647
                    "new_threat be a SeverityLevel instance".format(new_threat),
1648
                    function="create_override",
1649
                    argument="new_threat",
1650
                )
1651
1652
            cmd.add_element("new_threat", new_threat.value)
1653
1654
        return self._send_xml_command(cmd)
1655
1656
    def clone_override(self, override_id: str) -> Any:
1657
        """Clone an existing override
1658
1659
        Arguments:
1660
            override_id: UUID of an existing override to clone from
1661
1662
        Returns:
1663
            The response. See :py:meth:`send_command` for details.
1664
        """
1665
        if not override_id:
1666
            raise RequiredArgument(
1667
                "clone_override requires a override_id argument"
1668
            )
1669
1670
        cmd = XmlCommand("create_override")
1671
        cmd.add_element("copy", override_id)
1672
        return self._send_xml_command(cmd)
1673
1674
    def create_permission(
1675
        self,
1676
        name: str,
1677
        subject_id: str,
1678
        subject_type: PermissionSubjectType,
1679
        *,
1680
        resource_id: Optional[str] = None,
1681
        resource_type: Optional[EntityType] = None,
1682
        comment: Optional[str] = None
1683
    ) -> Any:
1684
        """Create a new permission
1685
1686
        Arguments:
1687
            name: Name of the new permission
1688
            subject_id: UUID of subject to whom the permission is granted
1689
            subject_type: Type of the subject user, group or role
1690
            comment: Comment for the permission
1691
            resource_id: UUID of entity to which the permission applies
1692
            resource_type: Type of the resource. For Super permissions user,
1693
                group or role
1694
1695
        Returns:
1696
            The response. See :py:meth:`send_command` for details.
1697
        """
1698
        if not name:
1699
            raise RequiredArgument("create_permission requires a name argument")
1700
1701
        if not subject_id:
1702
            raise RequiredArgument(
1703
                "create_permission requires a subject_id argument"
1704
            )
1705
1706
        if not isinstance(subject_type, PermissionSubjectType):
1707
            raise InvalidArgument(
1708
                "create_permission requires subject_type to be a "
1709
                "PermissionSubjectType instance",
1710
                function="create_permission",
1711
                argument="subject_type",
1712
            )
1713
1714
        cmd = XmlCommand("create_permission")
1715
        cmd.add_element("name", name)
1716
1717
        _xmlsubject = cmd.add_element("subject", attrs={"id": subject_id})
1718
        _xmlsubject.add_element("type", subject_type.value)
1719
1720
        if comment:
1721
            cmd.add_element("comment", comment)
1722
1723 View Code Duplication
        if resource_id or resource_type:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1724
            if not resource_id:
1725
                raise RequiredArgument(
1726
                    "create_permission requires resource_id for resource_type"
1727
                )
1728
1729
            if not resource_type:
1730
                raise RequiredArgument(
1731
                    "create_permission requires resource_type for resource_id"
1732
                )
1733
1734
            if not isinstance(resource_type, self._entity_type):
1735
                raise InvalidArgument(
1736
                    function="create_permission", argument="resource_type"
1737
                )
1738
1739
            _xmlresource = cmd.add_element(
1740
                "resource", attrs={"id": resource_id}
1741
            )
1742
            _xmlresource.add_element("type", resource_type.value)
1743
1744
        return self._send_xml_command(cmd)
1745
1746
    def clone_permission(self, permission_id: str) -> Any:
1747
        """Clone an existing permission
1748
1749
        Arguments:
1750
            permission_id: UUID of an existing permission to clone from
1751
1752
        Returns:
1753
            The response. See :py:meth:`send_command` for details.
1754
        """
1755
        if not permission_id:
1756
            raise RequiredArgument(
1757
                "clone_permission requires a permission_id argument"
1758
            )
1759
1760
        cmd = XmlCommand("create_permission")
1761
        cmd.add_element("copy", permission_id)
1762
        return self._send_xml_command(cmd)
1763
1764
    def create_port_list(
1765
        self, name: str, port_range: str, *, comment: Optional[str] = None
1766
    ) -> Any:
1767
        """Create a new port list
1768
1769
        Arguments:
1770
            name: Name of the new port list
1771
            port_range: Port list ranges e.g. `"T: 1-1234"` for tcp port
1772
                1 - 1234
1773
            comment: Comment for the port list
1774
1775
        Returns:
1776
            The response. See :py:meth:`send_command` for details.
1777
        """
1778
        if not name:
1779
            raise RequiredArgument("create_port_list requires a name argument")
1780
1781
        if not port_range:
1782
            raise RequiredArgument(
1783
                "create_port_list requires a port_range argument"
1784
            )
1785
1786
        cmd = XmlCommand("create_port_list")
1787
        cmd.add_element("name", name)
1788
        cmd.add_element("port_range", port_range)
1789
1790
        if comment:
1791
            cmd.add_element("comment", comment)
1792
1793
        return self._send_xml_command(cmd)
1794
1795
    def clone_port_list(self, port_list_id: str) -> Any:
1796
        """Clone an existing port list
1797
1798
        Arguments:
1799
            port_list_id: UUID of an existing port list to clone from
1800
1801
        Returns:
1802
            The response. See :py:meth:`send_command` for details.
1803
        """
1804
        if not port_list_id:
1805
            raise RequiredArgument(
1806
                "clone_port_list requires a port_list_id argument"
1807
            )
1808
1809
        cmd = XmlCommand("create_port_list")
1810
        cmd.add_element("copy", port_list_id)
1811
        return self._send_xml_command(cmd)
1812
1813
    def create_port_range(
1814
        self,
1815
        port_list_id: str,
1816
        start: int,
1817
        end: int,
1818
        port_range_type: PortRangeType,
1819
        *,
1820
        comment: Optional[str] = None
1821
    ) -> Any:
1822
        """Create new port range
1823
1824
        Arguments:
1825
            port_list_id: UUID of the port list to which to add the range
1826
            start: The first port in the range
1827
            end: The last port in the range
1828
            port_range_type: The type of the ports: TCP, UDP, ...
1829
            comment: Comment for the port range
1830
1831
        Returns:
1832
            The response. See :py:meth:`send_command` for details.
1833
        """
1834
        if not port_list_id:
1835
            raise RequiredArgument(
1836
                "create_port_range requires a port_list_id argument"
1837
            )
1838
1839
        if not port_range_type:
1840
            raise RequiredArgument(
1841
                "create_port_range requires a port_range_type argument"
1842
            )
1843
1844
        if not start:
1845
            raise RequiredArgument(
1846
                "create_port_range requires a start argument"
1847
            )
1848
1849
        if not end:
1850
            raise RequiredArgument("create_port_range requires a end argument")
1851
1852
        if not isinstance(port_range_type, PortRangeType):
1853
            raise InvalidArgument(
1854
                function="create_port_range", argument="port_range_type"
1855
            )
1856
1857
        cmd = XmlCommand("create_port_range")
1858
        cmd.add_element("port_list", attrs={"id": port_list_id})
1859
        cmd.add_element("start", str(start))
1860
        cmd.add_element("end", str(end))
1861
        cmd.add_element("type", port_range_type.value)
1862
1863
        if comment:
1864
            cmd.add_element("comment", comment)
1865
1866
        return self._send_xml_command(cmd)
1867
1868
    def import_report(
1869
        self,
1870
        report: str,
1871
        *,
1872
        task_id: Optional[str] = None,
1873
        task_name: Optional[str] = None,
1874
        task_comment: Optional[str] = None,
1875
        in_assets: Optional[bool] = None
1876
    ) -> Any:
1877
        """Import a Report from XML
1878
1879
        Arguments:
1880
            report: Report XML as string to import. This XML must contain
1881
                a :code:`<report>` root element.
1882
            task_id: UUID of task to import report to
1883
            task_name: Name of task to be created if task_id is not present.
1884
                Either task_id or task_name must be passed
1885
            task_comment: Comment for task to be created if task_id is not
1886
                present
1887
            in_asset: Whether to create or update assets using the report
1888
1889
        Returns:
1890
            The response. See :py:meth:`send_command` for details.
1891
        """
1892
        if not report:
1893
            raise RequiredArgument("import_report requires a report argument")
1894
1895
        cmd = XmlCommand("create_report")
1896
1897
        if task_id:
1898
            cmd.add_element("task", attrs={"id": task_id})
1899
        elif task_name:
1900
            _xmltask = cmd.add_element("task")
1901
            _xmltask.add_element("name", task_name)
1902
1903
            if task_comment:
1904
                _xmltask.add_element("comment", task_comment)
1905
        else:
1906
            raise RequiredArgument(
1907
                "import_report requires a task_id or task_name argument"
1908
            )
1909
1910
        if not in_assets is None:
1911
            cmd.add_element("in_assets", _to_bool(in_assets))
1912
1913
        try:
1914
            cmd.append_xml_str(report)
1915
        except etree.XMLSyntaxError as e:
1916
            raise InvalidArgument(
1917
                "Invalid xml passed as report to import_report {}".format(e)
1918
            )
1919
1920
        return self._send_xml_command(cmd)
1921
1922
    def create_role(
1923
        self,
1924
        name: str,
1925
        *,
1926
        comment: Optional[str] = None,
1927
        users: Optional[List[str]] = None
1928
    ) -> Any:
1929
        """Create a new role
1930
1931
        Arguments:
1932
            name: Name of the role
1933
            comment: Comment for the role
1934
            users: List of user names to add to the role
1935
1936
        Returns:
1937
            The response. See :py:meth:`send_command` for details.
1938
        """
1939
1940
        if not name:
1941
            raise RequiredArgument("create_role requires a name argument")
1942
1943
        cmd = XmlCommand("create_role")
1944
        cmd.add_element("name", name)
1945
1946
        if comment:
1947
            cmd.add_element("comment", comment)
1948
1949
        if users:
1950
            cmd.add_element("users", _to_comma_list(users))
1951
1952
        return self._send_xml_command(cmd)
1953
1954
    def clone_role(self, role_id: str) -> Any:
1955
        """Clone an existing role
1956
1957
        Arguments:
1958
            role_id: UUID of an existing role to clone from
1959
1960
        Returns:
1961
            The response. See :py:meth:`send_command` for details.
1962
        """
1963
        if not role_id:
1964
            raise RequiredArgument("clone_role requires a role_id argument")
1965
1966
        cmd = XmlCommand("create_role")
1967
        cmd.add_element("copy", role_id)
1968
        return self._send_xml_command(cmd)
1969
1970
    def create_scanner(
1971
        self,
1972
        name: str,
1973
        host: str,
1974
        port: int,
1975
        scanner_type: ScannerType,
1976
        credential_id: str,
1977
        *,
1978
        ca_pub: Optional[str] = None,
1979
        comment: Optional[str] = None
1980
    ) -> Any:
1981
        """Create a new scanner
1982
1983
        Arguments:
1984
            name: Name of the scanner
1985
            host: The host of the scanner
1986
            port: The port of the scanner
1987
            scanner_type: Type of the scanner.
1988
            credential_id: UUID of client certificate credential for the
1989
                scanner
1990
            ca_pub: Certificate of CA to verify scanner certificate
1991
            comment: Comment for the scanner
1992
1993
        Returns:
1994
            The response. See :py:meth:`send_command` for details.
1995
        """
1996
        if not name:
1997
            raise RequiredArgument("create_scanner requires a name argument")
1998
1999
        if not host:
2000
            raise RequiredArgument("create_scanner requires a host argument")
2001
2002
        if not port:
2003
            raise RequiredArgument("create_scanner requires a port argument")
2004
2005
        if not scanner_type:
2006
            raise RequiredArgument(
2007
                "create_scanner requires a scanner_type " "argument"
2008
            )
2009
2010
        if not credential_id:
2011
            raise RequiredArgument(
2012
                "create_scanner requires a credential_id " "argument"
2013
            )
2014
2015
        if not isinstance(scanner_type, ScannerType):
2016
            raise InvalidArgument(
2017
                function="create_scanner", argument="scanner_type"
2018
            )
2019
2020
        cmd = XmlCommand("create_scanner")
2021
        cmd.add_element("name", name)
2022
        cmd.add_element("host", host)
2023
        cmd.add_element("port", str(port))
2024
        cmd.add_element("type", scanner_type.value)
2025
2026
        if ca_pub:
2027
            cmd.add_element("ca_pub", ca_pub)
2028
2029
        cmd.add_element("credential", attrs={"id": str(credential_id)})
2030
2031
        if comment:
2032
            cmd.add_element("comment", comment)
2033
2034
        return self._send_xml_command(cmd)
2035
2036
    def clone_scanner(self, scanner_id: str) -> Any:
2037
        """Clone an existing scanner
2038
2039
        Arguments:
2040
            scanner_id: UUID of an existing scanner to clone from
2041
2042
        Returns:
2043
            The response. See :py:meth:`send_command` for details.
2044
        """
2045
        if not scanner_id:
2046
            raise RequiredArgument(
2047
                "clone_scanner requires a scanner_id argument"
2048
            )
2049
2050
        cmd = XmlCommand("create_scanner")
2051
        cmd.add_element("copy", scanner_id)
2052
        return self._send_xml_command(cmd)
2053
2054 View Code Duplication
    def create_schedule(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
Comprehensibility introduced by
This function exceeds the maximum number of variables (18/15).
Loading history...
2055
        self,
2056
        name: str,
2057
        *,
2058
        comment: Optional[str] = None,
2059
        first_time_minute: Optional[int] = None,
2060
        first_time_hour: Optional[int] = None,
2061
        first_time_day_of_month: Optional[int] = None,
2062
        first_time_month: Optional[int] = None,
2063
        first_time_year: Optional[int] = None,
2064
        duration: Optional[int] = None,
2065
        duration_unit: Optional[TimeUnit] = None,
2066
        period: Optional[int] = None,
2067
        period_unit: Optional[TimeUnit] = None,
2068
        timezone: Optional[str] = None
2069
    ) -> Any:
2070
        """Create a new schedule
2071
2072
        Arguments:
2073
            name: Name of the schedule
2074
            comment: Comment for the schedule
2075
            first_time_minute: First time minute the schedule will run. Must be
2076
                an integer >= 0.
2077
            first_time_hour: First time hour the schedule will run. Must be an
2078
                integer >= 0.
2079
            first_time_day_of_month: First time day of month the schedule will
2080
                run. Must be an integer > 0 <= 31.
2081
            first_time_month: First time month the schedule will run. Must be an
2082
                integer >= 1 <= 12.
2083
            first_time_year: First time year the schedule will run. Must be an
2084
                integer >= 1970.
2085
            duration: How long the Manager will run the scheduled task for until
2086
                it gets paused if not finished yet. Must be an integer > 0.
2087
            duration_unit: Unit of the duration. One of second,
2088
                minute, hour, day, week, month, year, decade. Required if
2089
                duration is set.
2090
            period: How often the Manager will repeat the
2091
                scheduled task. Must be an integer > 0.
2092
            period_unit: Unit of the period. One of second,
2093
                minute, hour, day, week, month, year, decade. Required if
2094
                period is set.
2095
            timezone: The timezone the schedule will follow
2096
2097
        Returns:
2098
            The response. See :py:meth:`send_command` for details.
2099
        """
2100
        if not name:
2101
            raise RequiredArgument("create_schedule requires a name argument")
2102
2103
        cmd = XmlCommand("create_schedule")
2104
        cmd.add_element("name", name)
2105
2106
        if comment:
2107
            cmd.add_element("comment", comment)
2108
2109
        if (
2110
            first_time_minute is not None
2111
            or first_time_hour is not None
2112
            or first_time_day_of_month is not None
2113
            or first_time_month is not None
2114
            or first_time_year is not None
2115
        ):
2116
2117
            if first_time_minute is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
2118
                raise RequiredArgument(
2119
                    "Setting first_time requires first_time_minute argument"
2120
                )
2121
            elif (
2122
                not isinstance(first_time_minute, numbers.Integral)
2123
                or first_time_minute < 0
2124
            ):
2125
                raise InvalidArgument(
2126
                    "first_time_minute argument of create_schedule needs to be "
2127
                    "an integer greater or equal 0"
2128
                )
2129
2130
            if first_time_hour is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
2131
                raise RequiredArgument(
2132
                    "Setting first_time requires first_time_hour argument"
2133
                )
2134
            elif (
2135
                not isinstance(first_time_hour, numbers.Integral)
2136
                or first_time_hour < 0
2137
            ):
2138
                raise InvalidArgument(
2139
                    "first_time_hour argument of create_schedule needs to be "
2140
                    "an integer greater or equal 0"
2141
                )
2142
2143
            if first_time_day_of_month is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
2144
                raise RequiredArgument(
2145
                    "Setting first_time requires first_time_day_of_month "
2146
                    "argument"
2147
                )
2148
            elif (
2149
                not isinstance(first_time_day_of_month, numbers.Integral)
2150
                or first_time_day_of_month < 1
2151
                or first_time_day_of_month > 31
2152
            ):
2153
                raise InvalidArgument(
2154
                    "first_time_day_of_month argument of create_schedule needs "
2155
                    "to be an integer between 1 and 31"
2156
                )
2157
2158
            if first_time_month is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
2159
                raise RequiredArgument(
2160
                    "Setting first_time requires first_time_month argument"
2161
                )
2162
            elif (
2163
                not isinstance(first_time_month, numbers.Integral)
2164
                or first_time_month < 1
2165
                or first_time_month > 12
2166
            ):
2167
                raise InvalidArgument(
2168
                    "first_time_month argument of create_schedule needs "
2169
                    "to be an integer between 1 and 12"
2170
                )
2171
2172
            if first_time_year is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
2173
                raise RequiredArgument(
2174
                    "Setting first_time requires first_time_year argument"
2175
                )
2176
            elif (
2177
                not isinstance(first_time_year, numbers.Integral)
2178
                or first_time_year < 1970
2179
            ):
2180
                raise InvalidArgument(
2181
                    "first_time_year argument of create_schedule needs "
2182
                    "to be an integer greater or equal 1970"
2183
                )
2184
2185
            _xmlftime = cmd.add_element("first_time")
2186
            _xmlftime.add_element("minute", str(first_time_minute))
2187
            _xmlftime.add_element("hour", str(first_time_hour))
2188
            _xmlftime.add_element("day_of_month", str(first_time_day_of_month))
2189
            _xmlftime.add_element("month", str(first_time_month))
2190
            _xmlftime.add_element("year", str(first_time_year))
2191
2192
        if duration is not None:
2193
            if not duration_unit:
2194
                raise RequiredArgument(
2195
                    "Setting duration requires duration_unit argument"
2196
                )
2197
2198
            if not isinstance(duration_unit, TimeUnit):
2199
                raise InvalidArgument(
2200
                    function="create_schedule", argument="duration_unit"
2201
                )
2202
2203
            if not isinstance(duration, numbers.Integral) or duration < 1:
2204
                raise InvalidArgument(
2205
                    "duration argument must be an integer greater than 0"
2206
                )
2207
2208
            _xmlduration = cmd.add_element("duration", str(duration))
2209
            _xmlduration.add_element("unit", duration_unit.value)
2210
2211
        if period is not None:
2212
            if not period_unit:
2213
                raise RequiredArgument(
2214
                    "Setting period requires period_unit argument"
2215
                )
2216
2217
            if not isinstance(period_unit, TimeUnit):
2218
                raise InvalidArgument(
2219
                    function="create_schedule", argument="period_unit"
2220
                )
2221
2222
            if not isinstance(period, numbers.Integral) or period < 0:
2223
                raise InvalidArgument(
2224
                    "period argument must be a positive integer"
2225
                )
2226
2227
            _xmlperiod = cmd.add_element("period", str(period))
2228
            _xmlperiod.add_element("unit", period_unit.value)
2229
2230
        if timezone:
2231
            cmd.add_element("timezone", timezone)
2232
2233
        return self._send_xml_command(cmd)
2234
2235
    def clone_schedule(self, schedule_id: str) -> Any:
2236
        """Clone an existing schedule
2237
2238
        Arguments:
2239
            schedule_id: UUID of an existing schedule to clone from
2240
2241
        Returns:
2242
            The response. See :py:meth:`send_command` for details.
2243
        """
2244
        if not schedule_id:
2245
            raise RequiredArgument(
2246
                "clone_schedule requires a schedule_id argument"
2247
            )
2248
2249
        cmd = XmlCommand("create_schedule")
2250
        cmd.add_element("copy", schedule_id)
2251
        return self._send_xml_command(cmd)
2252
2253
    def create_tag(
2254
        self,
2255
        name: str,
2256
        resource_type: EntityType,
2257
        *,
2258
        resource_id: Optional[str] = None,
2259
        value: Optional[str] = None,
2260
        comment: Optional[str] = None,
2261
        active: Optional[bool] = None
2262
    ) -> Any:
2263
        """Create a new tag
2264
2265
        Arguments:
2266
            name: Name of the tag. A full tag name consisting of namespace
2267
                and predicate e.g. `foo:bar`.
2268
            resource_id: ID of the resource the tag is to be attached to.
2269
            resource_type: Entity type the tag is to be attached to
2270
            value: Value associated with the tag
2271
            comment: Comment for the tag
2272
            active: Whether the tag should be active
2273
2274
        Returns:
2275
            The response. See :py:meth:`send_command` for details.
2276
        """
2277
        if not name:
2278
            raise RequiredArgument("create_tag requires name argument")
2279
2280
        if not resource_type:
2281
            raise RequiredArgument("create_tag requires resource_type argument")
2282
2283
        if not isinstance(resource_type, self._entity_type):
2284
            raise InvalidArgument(
2285
                function="create_tag", argument="resource_type"
2286
            )
2287
2288
        cmd = XmlCommand("create_tag")
2289
        cmd.add_element("name", name)
2290
2291
        if not resource_id:
2292
            resource_id = ''
2293
2294
        _xmlresource = cmd.add_element(
2295
            "resource", attrs={"id": str(resource_id)}
2296
        )
2297
        _xmlresource.add_element("type", resource_type.value)
2298
2299
        if comment:
2300
            cmd.add_element("comment", comment)
2301
2302
        if value:
2303
            cmd.add_element("value", value)
2304
2305
        if not active is None:
2306
            if active:
2307
                cmd.add_element("active", "1")
2308
            else:
2309
                cmd.add_element("active", "0")
2310
2311
        return self._send_xml_command(cmd)
2312
2313
    def clone_tag(self, tag_id: str) -> Any:
2314
        """Clone an existing tag
2315
2316
        Arguments:
2317
            tag_id: UUID of an existing tag to clone from
2318
2319
        Returns:
2320
            The response. See :py:meth:`send_command` for details.
2321
        """
2322
        if not tag_id:
2323
            raise RequiredArgument("clone_tag requires a tag_id argument")
2324
2325
        cmd = XmlCommand("create_tag")
2326
        cmd.add_element("copy", tag_id)
2327
        return self._send_xml_command(cmd)
2328
2329
    def create_target(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (21/15).
Loading history...
2330
        self,
2331
        name: str,
2332
        *,
2333
        make_unique: Optional[bool] = None,
2334
        asset_hosts_filter: Optional[str] = None,
2335
        hosts: Optional[List[str]] = None,
2336
        comment: Optional[str] = None,
2337
        exclude_hosts: Optional[List[str]] = None,
2338
        ssh_credential_id: Optional[str] = None,
2339
        ssh_credential_port: Optional[int] = None,
2340
        smb_credential_id: Optional[str] = None,
2341
        esxi_credential_id: Optional[str] = None,
2342
        snmp_credential_id: Optional[str] = None,
2343
        alive_test: Optional[AliveTest] = None,
2344
        reverse_lookup_only: Optional[bool] = None,
2345
        reverse_lookup_unify: Optional[bool] = None,
2346
        port_range: Optional[str] = None,
2347
        port_list_id: Optional[str] = None
2348
    ) -> Any:
2349
        """Create a new target
2350
2351
        Arguments:
2352
            name: Name of the target
2353
            make_unique: Append a unique suffix if the name already exists
2354
            asset_hosts_filter: Filter to select target host from assets hosts
2355
            hosts: List of hosts addresses to scan
2356
            exclude_hosts: List of hosts addresses to exclude from scan
2357
            comment: Comment for the target
2358
            ssh_credential_id: UUID of a ssh credential to use on target
2359
            ssh_credential_port: The port to use for ssh credential
2360
            smb_credential_id: UUID of a smb credential to use on target
2361
            snmp_credential_id: UUID of a snmp credential to use on target
2362
            esxi_credential_id: UUID of a esxi credential to use on target
2363
            alive_test: Which alive test to use
2364
            reverse_lookup_only: Whether to scan only hosts that have names
2365
            reverse_lookup_unify: Whether to scan only one IP when multiple IPs
2366
                have the same name.
2367
            port_range: Port range for the target
2368
            port_list_id: UUID of the port list to use on target
2369
2370
        Returns:
2371
            The response. See :py:meth:`send_command` for details.
2372
        """
2373
        if not name:
2374
            raise RequiredArgument("create_target requires a name argument")
2375
2376
        cmd = XmlCommand("create_target")
2377
        _xmlname = cmd.add_element("name", name)
2378
2379
        if make_unique is not None:
2380
            _xmlname.add_element("make_unique", _to_bool(make_unique))
2381
2382
        if asset_hosts_filter:
2383
            cmd.add_element(
2384
                "asset_hosts", attrs={"filter": str(asset_hosts_filter)}
2385
            )
2386
        elif hosts:
2387
            cmd.add_element("hosts", _to_comma_list(hosts))
2388
        else:
2389
            raise RequiredArgument(
2390
                "create_target requires either a hosts or "
2391
                "an asset_hosts_filter argument"
2392
            )
2393
2394
        if comment:
2395
            cmd.add_element("comment", comment)
2396
2397
        if exclude_hosts:
2398
            cmd.add_element("exclude_hosts", _to_comma_list(exclude_hosts))
2399
2400
        if ssh_credential_id:
2401
            _xmlssh = cmd.add_element(
2402
                "ssh_credential", attrs={"id": ssh_credential_id}
2403
            )
2404
            if ssh_credential_port:
2405
                _xmlssh.add_element("port", str(ssh_credential_port))
2406
2407
        if smb_credential_id:
2408
            cmd.add_element("smb_credential", attrs={"id": smb_credential_id})
2409
2410
        if esxi_credential_id:
2411
            cmd.add_element("esxi_credential", attrs={"id": esxi_credential_id})
2412
2413
        if snmp_credential_id:
2414
            cmd.add_element("snmp_credential", attrs={"id": snmp_credential_id})
2415
2416
        if alive_test:
2417
            if not isinstance(alive_test, AliveTest):
2418
                raise InvalidArgument(
2419
                    function="create_target", argument="alive_test"
2420
                )
2421
2422
            cmd.add_element("alive_tests", alive_test.value)
2423
2424
        if not reverse_lookup_only is None:
2425
            cmd.add_element(
2426
                "reverse_lookup_only", _to_bool(reverse_lookup_only)
2427
            )
2428
2429
        if not reverse_lookup_unify is None:
2430
            cmd.add_element(
2431
                "reverse_lookup_unify", _to_bool(reverse_lookup_unify)
2432
            )
2433
2434
        if port_range:
2435
            cmd.add_element("port_range", port_range)
2436
2437
        if port_list_id:
2438
            cmd.add_element("port_list", attrs={"id": port_list_id})
2439
2440
        return self._send_xml_command(cmd)
2441
2442
    def clone_target(self, target_id: str) -> Any:
2443
        """Clone an existing target
2444
2445
        Arguments:
2446
            target_id: UUID of an existing target to clone from
2447
2448
        Returns:
2449
            The response. See :py:meth:`send_command` for details.
2450
        """
2451
        if not target_id:
2452
            raise RequiredArgument("clone_target requires a target_id argument")
2453
2454
        cmd = XmlCommand("create_target")
2455
        cmd.add_element("copy", target_id)
2456
        return self._send_xml_command(cmd)
2457
2458
    def create_task(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (20/15).
Loading history...
2459
        self,
2460
        name: str,
2461
        config_id: str,
2462
        target_id: str,
2463
        scanner_id: str,
2464
        *,
2465
        alterable: Optional[bool] = None,
2466
        hosts_ordering: Optional[HostsOrdering] = None,
2467
        schedule_id: Optional[str] = None,
2468
        alert_ids: Optional[List[str]] = None,
2469
        comment: Optional[str] = None,
2470
        schedule_periods: Optional[int] = None,
2471
        observers: Optional[List[str]] = None,
2472
        preferences: Optional[dict] = None
2473
    ) -> Any:
2474
        """Create a new task
2475
2476
        Arguments:
2477
            name: Name of the task
2478
            config_id: UUID of scan config to use by the task
2479
            target_id: UUID of target to be scanned
2480
            scanner_id: UUID of scanner to use for scanning the target
2481
            comment: Comment for the task
2482
            alterable: Whether the task should be alterable
2483
            alert_ids: List of UUIDs for alerts to be applied to the task
2484
            hosts_ordering: The order hosts are scanned in
2485
            schedule_id: UUID of a schedule when the task should be run.
2486
            schedule_periods: A limit to the number of times the task will be
2487
                scheduled, or 0 for no limit
2488
            observers: List of names or ids of users which should be allowed to
2489
                observe this task
2490
            preferences: Name/Value pairs of scanner preferences.
2491
2492
        Returns:
2493
            The response. See :py:meth:`send_command` for details.
2494
        """
2495
        if not name:
2496
            raise RequiredArgument("create_task requires a name argument")
2497
2498
        if not config_id:
2499
            raise RequiredArgument("create_task requires a config_id argument")
2500
2501
        if not target_id:
2502
            raise RequiredArgument("create_task requires a target_id argument")
2503
2504
        if not scanner_id:
2505
            raise RequiredArgument("create_task requires a scanner_id argument")
2506
2507
        # don't allow to create a container task with create_task
2508
        if target_id == '0':
2509
            raise InvalidArgument(
2510
                'Invalid argument {} for target_id'.format(target_id)
2511
            )
2512
2513
        cmd = XmlCommand("create_task")
2514
        cmd.add_element("name", name)
2515
        cmd.add_element("config", attrs={"id": config_id})
2516
        cmd.add_element("target", attrs={"id": target_id})
2517
        cmd.add_element("scanner", attrs={"id": scanner_id})
2518
2519
        if comment:
2520
            cmd.add_element("comment", comment)
2521
2522
        if not alterable is None:
2523
            cmd.add_element("alterable", _to_bool(alterable))
2524
2525
        if hosts_ordering:
2526
            if not isinstance(hosts_ordering, HostsOrdering):
2527
                raise InvalidArgument(
2528
                    function="create_task", argument="hosts_ordering"
2529
                )
2530
            cmd.add_element("hosts_ordering", hosts_ordering.value)
2531
2532
        if alert_ids:
2533
            if isinstance(alert_ids, str):
2534
                deprecation(
2535
                    "Please pass a list as alert_ids parameter to create_task. "
2536
                    "Passing a string is deprecated and will be removed in "
2537
                    "future."
2538
                )
2539
2540
                # if a single id is given as a string wrap it into a list
2541
                alert_ids = [alert_ids]
2542
            if _is_list_like(alert_ids):
2543
                # parse all given alert id's
2544
                for alert in alert_ids:
2545
                    cmd.add_element("alert", attrs={"id": str(alert)})
2546
2547
        if schedule_id:
2548
            cmd.add_element("schedule", attrs={"id": schedule_id})
2549
2550 View Code Duplication
            if schedule_periods is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
2551
                if (
2552
                    not isinstance(schedule_periods, numbers.Integral)
2553
                    or schedule_periods < 0
2554
                ):
2555
                    raise InvalidArgument(
2556
                        "schedule_periods must be an integer greater or equal "
2557
                        "than 0"
2558
                    )
2559
                cmd.add_element("schedule_periods", str(schedule_periods))
2560
2561
        if observers is not None:
2562
            if not _is_list_like(observers):
2563
                raise InvalidArgument("obeservers argument must be a list")
2564
2565
            # gvmd splits by comma and space
2566
            # gvmd tries to lookup each value as user name and afterwards as
2567
            # user id. So both user name and user id are possible
2568
            cmd.add_element("observers", _to_comma_list(observers))
2569
2570
        if preferences is not None:
2571
            if not isinstance(preferences, collections.abc.Mapping):
2572
                raise InvalidArgument('preferences argument must be a dict')
2573
2574
            _xmlprefs = cmd.add_element("preferences")
2575
            for pref_name, pref_value in preferences.items():
2576
                _xmlpref = _xmlprefs.add_element("preference")
2577
                _xmlpref.add_element("scanner_name", pref_name)
2578
                _xmlpref.add_element("value", str(pref_value))
2579
2580
        return self._send_xml_command(cmd)
2581
2582
    def create_container_task(
2583
        self, name: str, *, comment: Optional[str] = None
2584
    ) -> Any:
2585
        """Create a new container task
2586
2587
        A container task is a "meta" task to import and view reports from other
2588
        systems.
2589
2590
        Arguments:
2591
            name: Name of the task
2592
            comment: Comment for the task
2593
2594
        Returns:
2595
            The response. See :py:meth:`send_command` for details.
2596
        """
2597
        if not name:
2598
            raise RequiredArgument("create_task requires a name argument")
2599
2600
        cmd = XmlCommand("create_task")
2601
        cmd.add_element("name", name)
2602
        cmd.add_element("target", attrs={"id": "0"})
2603
2604
        if comment:
2605
            cmd.add_element("comment", comment)
2606
2607
        return self._send_xml_command(cmd)
2608
2609
    def clone_task(self, task_id: str) -> Any:
2610
        """Clone an existing task
2611
2612
        Arguments:
2613
            task_id: UUID of existing task to clone from
2614
2615
        Returns:
2616
            The response. See :py:meth:`send_command` for details.
2617
        """
2618
        if not task_id:
2619
            raise RequiredArgument("clone_task requires a task_id argument")
2620
2621
        cmd = XmlCommand("create_task")
2622
        cmd.add_element("copy", task_id)
2623
        return self._send_xml_command(cmd)
2624
2625
    def create_user(
2626
        self,
2627
        name: str,
2628
        *,
2629
        password: Optional[str] = None,
2630
        hosts: Optional[List[str]] = None,
2631
        hosts_allow: Optional[bool] = False,
2632
        ifaces: Optional[List[str]] = None,
2633
        ifaces_allow: Optional[bool] = False,
2634
        role_ids: Optional[List[str]] = None
2635
    ) -> Any:
2636
        """Create a new user
2637
2638
        Arguments:
2639
            name: Name of the user
2640
            password: Password of the user
2641
            hosts: A list of host addresses (IPs, DNS names)
2642
            hosts_allow: If True allow only access to passed hosts otherwise
2643
                deny access. Default is False for deny hosts.
2644
            ifaces: A list of interface names
2645
            ifaces_allow: If True allow only access to passed interfaces
2646
                otherwise deny access. Default is False for deny interfaces.
2647
            role_ids: A list of role UUIDs for the user
2648
2649
        Returns:
2650
            The response. See :py:meth:`send_command` for details.
2651
        """
2652
        if not name:
2653
            raise RequiredArgument("create_user requires a name argument")
2654
2655
        cmd = XmlCommand("create_user")
2656
        cmd.add_element("name", name)
2657
2658
        if password:
2659
            cmd.add_element("password", password)
2660
2661
        if hosts:
2662
            cmd.add_element(
2663
                "hosts",
2664
                _to_comma_list(hosts),
2665
                attrs={"allow": _to_bool(hosts_allow)},
2666
            )
2667
2668
        if ifaces:
2669
            cmd.add_element(
2670
                "ifaces",
2671
                _to_comma_list(ifaces),
2672
                attrs={"allow": _to_bool(ifaces_allow)},
2673
            )
2674
2675
        if role_ids:
2676
            for role in role_ids:
2677
                cmd.add_element("role", attrs={"id": role})
2678
2679
        return self._send_xml_command(cmd)
2680
2681
    def clone_user(self, user_id: str) -> Any:
2682
        """Clone an existing user
2683
2684
        Arguments:
2685
            user_id: UUID of existing user to clone from
2686
2687
        Returns:
2688
            The response. See :py:meth:`send_command` for details.
2689
        """
2690
        if not user_id:
2691
            raise RequiredArgument("clone_user requires a user_id argument")
2692
2693
        cmd = XmlCommand("create_user")
2694
        cmd.add_element("copy", user_id)
2695
        return self._send_xml_command(cmd)
2696
2697
    def delete_agent(
2698
        self, agent_id: str, *, ultimate: Optional[bool] = False
2699
    ) -> Any:
2700
        """Deletes an existing agent
2701
2702
        Arguments:
2703
            agent_id: UUID of the agent to be deleted.
2704
            ultimate: Whether to remove entirely, or to the trashcan.
2705
        """
2706
        if not agent_id:
2707
            raise RequiredArgument("delete_agent requires an agent_id argument")
2708
2709
        cmd = XmlCommand("delete_agent")
2710
        cmd.set_attribute("agent_id", agent_id)
2711
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2712
2713
        return self._send_xml_command(cmd)
2714
2715
    def delete_alert(
2716
        self, alert_id: str, *, ultimate: Optional[bool] = False
2717
    ) -> Any:
2718
        """Deletes an existing alert
2719
2720
        Arguments:
2721
            alert_id: UUID of the alert to be deleted.
2722
            ultimate: Whether to remove entirely, or to the trashcan.
2723
        """
2724
        if not alert_id:
2725
            raise RequiredArgument("delete_alert requires an alert_id argument")
2726
2727
        cmd = XmlCommand("delete_alert")
2728
        cmd.set_attribute("alert_id", alert_id)
2729
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2730
2731
        return self._send_xml_command(cmd)
2732
2733
    def delete_asset(
2734
        self, *, asset_id: Optional[str] = None, report_id: Optional[str] = None
2735
    ) -> Any:
2736
        """Deletes an existing asset
2737
2738
        Arguments:
2739
            asset_id: UUID of the single asset to delete.
2740
            report_id: UUID of report from which to get all
2741
                assets to delete.
2742
        """
2743
        if not asset_id and not report_id:
2744
            raise RequiredArgument(
2745
                "delete_asset requires an asset_id or a report_id argument"
2746
            )
2747
2748
        cmd = XmlCommand("delete_asset")
2749
        if asset_id:
2750
            cmd.set_attribute("asset_id", asset_id)
2751
        else:
2752
            cmd.set_attribute("report_id", report_id)
2753
2754
        return self._send_xml_command(cmd)
2755
2756
    def delete_config(
2757
        self, config_id: str, *, ultimate: Optional[bool] = False
2758
    ) -> Any:
2759
        """Deletes an existing config
2760
2761
        Arguments:
2762
            config_id: UUID of the config to be deleted.
2763
            ultimate: Whether to remove entirely, or to the trashcan.
2764
        """
2765
        if not config_id:
2766
            raise RequiredArgument(
2767
                "delete_config requires a config_id argument"
2768
            )
2769
2770
        cmd = XmlCommand("delete_config")
2771
        cmd.set_attribute("config_id", config_id)
2772
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2773
2774
        return self._send_xml_command(cmd)
2775
2776
    def delete_credential(
2777
        self, credential_id: str, *, ultimate: Optional[bool] = False
2778
    ) -> Any:
2779
        """Deletes an existing credential
2780
2781
        Arguments:
2782
            credential_id: UUID of the credential to be deleted.
2783
            ultimate: Whether to remove entirely, or to the trashcan.
2784
        """
2785
        if not credential_id:
2786
            raise RequiredArgument(
2787
                "delete_credential requires a credential_id argument"
2788
            )
2789
2790
        cmd = XmlCommand("delete_credential")
2791
        cmd.set_attribute("credential_id", credential_id)
2792
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2793
2794
        return self._send_xml_command(cmd)
2795
2796
    def delete_filter(
2797
        self, filter_id: str, *, ultimate: Optional[bool] = False
2798
    ) -> Any:
2799
        """Deletes an existing filter
2800
2801
        Arguments:
2802
            filter_id: UUID of the filter to be deleted.
2803
            ultimate: Whether to remove entirely, or to the trashcan.
2804
        """
2805
        if not filter_id:
2806
            raise RequiredArgument(
2807
                "delete_filter requires a filter_id argument"
2808
            )
2809
2810
        cmd = XmlCommand("delete_filter")
2811
        cmd.set_attribute("filter_id", filter_id)
2812
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2813
2814
        return self._send_xml_command(cmd)
2815
2816
    def delete_group(
2817
        self, group_id: str, *, ultimate: Optional[bool] = False
2818
    ) -> Any:
2819
        """Deletes an existing group
2820
2821
        Arguments:
2822
            group_id: UUID of the group to be deleted.
2823
            ultimate: Whether to remove entirely, or to the trashcan.
2824
        """
2825
        if not group_id:
2826
            raise RequiredArgument("delete_group requires a group_id argument")
2827
2828
        cmd = XmlCommand("delete_group")
2829
        cmd.set_attribute("group_id", group_id)
2830
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2831
2832
        return self._send_xml_command(cmd)
2833
2834
    def delete_note(
2835
        self, note_id: str, *, ultimate: Optional[bool] = False
2836
    ) -> Any:
2837
        """Deletes an existing note
2838
2839
        Arguments:
2840
            note_id: UUID of the note to be deleted.
2841
            ultimate: Whether to remove entirely,or to the trashcan.
2842
        """
2843
        if not note_id:
2844
            raise RequiredArgument("delete_note requires a note_id argument")
2845
2846
        cmd = XmlCommand("delete_note")
2847
        cmd.set_attribute("note_id", note_id)
2848
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2849
2850
        return self._send_xml_command(cmd)
2851
2852
    def delete_override(
2853
        self, override_id: str, *, ultimate: Optional[bool] = False
2854
    ) -> Any:
2855
        """Deletes an existing override
2856
2857
        Arguments:
2858
            override_id: UUID of the override to be deleted.
2859
            ultimate: Whether to remove entirely, or to the trashcan.
2860
        """
2861
        if not override_id:
2862
            raise RequiredArgument(
2863
                "delete_override requires a override_id argument"
2864
            )
2865
2866
        cmd = XmlCommand("delete_override")
2867
        cmd.set_attribute("override_id", override_id)
2868
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2869
2870
        return self._send_xml_command(cmd)
2871
2872
    def delete_permission(
2873
        self, permission_id: str, *, ultimate: Optional[bool] = False
2874
    ) -> Any:
2875
        """Deletes an existing permission
2876
2877
        Arguments:
2878
            permission_id: UUID of the permission to be deleted.
2879
            ultimate: Whether to remove entirely, or to the trashcan.
2880
        """
2881
        if not permission_id:
2882
            raise RequiredArgument(
2883
                "delete_permission requires a permission_id argument"
2884
            )
2885
2886
        cmd = XmlCommand("delete_permission")
2887
        cmd.set_attribute("permission_id", permission_id)
2888
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2889
2890
        return self._send_xml_command(cmd)
2891
2892
    def delete_port_list(
2893
        self, port_list_id: str, *, ultimate: Optional[bool] = False
2894
    ) -> Any:
2895
        """Deletes an existing port list
2896
2897
        Arguments:
2898
            port_list_id: UUID of the port list to be deleted.
2899
            ultimate: Whether to remove entirely, or to the trashcan.
2900
        """
2901
        if not port_list_id:
2902
            raise RequiredArgument(
2903
                "delete_port_list requires a port_list_id argument"
2904
            )
2905
2906
        cmd = XmlCommand("delete_port_list")
2907
        cmd.set_attribute("port_list_id", port_list_id)
2908
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2909
2910
        return self._send_xml_command(cmd)
2911
2912
    def delete_port_range(self, port_range_id: str) -> Any:
2913
        """Deletes an existing port range
2914
2915
        Arguments:
2916
            port_range_id: UUID of the port range to be deleted.
2917
        """
2918
        if not port_range_id:
2919
            raise RequiredArgument(
2920
                "delete_port_range requires a port_range_id argument"
2921
            )
2922
2923
        cmd = XmlCommand("delete_port_range")
2924
        cmd.set_attribute("port_range_id", port_range_id)
2925
2926
        return self._send_xml_command(cmd)
2927
2928
    def delete_report(self, report_id: str) -> Any:
2929
        """Deletes an existing report
2930
2931
        Arguments:
2932
            report_id: UUID of the report to be deleted.
2933
        """
2934
        if not report_id:
2935
            raise RequiredArgument(
2936
                "delete_report requires a report_id argument"
2937
            )
2938
2939
        cmd = XmlCommand("delete_report")
2940
        cmd.set_attribute("report_id", report_id)
2941
2942
        return self._send_xml_command(cmd)
2943
2944
    def delete_report_format(
2945
        self, report_format_id: str, *, ultimate: Optional[bool] = False
2946
    ) -> Any:
2947
        """Deletes an existing report format
2948
2949
        Arguments:
2950
            report_format_id: UUID of the report format to be deleted.
2951
            ultimate: Whether to remove entirely, or to the trashcan.
2952
        """
2953
        if not report_format_id:
2954
            raise RequiredArgument(
2955
                "delete_report_format requires a report_format_id argument"
2956
            )
2957
2958
        cmd = XmlCommand("delete_report_format")
2959
        cmd.set_attribute("report_format_id", report_format_id)
2960
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2961
2962
        return self._send_xml_command(cmd)
2963
2964
    def delete_role(
2965
        self, role_id: str, *, ultimate: Optional[bool] = False
2966
    ) -> Any:
2967
        """Deletes an existing role
2968
2969
        Arguments:
2970
            role_id: UUID of the role to be deleted.
2971
            ultimate: Whether to remove entirely, or to the trashcan.
2972
        """
2973
        if not role_id:
2974
            raise RequiredArgument("delete_role requires a role_id argument")
2975
2976
        cmd = XmlCommand("delete_role")
2977
        cmd.set_attribute("role_id", role_id)
2978
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2979
2980
        return self._send_xml_command(cmd)
2981
2982
    def delete_scanner(
2983
        self, scanner_id: str, *, ultimate: Optional[bool] = False
2984
    ) -> Any:
2985
        """Deletes an existing scanner
2986
2987
        Arguments:
2988
            scanner_id: UUID of the scanner to be deleted.
2989
            ultimate: Whether to remove entirely, or to the trashcan.
2990
        """
2991
        if not scanner_id:
2992
            raise RequiredArgument(
2993
                "delete_scanner requires a scanner_id argument"
2994
            )
2995
2996
        cmd = XmlCommand("delete_scanner")
2997
        cmd.set_attribute("scanner_id", scanner_id)
2998
        cmd.set_attribute("ultimate", _to_bool(ultimate))
2999
3000
        return self._send_xml_command(cmd)
3001
3002
    def delete_schedule(
3003
        self, schedule_id: str, *, ultimate: Optional[bool] = False
3004
    ) -> Any:
3005
        """Deletes an existing schedule
3006
3007
        Arguments:
3008
            schedule_id: UUID of the schedule to be deleted.
3009
            ultimate: Whether to remove entirely, or to the trashcan.
3010
        """
3011
        if not schedule_id:
3012
            raise RequiredArgument(
3013
                "delete_schedule requires a schedule_id argument"
3014
            )
3015
3016
        cmd = XmlCommand("delete_schedule")
3017
        cmd.set_attribute("schedule_id", schedule_id)
3018
        cmd.set_attribute("ultimate", _to_bool(ultimate))
3019
3020
        return self._send_xml_command(cmd)
3021
3022
    def delete_tag(
3023
        self, tag_id: str, *, ultimate: Optional[bool] = False
3024
    ) -> Any:
3025
        """Deletes an existing tag
3026
3027
        Arguments:
3028
            tag_id: UUID of the tag to be deleted.
3029
            ultimate: Whether to remove entirely, or to the trashcan.
3030
        """
3031
        if not tag_id:
3032
            raise RequiredArgument("delete_tag requires a " "tag_id argument")
3033
3034
        cmd = XmlCommand("delete_tag")
3035
        cmd.set_attribute("tag_id", tag_id)
3036
        cmd.set_attribute("ultimate", _to_bool(ultimate))
3037
3038
        return self._send_xml_command(cmd)
3039
3040
    def delete_target(
3041
        self, target_id: str, *, ultimate: Optional[bool] = False
3042
    ) -> Any:
3043
        """Deletes an existing target
3044
3045
        Arguments:
3046
            target_id: UUID of the target to be deleted.
3047
            ultimate: Whether to remove entirely, or to the trashcan.
3048
        """
3049
        if not target_id:
3050
            raise RequiredArgument(
3051
                "delete_target requires a target_id argument"
3052
            )
3053
3054
        cmd = XmlCommand("delete_target")
3055
        cmd.set_attribute("target_id", target_id)
3056
        cmd.set_attribute("ultimate", _to_bool(ultimate))
3057
3058
        return self._send_xml_command(cmd)
3059
3060
    def delete_task(
3061
        self, task_id: str, *, ultimate: Optional[bool] = False
3062
    ) -> Any:
3063
        """Deletes an existing task
3064
3065
        Arguments:
3066
            task_id: UUID of the task to be deleted.
3067
            ultimate: Whether to remove entirely, or to the trashcan.
3068
        """
3069
        if not task_id:
3070
            raise RequiredArgument("delete_task requires a task_id argument")
3071
3072
        cmd = XmlCommand("delete_task")
3073
        cmd.set_attribute("task_id", task_id)
3074
        cmd.set_attribute("ultimate", _to_bool(ultimate))
3075
3076
        return self._send_xml_command(cmd)
3077
3078
    def delete_user(
3079
        self,
3080
        user_id: str = None,
3081
        *,
3082
        name: Optional[str] = None,
3083
        inheritor_id: Optional[str] = None,
3084
        inheritor_name: Optional[str] = None
3085
    ) -> Any:
3086
        """Deletes an existing user
3087
3088
        Either user_id or name must be passed.
3089
3090
        Arguments:
3091
            user_id: UUID of the task to be deleted.
3092
            name: The name of the user to be deleted.
3093
            inheritor_id: The ID of the inheriting user or "self". Overrides
3094
                inheritor_name.
3095
            inheritor_name: The name of the inheriting user.
3096
3097
        """
3098
        if not user_id and not name:
3099
            raise RequiredArgument(
3100
                "delete_user requires a user_id or name argument"
3101
            )
3102
3103
        cmd = XmlCommand("delete_user")
3104
3105
        if user_id:
3106
            cmd.set_attribute("user_id", user_id)
3107
3108
        if name:
3109
            cmd.set_attribute("name", name)
3110
3111
        if inheritor_id:
3112
            cmd.set_attribute("inheritor_id", inheritor_id)
3113
3114
        if inheritor_name:
3115
            cmd.set_attribute("inheritor_name", inheritor_name)
3116
3117
        return self._send_xml_command(cmd)
3118
3119
    def describe_auth(self) -> Any:
3120
        """Describe authentication methods
3121
3122
        Returns a list of all used authentication methods if such a list is
3123
        available.
3124
3125
        Returns:
3126
            The response. See :py:meth:`send_command` for details.
3127
        """
3128
        return self._send_xml_command(XmlCommand("describe_auth"))
3129
3130
    def empty_trashcan(self) -> Any:
3131
        """Empty the trashcan
3132
3133
        Remove all entities from the trashcan. **Attention:** this command can
3134
        not be reverted
3135
3136
        Returns:
3137
            The response. See :py:meth:`send_command` for details.
3138
        """
3139
        return self._send_xml_command(XmlCommand("empty_trashcan"))
3140
3141 View Code Duplication
    def get_agents(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3142
        self,
3143
        *,
3144
        filter: Optional[str] = None,
3145
        filter_id: Optional[str] = None,
3146
        trash: Optional[bool] = None,
3147
        details: Optional[bool] = None,
3148
        format: Optional[str] = None
3149
    ) -> Any:
3150
        """Request a list of agents
3151
3152
        Arguments:
3153
            filter: Filter term to use for the query
3154
            filter_id: UUID of an existing filter to use for the query
3155
            trash: True to request the agents in the trashcan
3156
            details: Whether to include agents packageinformation when no format
3157
                was provided
3158
            format: One of "installer", "howto_install" or "howto_use"
3159
3160
        Returns:
3161
            The response. See :py:meth:`send_command` for details.
3162
        """
3163
        cmd = XmlCommand("get_agents")
3164
3165
        _add_filter(cmd, filter, filter_id)
3166
3167
        if not trash is None:
3168
            cmd.set_attribute("trash", _to_bool(trash))
3169
3170
        if not details is None:
3171
            cmd.set_attribute("details", _to_bool(details))
3172
3173
        if format:
3174
            if not format in ("installer", "howto_install", "howto_use"):
3175
                raise InvalidArgument(
3176
                    "installer argument needs to be one of installer, "
3177
                    "howto_install or howto_use"
3178
                )
3179
3180
            cmd.set_attribute("format", format)
3181
3182
        return self._send_xml_command(cmd)
3183
3184
    def get_agent(self, agent_id: str) -> Any:
3185
        """Request a single agent
3186
3187
        Arguments:
3188
            agent_id: UUID of an existing agent
3189
3190
        Returns:
3191
            The response. See :py:meth:`send_command` for details.
3192
        """
3193
        if not agent_id:
3194
            raise RequiredArgument("get_agent requires an agent_id argument")
3195
3196
        cmd = XmlCommand("get_agents")
3197
        cmd.set_attribute("agent_id", agent_id)
3198
3199
        # for single entity always request all details
3200
        cmd.set_attribute("details", "1")
3201
        return self._send_xml_command(cmd)
3202
3203
    def get_aggregates(self, resource_type: EntityType, **kwargs) -> Any:
3204
        """Request aggregated information on a resource type
3205
3206
        Additional arguments can be set via the kwargs parameter, but are not
3207
        yet validated.
3208
3209
        Arguments:
3210
           resource_type: The entity type to gather data from
3211
3212
        Returns:
3213
            The response. See :py:meth:`send_command` for details.
3214
        """
3215
        if not resource_type:
3216
            raise RequiredArgument(
3217
                "get_aggregates requires resource_type argument"
3218
            )
3219
3220
        if not isinstance(resource_type, self._entity_type):
3221
            raise InvalidArgument(
3222
                function="get_aggregate", argument="resource_type"
3223
            )
3224
3225
        cmd = XmlCommand("get_aggregates")
3226
3227
        cmd.set_attribute("type", resource_type.value)
3228
3229
        cmd.set_attributes(kwargs)
3230
        return self._send_xml_command(cmd)
3231
3232
    def get_alerts(
3233
        self,
3234
        *,
3235
        filter: Optional[str] = None,
3236
        filter_id: Optional[str] = None,
3237
        trash: Optional[bool] = None,
3238
        tasks: Optional[bool] = None
3239
    ) -> Any:
3240
        """Request a list of alerts
3241
3242
        Arguments:
3243
            filter: Filter term to use for the query
3244
            filter_id: UUID of an existing filter to use for the query
3245
            trash: True to request the alerts in the trashcan
3246
            tasks: Whether to include the tasks using the alerts
3247
        Returns:
3248
            The response. See :py:meth:`send_command` for details.
3249
        """
3250
        cmd = XmlCommand("get_alerts")
3251
3252
        _add_filter(cmd, filter, filter_id)
3253
3254
        if not trash is None:
3255
            cmd.set_attribute("trash", _to_bool(trash))
3256
3257
        if not tasks is None:
3258
            cmd.set_attribute("tasks", _to_bool(tasks))
3259
3260
        return self._send_xml_command(cmd)
3261
3262
    def get_alert(self, alert_id: str) -> Any:
3263
        """Request a single alert
3264
3265
        Arguments:
3266
            alert_id: UUID of an existing alert
3267
3268
        Returns:
3269
            The response. See :py:meth:`send_command` for details.
3270
        """
3271
        if not alert_id:
3272
            raise RequiredArgument("get_alert requires an alert_id argument")
3273
3274
        cmd = XmlCommand("get_alerts")
3275
        cmd.set_attribute("alert_id", alert_id)
3276
        return self._send_xml_command(cmd)
3277
3278
    def get_assets(
3279
        self,
3280
        asset_type: AssetType,
3281
        *,
3282
        filter: Optional[str] = None,
3283
        filter_id: Optional[str] = None
3284
    ) -> Any:
3285
        """Request a list of assets
3286
3287
        Arguments:
3288
            asset_type: Either 'os' or 'host'
3289
            filter: Filter term to use for the query
3290
            filter_id: UUID of an existing filter to use for the query
3291
3292
        Returns:
3293
            The response. See :py:meth:`send_command` for details.
3294
        """
3295
        if not isinstance(asset_type, AssetType):
3296
            raise InvalidArgument(function="get_assets", argument="asset_type")
3297
3298
        cmd = XmlCommand("get_assets")
3299
3300
        cmd.set_attribute("type", asset_type.value)
3301
3302
        _add_filter(cmd, filter, filter_id)
3303
3304
        return self._send_xml_command(cmd)
3305
3306
    def get_asset(self, asset_id: str, asset_type: AssetType) -> Any:
3307
        """Request a single asset
3308
3309
        Arguments:
3310
            asset_id: UUID of an existing asset
3311
            asset_type: Either 'os' or 'host'
3312
3313
        Returns:
3314
            The response. See :py:meth:`send_command` for details.
3315
        """
3316
        if not isinstance(asset_type, AssetType):
3317
            raise InvalidArgument(function="get_asset", argument="asset_type")
3318
3319
        if not asset_id:
3320
            raise RequiredArgument("get_asset requires an asset_type argument")
3321
3322
        cmd = XmlCommand("get_assets")
3323
        cmd.set_attribute("asset_id", asset_id)
3324
        cmd.set_attribute("type", asset_type.value)
3325
3326
        return self._send_xml_command(cmd)
3327
3328
    def get_credentials(
3329
        self,
3330
        *,
3331
        filter: Optional[str] = None,
3332
        filter_id: Optional[str] = None,
3333
        scanners: Optional[bool] = None,
3334
        trash: Optional[bool] = None,
3335
        targets: Optional[bool] = None
3336
    ) -> Any:
3337
        """Request a list of credentials
3338
3339
        Arguments:
3340
            filter: Filter term to use for the query
3341
            filter_id: UUID of an existing filter to use for the query
3342
            scanners: Whether to include a list of scanners using the
3343
                credentials
3344
            trash: Whether to get the trashcan credentials instead
3345
            targets: Whether to include a list of targets using the credentials
3346
3347
        Returns:
3348
            The response. See :py:meth:`send_command` for details.
3349
        """
3350
        cmd = XmlCommand("get_credentials")
3351
3352
        _add_filter(cmd, filter, filter_id)
3353
3354
        if not scanners is None:
3355
            cmd.set_attribute("scanners", _to_bool(scanners))
3356
3357
        if not trash is None:
3358
            cmd.set_attribute("trash", _to_bool(trash))
3359
3360
        if not targets is None:
3361
            cmd.set_attribute("targets", _to_bool(targets))
3362
3363
        return self._send_xml_command(cmd)
3364
3365
    def get_credential(
3366
        self,
3367
        credential_id: str,
3368
        *,
3369
        credential_format: Optional[CredentialFormat] = None
3370
    ) -> Any:
3371
        """Request a single credential
3372
3373
        Arguments:
3374
            credential_id: UUID of an existing credential
3375
            credential_format: One of "key", "rpm", "deb", "exe" or "pem"
3376
3377
        Returns:
3378
            The response. See :py:meth:`send_command` for details.
3379
        """
3380
        if not credential_id:
3381
            raise RequiredArgument(
3382
                "get_credential requires credential_id argument"
3383
            )
3384
3385
        cmd = XmlCommand("get_credentials")
3386
        cmd.set_attribute("credential_id", credential_id)
3387
3388
        if credential_format:
3389
            if not isinstance(credential_format, CredentialFormat):
3390
                raise InvalidArgument(
3391
                    function="get_credential", argument="credential_format"
3392
                )
3393
3394
            cmd.set_attribute("format", credential_format.value)
3395
        return self._send_xml_command(cmd)
3396
3397
    def get_configs(
3398
        self,
3399
        *,
3400
        filter: Optional[str] = None,
3401
        filter_id: Optional[str] = None,
3402
        trash: Optional[bool] = None,
3403
        details: Optional[bool] = None,
3404
        families: Optional[bool] = None,
3405
        preferences: Optional[bool] = None,
3406
        tasks: Optional[bool] = None
3407
    ) -> Any:
3408
        """Request a list of scan configs
3409
3410
        Arguments:
3411
            filter: Filter term to use for the query
3412
            filter_id: UUID of an existing filter to use for the query
3413
            trash: Whether to get the trashcan scan configs instead
3414
            details: Whether to get config families, preferences, nvt selectors
3415
                and tasks.
3416
            families: Whether to include the families if no details are
3417
                requested
3418
            preferences: Whether to include the preferences if no details are
3419
                requested
3420
            tasks: Whether to get tasks using this config
3421
3422
        Returns:
3423
            The response. See :py:meth:`send_command` for details.
3424
        """
3425
        cmd = XmlCommand("get_configs")
3426
3427
        _add_filter(cmd, filter, filter_id)
3428
3429
        if not trash is None:
3430
            cmd.set_attribute("trash", _to_bool(trash))
3431
3432
        if not details is None:
3433
            cmd.set_attribute("details", _to_bool(details))
3434
3435
        if not families is None:
3436
            cmd.set_attribute("families", _to_bool(families))
3437
3438
        if not preferences is None:
3439
            cmd.set_attribute("preferences", _to_bool(preferences))
3440
3441
        if not tasks is None:
3442
            cmd.set_attribute("tasks", _to_bool(tasks))
3443
3444
        return self._send_xml_command(cmd)
3445
3446
    def get_config(self, config_id: str) -> Any:
3447
        """Request a single scan config
3448
3449
        Arguments:
3450
            config_id: UUID of an existing scan config
3451
3452
        Returns:
3453
            The response. See :py:meth:`send_command` for details.
3454
        """
3455
        if not config_id:
3456
            raise RequiredArgument("get_config requires config_id argument")
3457
3458
        cmd = XmlCommand("get_configs")
3459
        cmd.set_attribute("config_id", config_id)
3460
3461
        # for single entity always request all details
3462
        cmd.set_attribute("details", "1")
3463
        return self._send_xml_command(cmd)
3464
3465
    def get_feeds(self) -> Any:
3466
        """Request the list of feeds
3467
3468
        Returns:
3469
            The response. See :py:meth:`send_command` for details.
3470
        """
3471
        return self._send_xml_command(XmlCommand("get_feeds"))
3472
3473
    def get_feed(self, feed_type: Optional[FeedType]) -> Any:
3474
        """Request a single feed
3475
3476
        Arguments:
3477
            feed_type: Type of single feed to get: NVT, CERT or SCAP
3478
3479
        Returns:
3480
            The response. See :py:meth:`send_command` for details.
3481
        """
3482
        if not feed_type:
3483
            raise RequiredArgument("get_feed requires a feed_type argument")
3484
3485
        if not isinstance(feed_type, FeedType):
3486
            raise InvalidArgument(
3487
                "get_feed type arguments must be one of NVT, CERT or SCAP"
3488
            )
3489
3490
        cmd = XmlCommand("get_feeds")
3491
        cmd.set_attribute("type", feed_type.value)
3492
3493
        return self._send_xml_command(cmd)
3494
3495
    def get_filters(
3496
        self,
3497
        *,
3498
        filter: Optional[str] = None,
3499
        filter_id: Optional[str] = None,
3500
        trash: Optional[bool] = None,
3501
        alerts: Optional[bool] = None
3502
    ) -> Any:
3503
        """Request a list of filters
3504
3505
        Arguments:
3506
            filter: Filter term to use for the query
3507
            filter_id: UUID of an existing filter to use for the query
3508
            trash: Whether to get the trashcan filters instead
3509
            alerts: Whether to include list of alerts that use the filter.
3510
3511
        Returns:
3512
            The response. See :py:meth:`send_command` for details.
3513
        """
3514
        cmd = XmlCommand("get_filters")
3515
3516
        _add_filter(cmd, filter, filter_id)
3517
3518
        if not trash is None:
3519
            cmd.set_attribute("trash", _to_bool(trash))
3520
3521
        if not alerts is None:
3522
            cmd.set_attribute("alerts", _to_bool(alerts))
3523
3524
        return self._send_xml_command(cmd)
3525
3526
    def get_filter(self, filter_id: str) -> Any:
3527
        """Request a single filter
3528
3529
        Arguments:
3530
            filter_id: UUID of an existing filter
3531
3532
        Returns:
3533
            The response. See :py:meth:`send_command` for details.
3534
        """
3535
        if not filter_id:
3536
            raise RequiredArgument("get_filter requires a filter_id argument")
3537
3538
        cmd = XmlCommand("get_filters")
3539
        cmd.set_attribute("filter_id", filter_id)
3540
        return self._send_xml_command(cmd)
3541
3542 View Code Duplication
    def get_groups(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3543
        self,
3544
        *,
3545
        filter: Optional[str] = None,
3546
        filter_id: Optional[str] = None,
3547
        trash: Optional[bool] = None
3548
    ) -> Any:
3549
        """Request a list of groups
3550
3551
        Arguments:
3552
            filter: Filter term to use for the query
3553
            filter_id: UUID of an existing filter to use for the query
3554
            trash: Whether to get the trashcan groups instead
3555
3556
        Returns:
3557
            The response. See :py:meth:`send_command` for details.
3558
        """
3559
        cmd = XmlCommand("get_groups")
3560
3561
        _add_filter(cmd, filter, filter_id)
3562
3563
        if not trash is None:
3564
            cmd.set_attribute("trash", _to_bool(trash))
3565
3566
        return self._send_xml_command(cmd)
3567
3568
    def get_group(self, group_id: str) -> Any:
3569
        """Request a single group
3570
3571
        Arguments:
3572
            group_id: UUID of an existing group
3573
3574
        Returns:
3575
            The response. See :py:meth:`send_command` for details.
3576
        """
3577
        if not group_id:
3578
            raise RequiredArgument("get_group requires a group_id argument")
3579
3580
        cmd = XmlCommand("get_groups")
3581
        cmd.set_attribute("group_id", group_id)
3582
        return self._send_xml_command(cmd)
3583
3584
    def get_info_list(
3585
        self,
3586
        info_type: InfoType,
3587
        *,
3588
        filter: Optional[str] = None,
3589
        filter_id: Optional[str] = None,
3590
        name: Optional[str] = None,
3591
        details: Optional[bool] = None
3592
    ) -> Any:
3593
        """Request a list of security information
3594
3595
        Arguments:
3596
            info_type: Type must be either CERT_BUND_ADV, CPE, CVE,
3597
                DFN_CERT_ADV, OVALDEF, NVT or ALLINFO
3598
            filter: Filter term to use for the query
3599
            filter_id: UUID of an existing filter to use for the query
3600
            name: Name or identifier of the requested information
3601
            details: Whether to include information about references to this
3602
                information
3603
3604
        Returns:
3605
            The response. See :py:meth:`send_command` for details.
3606
        """
3607
        if not info_type:
3608
            raise RequiredArgument(
3609
                "get_info_list requires an info_type argument"
3610
            )
3611
3612
        if not isinstance(info_type, InfoType):
3613
            raise InvalidArgument(
3614
                function="get_info_list", argument="info_type"
3615
            )
3616
3617
        cmd = XmlCommand("get_info")
3618
3619
        cmd.set_attribute("type", info_type.value)
3620
3621
        _add_filter(cmd, filter, filter_id)
3622
3623
        if name:
3624
            cmd.set_attribute("name", name)
3625
3626
        if not details is None:
3627
            cmd.set_attribute("details", _to_bool(details))
3628
3629
        return self._send_xml_command(cmd)
3630
3631
    def get_info(self, info_id: str, info_type: InfoType) -> Any:
3632
        """Request a single secinfo
3633
3634
        Arguments:
3635
            info_id: UUID of an existing secinfo
3636
            info_type: Type must be either CERT_BUND_ADV, CPE, CVE,
3637
                DFN_CERT_ADV, OVALDEF, NVT or ALLINFO
3638
3639
        Returns:
3640
            The response. See :py:meth:`send_command` for details.
3641
        """
3642
        if not info_type:
3643
            raise RequiredArgument("get_info requires an info_type argument")
3644
3645
        if not isinstance(info_type, InfoType):
3646
            raise InvalidArgument(function="get_info", argument="info_type")
3647
3648
        if not info_id:
3649
            raise RequiredArgument("get_info requires an info_id argument")
3650
3651
        cmd = XmlCommand("get_info")
3652
        cmd.set_attribute("info_id", info_id)
3653
3654
        cmd.set_attribute("type", info_type.value)
3655
3656
        # for single entity always request all details
3657
        cmd.set_attribute("details", "1")
3658
        return self._send_xml_command(cmd)
3659
3660 View Code Duplication
    def get_notes(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3661
        self,
3662
        *,
3663
        filter: Optional[str] = None,
3664
        filter_id: Optional[str] = None,
3665
        details: Optional[bool] = None,
3666
        result: Optional[bool] = None
3667
    ) -> Any:
3668
        """Request a list of notes
3669
3670
        Arguments:
3671
            filter: Filter term to use for the query
3672
            filter_id: UUID of an existing filter to use for the query
3673
            details: Add info about connected results and tasks
3674
            result: Return the details of possible connected results.
3675
3676
        Returns:
3677
            The response. See :py:meth:`send_command` for details.
3678
        """
3679
        cmd = XmlCommand("get_notes")
3680
3681
        _add_filter(cmd, filter, filter_id)
3682
3683
        if not details is None:
3684
            cmd.set_attribute("details", _to_bool(details))
3685
3686
        if not result is None:
3687
            cmd.set_attribute("result", _to_bool(result))
3688
3689
        return self._send_xml_command(cmd)
3690
3691
    def get_note(self, note_id: str) -> Any:
3692
        """Request a single note
3693
3694
        Arguments:
3695
            note_id: UUID of an existing note
3696
3697
        Returns:
3698
            The response. See :py:meth:`send_command` for details.
3699
        """
3700
        if not note_id:
3701
            raise RequiredArgument("get_note requires a note_id argument")
3702
3703
        cmd = XmlCommand("get_notes")
3704
        cmd.set_attribute("note_id", note_id)
3705
3706
        # for single entity always request all details
3707
        cmd.set_attribute("details", "1")
3708
        return self._send_xml_command(cmd)
3709
3710
    def get_nvts(
3711
        self,
3712
        *,
3713
        details: Optional[bool] = None,
3714
        preferences: Optional[bool] = None,
3715
        preference_count: Optional[bool] = None,
3716
        timeout: Optional[bool] = None,
3717
        config_id: Optional[str] = None,
3718
        preferences_config_id: Optional[str] = None,
3719
        family: Optional[str] = None,
3720
        sort_order: Optional[str] = None,
3721
        sort_field: Optional[str] = None
3722
    ):
3723
        """Request a list of nvts
3724
3725
        Arguments:
3726
            details: Whether to include full details
3727
            preferences: Whether to include nvt preferences
3728
            preference_count: Whether to include preference count
3729
            timeout: Whether to include the special timeout preference
3730
            config_id: UUID of scan config to which to limit the NVT listing
3731
            preferences_config_id: UUID of scan config to use for preference
3732
                values
3733
            family: Family to which to limit NVT listing
3734
            sort_order: Sort order
3735
            sort_field: Sort field
3736
3737
        Returns:
3738
            The response. See :py:meth:`send_command` for details.
3739
        """
3740
        cmd = XmlCommand("get_nvts")
3741
3742
        if not details is None:
3743
            cmd.set_attribute("details", _to_bool(details))
3744
3745
        if not preferences is None:
3746
            cmd.set_attribute("preferences", _to_bool(preferences))
3747
3748
        if not preference_count is None:
3749
            cmd.set_attribute("preference_count", _to_bool(preference_count))
3750
3751
        if not timeout is None:
3752
            cmd.set_attribute("timeout", _to_bool(timeout))
3753
3754
        if config_id:
3755
            cmd.set_attribute("config_id", config_id)
3756
3757
        if preferences_config_id:
3758
            cmd.set_attribute("preferences_config_id", preferences_config_id)
3759
3760
        if family:
3761
            cmd.set_attribute("family", family)
3762
3763
        if sort_order:
3764
            cmd.set_attribute("sort_order", sort_order)
3765
3766
        if sort_field:
3767
            cmd.set_attribute("sort_field", sort_field)
3768
3769
        return self._send_xml_command(cmd)
3770
3771
    def get_nvt(self, nvt_oid: str):
3772
        """Request a single nvt
3773
3774
        Arguments:
3775
            nvt_oid: OID of an existing nvt
3776
3777
        Returns:
3778
            The response. See :py:meth:`send_command` for details.
3779
        """
3780
        if not nvt_oid:
3781
            raise RequiredArgument("get_nvt requires nvt_oid argument")
3782
3783
        cmd = XmlCommand("get_nvts")
3784
        cmd.set_attribute("nvt_oid", nvt_oid)
3785
3786
        # for single entity always request all details
3787
        cmd.set_attribute("details", "1")
3788
        return self._send_xml_command(cmd)
3789
3790
    def get_nvt_families(self, *, sort_order: Optional[str] = None):
3791
        """Request a list of nvt families
3792
3793
        Arguments:
3794
            sort_order: Sort order
3795
3796
        Returns:
3797
            The response. See :py:meth:`send_command` for details.
3798
        """
3799
        cmd = XmlCommand("get_nvt_families")
3800
3801
        if sort_order:
3802
            cmd.set_attribute("sort_order", sort_order)
3803
3804
        return self._send_xml_command(cmd)
3805
3806 View Code Duplication
    def get_overrides(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3807
        self,
3808
        *,
3809
        filter: Optional[str] = None,
3810
        filter_id: Optional[str] = None,
3811
        details: Optional[bool] = None,
3812
        result: Optional[bool] = None
3813
    ) -> Any:
3814
        """Request a list of overrides
3815
3816
        Arguments:
3817
            filter: Filter term to use for the query
3818
            filter_id: UUID of an existing filter to use for the query
3819
            details: Wether to include full details
3820
            result: Wether to include results using the override
3821
3822
        Returns:
3823
            The response. See :py:meth:`send_command` for details.
3824
        """
3825
        cmd = XmlCommand("get_overrides")
3826
3827
        _add_filter(cmd, filter, filter_id)
3828
3829
        if not details is None:
3830
            cmd.set_attribute("details", _to_bool(details))
3831
3832
        if not result is None:
3833
            cmd.set_attribute("result", _to_bool(result))
3834
3835
        return self._send_xml_command(cmd)
3836
3837
    def get_override(self, override_id: str) -> Any:
3838
        """Request a single override
3839
3840
        Arguments:
3841
            override_id: UUID of an existing override
3842
3843
        Returns:
3844
            The response. See :py:meth:`send_command` for details.
3845
        """
3846
        if not override_id:
3847
            raise RequiredArgument(
3848
                "get_override requires an override_id argument"
3849
            )
3850
3851
        cmd = XmlCommand("get_overrides")
3852
        cmd.set_attribute("override_id", override_id)
3853
3854
        # for single entity always request all details
3855
        cmd.set_attribute("details", "1")
3856
        return self._send_xml_command(cmd)
3857
3858 View Code Duplication
    def get_permissions(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3859
        self,
3860
        *,
3861
        filter: Optional[str] = None,
3862
        filter_id: Optional[str] = None,
3863
        trash: Optional[bool] = None
3864
    ) -> Any:
3865
        """Request a list of permissions
3866
3867
        Arguments:
3868
            filter: Filter term to use for the query
3869
            filter_id: UUID of an existing filter to use for the query
3870
            trash: Whether to get permissions in the trashcan instead
3871
3872
        Returns:
3873
            The response. See :py:meth:`send_command` for details.
3874
        """
3875
        cmd = XmlCommand("get_permissions")
3876
3877
        _add_filter(cmd, filter, filter_id)
3878
3879
        if not trash is None:
3880
            cmd.set_attribute("trash", _to_bool(trash))
3881
3882
        return self._send_xml_command(cmd)
3883
3884
    def get_permission(self, permission_id: str) -> Any:
3885
        """Request a single permission
3886
3887
        Arguments:
3888
            permission_id: UUID of an existing permission
3889
3890
        Returns:
3891
            The response. See :py:meth:`send_command` for details.
3892
        """
3893
        if not permission_id:
3894
            raise RequiredArgument(
3895
                "get_permission requires a permission_id argument"
3896
            )
3897
3898
        cmd = XmlCommand("get_permissions")
3899
        cmd.set_attribute("permission_id", permission_id)
3900
        return self._send_xml_command(cmd)
3901
3902 View Code Duplication
    def get_port_lists(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
3903
        self,
3904
        *,
3905
        filter: Optional[str] = None,
3906
        filter_id: Optional[str] = None,
3907
        details: Optional[bool] = None,
3908
        targets: Optional[bool] = None,
3909
        trash: Optional[bool] = None
3910
    ) -> Any:
3911
        """Request a list of port lists
3912
3913
        Arguments:
3914
            filter: Filter term to use for the query
3915
            filter_id: UUID of an existing filter to use for the query
3916
            details: Whether to include full port list details
3917
            targets: Whether to include targets using this port list
3918
            trash: Whether to get port lists in the trashcan instead
3919
3920
        Returns:
3921
            The response. See :py:meth:`send_command` for details.
3922
        """
3923
        cmd = XmlCommand("get_port_lists")
3924
3925
        _add_filter(cmd, filter, filter_id)
3926
3927
        if not details is None:
3928
            cmd.set_attribute("details", _to_bool(details))
3929
3930
        if not targets is None:
3931
            cmd.set_attribute("targets", _to_bool(targets))
3932
3933
        if not trash is None:
3934
            cmd.set_attribute("trash", _to_bool(trash))
3935
3936
        return self._send_xml_command(cmd)
3937
3938
    def get_port_list(self, port_list_id: str):
3939
        """Request a single port list
3940
3941
        Arguments:
3942
            port_list_id: UUID of an existing port list
3943
3944
        Returns:
3945
            The response. See :py:meth:`send_command` for details.
3946
        """
3947
        if not port_list_id:
3948
            raise RequiredArgument(
3949
                "get_port_list requires a port_list_id argument"
3950
            )
3951
3952
        cmd = XmlCommand("get_port_lists")
3953
        cmd.set_attribute("port_list_id", port_list_id)
3954
3955
        # for single entity always request all details
3956
        cmd.set_attribute("details", "1")
3957
        return self._send_xml_command(cmd)
3958
3959
    def get_preferences(
3960
        self, *, nvt_oid: Optional[str] = None, config_id: Optional[str] = None
3961
    ) -> Any:
3962
        """Request a list of preferences
3963
3964
        When the command includes a config_id attribute, the preference element
3965
        includes the preference name, type and value, and the NVT to which the
3966
        preference applies. Otherwise, the preference element includes just the
3967
        name and value, with the NVT and type built into the name.
3968
3969
        Arguments:
3970
            nvt_oid: OID of nvt
3971
            config_id: UUID of scan config of which to show preference values
3972
3973
        Returns:
3974
            The response. See :py:meth:`send_command` for details.
3975
        """
3976
        cmd = XmlCommand("get_preferences")
3977
3978
        if nvt_oid:
3979
            cmd.set_attribute("nvt_oid", nvt_oid)
3980
3981
        if config_id:
3982
            cmd.set_attribute("config_id", config_id)
3983
3984
        return self._send_xml_command(cmd)
3985
3986
    def get_preference(self, name: str) -> Any:
3987
        """Request a nvt preference
3988
3989
3990
        Arguments:
3991
            name: name of a particular preference
3992
3993
        Returns:
3994
            The response. See :py:meth:`send_command` for details.
3995
        """
3996
        if not name:
3997
            raise RequiredArgument("get_preference requires a name argument")
3998
3999
        cmd = XmlCommand("get_preferences")
4000
4001
        cmd.set_attribute("preference", name)
4002
4003
        return self._send_xml_command(cmd)
4004
4005
    def get_reports(
4006
        self,
4007
        *,
4008
        filter: Optional[str] = None,
4009
        filter_id: Optional[str] = None,
4010
        note_details: Optional[bool] = None,
4011
        override_details: Optional[bool] = None,
4012
        no_details: Optional[bool] = None
4013
    ) -> Any:
4014
        """Request a list of reports
4015
4016
        Arguments:
4017
            filter: Filter term to use for the query
4018
            filter_id: UUID of an existing filter to use for the query
4019
            note_details: If notes are included, whether to include note details
4020
            override_details: If overrides are included, whether to include
4021
                override details
4022
            no_details: Whether to exclude results
4023
4024
        Returns:
4025
            The response. See :py:meth:`send_command` for details.
4026
        """
4027
        cmd = XmlCommand("get_reports")
4028
4029
        if filter:
4030
            cmd.set_attribute("report_filter", filter)
4031
4032
        if filter_id:
4033
            cmd.set_attribute("report_filt_id", filter_id)
4034
4035
        if not note_details is None:
4036
            cmd.set_attribute("note_details", _to_bool(note_details))
4037
4038
        if not override_details is None:
4039
            cmd.set_attribute("override_details", _to_bool(override_details))
4040
4041
        if not no_details is None:
4042
            cmd.set_attribute("details", _to_bool(not no_details))
4043
4044
        cmd.set_attribute("ignore_pagination", "1")
4045
4046
        return self._send_xml_command(cmd)
4047
4048
    def get_report(
4049
        self,
4050
        report_id: str,
4051
        *,
4052
        filter: Optional[str] = None,
4053
        filter_id: Optional[str] = None,
4054
        delta_report_id: Optional[str] = None,
4055
        report_format_id: Optional[str] = None
4056
    ) -> Any:
4057
        """Request a single report
4058
4059
        Arguments:
4060
            report_id: UUID of an existing report
4061
            filter: Filter term to use to filter results in the report
4062
            filter_id: UUID of filter to use to filter results in the report
4063
            delta_report_id: UUID of an existing report to compare report to.
4064
            report_format_id: UUID of report format to use
4065
4066
        Returns:
4067
            The response. See :py:meth:`send_command` for details.
4068
        """
4069
        if not report_id:
4070
            raise RequiredArgument("get_report requires a report_id argument")
4071
4072
        cmd = XmlCommand("get_reports")
4073
        cmd.set_attribute("report_id", report_id)
4074
4075
        _add_filter(cmd, filter, filter_id)
4076
4077
        if delta_report_id:
4078
            cmd.set_attribute("delta_report_id", delta_report_id)
4079
4080
        if report_format_id:
4081
            cmd.set_attribute("format_id", report_format_id)
4082
4083
        return self._send_xml_command(cmd)
4084
4085
    def get_report_formats(
4086
        self,
4087
        *,
4088
        filter: Optional[str] = None,
4089
        filter_id: Optional[str] = None,
4090
        trash: Optional[bool] = None,
4091
        alerts: Optional[bool] = None,
4092
        params: Optional[bool] = None,
4093
        details: Optional[bool] = None
4094
    ) -> Any:
4095
        """Request a list of report formats
4096
4097
        Arguments:
4098
            filter: Filter term to use for the query
4099
            filter_id: UUID of an existing filter to use for the query
4100
            trash: Whether to get the trashcan report formats instead
4101
            alerts: Whether to include alerts that use the report format
4102
            params: Whether to include report format parameters
4103
            details: Include report format file, signature and parameters
4104
4105
        Returns:
4106
            The response. See :py:meth:`send_command` for details.
4107
        """
4108
        cmd = XmlCommand("get_report_formats")
4109
4110
        _add_filter(cmd, filter, filter_id)
4111
4112
        if not details is None:
4113
            cmd.set_attribute("details", _to_bool(details))
4114
4115
        if not alerts is None:
4116
            cmd.set_attribute("alerts", _to_bool(alerts))
4117
4118
        if not params is None:
4119
            cmd.set_attribute("params", _to_bool(params))
4120
4121
        if not trash is None:
4122
            cmd.set_attribute("trash", _to_bool(trash))
4123
4124
        return self._send_xml_command(cmd)
4125
4126
    def get_report_format(self, report_format_id: str) -> Any:
4127
        """Request a single report format
4128
4129
        Arguments:
4130
            report_format_id: UUID of an existing report format
4131
4132
        Returns:
4133
            The response. See :py:meth:`send_command` for details.
4134
        """
4135
        if not report_format_id:
4136
            raise RequiredArgument(
4137
                "get_report_format requires report_format_id argument"
4138
            )
4139
4140
        cmd = XmlCommand("get_report_formats")
4141
        cmd.set_attribute("report_format_id", report_format_id)
4142
4143
        # for single entity always request all details
4144
        cmd.set_attribute("details", "1")
4145
        return self._send_xml_command(cmd)
4146
4147
    def get_results(
4148
        self,
4149
        *,
4150
        filter: Optional[str] = None,
4151
        filter_id: Optional[str] = None,
4152
        task_id: Optional[str] = None,
4153
        note_details: Optional[bool] = None,
4154
        override_details: Optional[bool] = None,
4155
        details: Optional[bool] = None
4156
    ) -> Any:
4157
        """Request a list of results
4158
4159
        Arguments:
4160
            filter: Filter term to use for the query
4161
            filter_id: UUID of an existing filter to use for the query
4162
            task_id: UUID of task for note and override handling
4163
            note_details: If notes are included, whether to include note details
4164
            override_details: If overrides are included, whether to include
4165
                override details
4166
            details: Whether to include additional details of the results
4167
4168
        Returns:
4169
            The response. See :py:meth:`send_command` for details.
4170
        """
4171
        cmd = XmlCommand("get_results")
4172
4173
        _add_filter(cmd, filter, filter_id)
4174
4175
        if task_id:
4176
            cmd.set_attribute("task_id", task_id)
4177
4178
        if not details is None:
4179
            cmd.set_attribute("details", _to_bool(details))
4180
4181
        if not note_details is None:
4182
            cmd.set_attribute("note_details", _to_bool(note_details))
4183
4184
        if not override_details is None:
4185
            cmd.set_attribute("override_details", _to_bool(override_details))
4186
4187
        return self._send_xml_command(cmd)
4188
4189
    def get_result(self, result_id: str) -> Any:
4190
        """Request a single result
4191
4192
        Arguments:
4193
            result_id: UUID of an existing result
4194
4195
        Returns:
4196
            The response. See :py:meth:`send_command` for details.
4197
        """
4198
        if not result_id:
4199
            raise RequiredArgument("get_result requires a result_id argument")
4200
4201
        cmd = XmlCommand("get_results")
4202
        cmd.set_attribute("result_id", result_id)
4203
4204
        # for single entity always request all details
4205
        cmd.set_attribute("details", "1")
4206
        return self._send_xml_command(cmd)
4207
4208 View Code Duplication
    def get_roles(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4209
        self,
4210
        *,
4211
        filter: Optional[str] = None,
4212
        filter_id: Optional[str] = None,
4213
        trash: Optional[bool] = None
4214
    ) -> Any:
4215
        """Request a list of roles
4216
4217
        Arguments:
4218
            filter: Filter term to use for the query
4219
            filter_id: UUID of an existing filter to use for the query
4220
            trash: Whether to get the trashcan roles instead
4221
4222
        Returns:
4223
            The response. See :py:meth:`send_command` for details.
4224
        """
4225
        cmd = XmlCommand("get_roles")
4226
4227
        _add_filter(cmd, filter, filter_id)
4228
4229
        if not trash is None:
4230
            cmd.set_attribute("trash", _to_bool(trash))
4231
4232
        return self._send_xml_command(cmd)
4233
4234
    def get_role(self, role_id: str) -> Any:
4235
        """Request a single role
4236
4237
        Arguments:
4238
            role_id: UUID of an existing role
4239
4240
        Returns:
4241
            The response. See :py:meth:`send_command` for details.
4242
        """
4243
        if not role_id:
4244
            raise RequiredArgument("get_role requires a role_id argument")
4245
4246
        cmd = XmlCommand("get_roles")
4247
        cmd.set_attribute("role_id", role_id)
4248
        return self._send_xml_command(cmd)
4249
4250 View Code Duplication
    def get_scanners(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4251
        self,
4252
        *,
4253
        filter: Optional[str] = None,
4254
        filter_id: Optional[str] = None,
4255
        trash: Optional[bool] = None,
4256
        details: Optional[bool] = None
4257
    ) -> Any:
4258
        """Request a list of scanners
4259
4260
        Arguments:
4261
            filter: Filter term to use for the query
4262
            filter_id: UUID of an existing filter to use for the query
4263
            trash: Whether to get the trashcan scanners instead
4264
            details:  Whether to include extra details like tasks using this
4265
                scanner
4266
4267
        Returns:
4268
            The response. See :py:meth:`send_command` for details.
4269
        """
4270
        cmd = XmlCommand("get_scanners")
4271
4272
        _add_filter(cmd, filter, filter_id)
4273
4274
        if not trash is None:
4275
            cmd.set_attribute("trash", _to_bool(trash))
4276
4277
        if not details is None:
4278
            cmd.set_attribute("details", _to_bool(details))
4279
4280
        return self._send_xml_command(cmd)
4281
4282
    def get_scanner(self, scanner_id: str) -> Any:
4283
        """Request a single scanner
4284
4285
        Arguments:
4286
            scanner_id: UUID of an existing scanner
4287
4288
        Returns:
4289
            The response. See :py:meth:`send_command` for details.
4290
        """
4291
        if not scanner_id:
4292
            raise RequiredArgument("get_scanner requires a scanner_id argument")
4293
4294
        cmd = XmlCommand("get_scanners")
4295
        cmd.set_attribute("scanner_id", scanner_id)
4296
4297
        # for single entity always request all details
4298
        cmd.set_attribute("details", "1")
4299
        return self._send_xml_command(cmd)
4300
4301
    def get_schedules(
4302
        self,
4303
        *,
4304
        filter: Optional[str] = None,
4305
        filter_id: Optional[str] = None,
4306
        trash: Optional[bool] = None,
4307
        tasks: Optional[bool] = None
4308
    ) -> Any:
4309
        """Request a list of schedules
4310
4311
        Arguments:
4312
            filter: Filter term to use for the query
4313
            filter_id: UUID of an existing filter to use for the query
4314
            trash: Whether to get the trashcan schedules instead
4315
            tasks: Whether to include tasks using the schedules
4316
4317
        Returns:
4318
            The response. See :py:meth:`send_command` for details.
4319
        """
4320
        cmd = XmlCommand("get_schedules")
4321
4322
        _add_filter(cmd, filter, filter_id)
4323
4324
        if not trash is None:
4325
            cmd.set_attribute("trash", _to_bool(trash))
4326
4327
        if not tasks is None:
4328
            cmd.set_attribute("tasks", _to_bool(tasks))
4329
4330
        return self._send_xml_command(cmd)
4331
4332
    def get_schedule(self, schedule_id: str) -> Any:
4333
        """Request a single schedule
4334
4335
        Arguments:
4336
            schedule_id: UUID of an existing schedule
4337
4338
        Returns:
4339
            The response. See :py:meth:`send_command` for details.
4340
        """
4341
        if not schedule_id:
4342
            raise RequiredArgument(
4343
                "get_schedule requires a schedule_id argument"
4344
            )
4345
4346
        cmd = XmlCommand("get_schedules")
4347
        cmd.set_attribute("schedule_id", schedule_id)
4348
        return self._send_xml_command(cmd)
4349
4350
    def get_settings(self, *, filter: Optional[str] = None) -> Any:
4351
        """Request a list of user settings
4352
4353
        Arguments:
4354
            filter: Filter term to use for the query
4355
4356
        Returns:
4357
            The response. See :py:meth:`send_command` for details.
4358
        """
4359
        cmd = XmlCommand("get_settings")
4360
4361
        if filter:
4362
            cmd.set_attribute("filter", filter)
4363
4364
        return self._send_xml_command(cmd)
4365
4366
    def get_setting(self, setting_id: str) -> Any:
4367
        """Request a single setting
4368
4369
        Arguments:
4370
            setting_id: UUID of an existing setting
4371
4372
        Returns:
4373
            The response. See :py:meth:`send_command` for details.
4374
        """
4375
        if not setting_id:
4376
            raise RequiredArgument("get_setting requires a setting_id argument")
4377
4378
        cmd = XmlCommand("get_settings")
4379
        cmd.set_attribute("setting_id", setting_id)
4380
        return self._send_xml_command(cmd)
4381
4382
    def get_system_reports(
4383
        self,
4384
        *,
4385
        name: Optional[str] = None,
4386
        duration: Optional[int] = None,
4387
        start_time: Optional[str] = None,
4388
        end_time: Optional[str] = None,
4389
        brief: Optional[bool] = None,
4390
        slave_id: Optional[str] = None
4391
    ) -> Any:
4392
        """Request a list of system reports
4393
4394
        Arguments:
4395
            name: A string describing the required system report
4396
            duration: The number of seconds into the past that the system report
4397
                should include
4398
            start_time: The start of the time interval the system report should
4399
                include in ISO time format
4400
            end_time: The end of the time interval the system report should
4401
                include in ISO time format
4402
            brief: Whether to include the actual system reports
4403
            slave_id: UUID of GMP scanner from which to get the system reports
4404
4405
        Returns:
4406
            The response. See :py:meth:`send_command` for details.
4407
        """
4408
        cmd = XmlCommand("get_system_reports")
4409
4410
        if name:
4411
            cmd.set_attribute("name", name)
4412
4413
        if not duration is None:
4414
            if not isinstance(duration, numbers.Integral):
4415
                raise InvalidArgument("duration needs to be an integer number")
4416
4417
            cmd.set_attribute("duration", str(duration))
4418
4419
        if start_time:
4420
            cmd.set_attribute("start_time", str(start_time))
4421
4422
        if end_time:
4423
            cmd.set_attribute("end_time", str(end_time))
4424
4425
        if not brief is None:
4426
            cmd.set_attribute("brief", _to_bool(brief))
4427
4428
        if slave_id:
4429
            cmd.set_attribute("slave_id", slave_id)
4430
4431
        return self._send_xml_command(cmd)
4432
4433
    def get_tags(
4434
        self,
4435
        *,
4436
        filter: Optional[str] = None,
4437
        filter_id: Optional[str] = None,
4438
        trash: Optional[bool] = None,
4439
        names_only: Optional[bool] = None
4440
    ) -> Any:
4441
        """Request a list of tags
4442
4443
        Arguments:
4444
            filter: Filter term to use for the query
4445
            filter_id: UUID of an existing filter to use for the query
4446
            trash: Whether to get tags from the trashcan instead
4447
            names_only: Whether to get only distinct tag names
4448
4449
        Returns:
4450
            The response. See :py:meth:`send_command` for details.
4451
        """
4452
        cmd = XmlCommand("get_tags")
4453
4454
        _add_filter(cmd, filter, filter_id)
4455
4456
        if not trash is None:
4457
            cmd.set_attribute("trash", _to_bool(trash))
4458
4459
        if not names_only is None:
4460
            cmd.set_attribute("names_only", _to_bool(names_only))
4461
4462
        return self._send_xml_command(cmd)
4463
4464
    def get_tag(self, tag_id: str) -> Any:
4465
        """Request a single tag
4466
4467
        Arguments:
4468
            tag_id: UUID of an existing tag
4469
4470
        Returns:
4471
            The response. See :py:meth:`send_command` for details.
4472
        """
4473
        if not tag_id:
4474
            raise RequiredArgument("get_tag requires a tag_id argument")
4475
4476
        cmd = XmlCommand("get_tags")
4477
        cmd.set_attribute("tag_id", tag_id)
4478
        return self._send_xml_command(cmd)
4479
4480
    def get_targets(
4481
        self,
4482
        *,
4483
        filter: Optional[str] = None,
4484
        filter_id: Optional[str] = None,
4485
        trash: Optional[bool] = None,
4486
        tasks: Optional[bool] = None
4487
    ) -> Any:
4488
        """Request a list of targets
4489
4490
        Arguments:
4491
            filter: Filter term to use for the query
4492
            filter_id: UUID of an existing filter to use for the query
4493
            trash: Whether to get the trashcan targets instead
4494
            tasks: Whether to include list of tasks that use the target
4495
4496
        Returns:
4497
            The response. See :py:meth:`send_command` for details.
4498
        """
4499
        cmd = XmlCommand("get_targets")
4500
4501
        _add_filter(cmd, filter, filter_id)
4502
4503
        if not trash is None:
4504
            cmd.set_attribute("trash", _to_bool(trash))
4505
4506
        if not tasks is None:
4507
            cmd.set_attribute("tasks", _to_bool(tasks))
4508
4509
        return self._send_xml_command(cmd)
4510
4511
    def get_target(self, target_id: str) -> Any:
4512
        """Request a single target
4513
4514
        Arguments:
4515
            target_id: UUID of an existing target
4516
4517
        Returns:
4518
            The response. See :py:meth:`send_command` for details.
4519
        """
4520
        if not target_id:
4521
            raise RequiredArgument("get_target requires a target_id argument")
4522
4523
        cmd = XmlCommand("get_targets")
4524
        cmd.set_attribute("target_id", target_id)
4525
        return self._send_xml_command(cmd)
4526
4527 View Code Duplication
    def get_tasks(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
4528
        self,
4529
        *,
4530
        filter: Optional[str] = None,
4531
        filter_id: Optional[str] = None,
4532
        trash: Optional[bool] = None,
4533
        details: Optional[bool] = None,
4534
        schedules_only: Optional[bool] = None
4535
    ) -> Any:
4536
        """Request a list of tasks
4537
4538
        Arguments:
4539
            filter: Filter term to use for the query
4540
            filter_id: UUID of an existing filter to use for the query
4541
            trash: Whether to get the trashcan tasks instead
4542
            details: Whether to include full task details
4543
            schedules_only: Whether to only include id, name and schedule
4544
                details
4545
4546
        Returns:
4547
            The response. See :py:meth:`send_command` for details.
4548
        """
4549
        cmd = XmlCommand("get_tasks")
4550
4551
        _add_filter(cmd, filter, filter_id)
4552
4553
        if not trash is None:
4554
            cmd.set_attribute("trash", _to_bool(trash))
4555
4556
        if not details is None:
4557
            cmd.set_attribute("details", _to_bool(details))
4558
4559
        if not schedules_only is None:
4560
            cmd.set_attribute("schedules_only", _to_bool(schedules_only))
4561
4562
        return self._send_xml_command(cmd)
4563
4564
    def get_task(self, task_id: str) -> Any:
4565
        """Request a single task
4566
4567
        Arguments:
4568
            task_id: UUID of an existing task
4569
4570
        Returns:
4571
            The response. See :py:meth:`send_command` for details.
4572
        """
4573
        if not task_id:
4574
            raise RequiredArgument("get_task requires task_id argument")
4575
4576
        cmd = XmlCommand("get_tasks")
4577
        cmd.set_attribute("task_id", task_id)
4578
4579
        # for single entity always request all details
4580
        cmd.set_attribute("details", "1")
4581
        return self._send_xml_command(cmd)
4582
4583
    def get_users(
4584
        self, *, filter: Optional[str] = None, filter_id: Optional[str] = None
4585
    ) -> Any:
4586
        """Request a list of users
4587
4588
        Arguments:
4589
            filter: Filter term to use for the query
4590
            filter_id: UUID of an existing filter to use for the query
4591
4592
        Returns:
4593
            The response. See :py:meth:`send_command` for details.
4594
        """
4595
        cmd = XmlCommand("get_users")
4596
4597
        _add_filter(cmd, filter, filter_id)
4598
4599
        return self._send_xml_command(cmd)
4600
4601
    def get_user(self, user_id: str) -> Any:
4602
        """Request a single user
4603
4604
        Arguments:
4605
            user_id: UUID of an existing user
4606
4607
        Returns:
4608
            The response. See :py:meth:`send_command` for details.
4609
        """
4610
        if not user_id:
4611
            raise RequiredArgument("get_user requires a user_id argument")
4612
4613
        cmd = XmlCommand("get_users")
4614
        cmd.set_attribute("user_id", user_id)
4615
        return self._send_xml_command(cmd)
4616
4617
    def get_version(self) -> Any:
4618
        """Get the Greenbone Manager Protocol version used by the remote gvmd
4619
4620
        Returns:
4621
            The response. See :py:meth:`send_command` for details.
4622
        """
4623
        return self._send_xml_command(XmlCommand("get_version"))
4624
4625
    def help(
4626
        self, *, format: Optional[str] = None, help_type: Optional[str] = ""
4627
    ) -> Any:
4628
        """Get the help text
4629
4630
        Arguments:
4631
            format: One of "html", "rnc", "text" or "xml
4632
            help_type: One of "brief" or "". Default ""
4633
4634
        Returns:
4635
            The response. See :py:meth:`send_command` for details.
4636
        """
4637
        cmd = XmlCommand("help")
4638
4639
        if help_type not in ("", "brief"):
4640
            raise InvalidArgument(
4641
                'help_type argument must be an empty string or "brief"'
4642
            )
4643
4644
        cmd.set_attribute("type", help_type)
4645
4646
        if format:
4647
            if not format.lower() in ("html", "rnc", "text", "xml"):
4648
                raise InvalidArgument(
4649
                    "help format Argument must be one of html, rnc, text or "
4650
                    "xml"
4651
                )
4652
4653
            cmd.set_attribute("format", format)
4654
4655
        return self._send_xml_command(cmd)
4656
4657
    def modify_agent(
4658
        self,
4659
        agent_id: str,
4660
        *,
4661
        name: Optional[str] = None,
4662
        comment: Optional[str] = None
4663
    ) -> Any:
4664
        """Modifies an existing agent
4665
4666
        Arguments:
4667
            agent_id: UUID of the agent to be modified.
4668
            name: Name of the new credential
4669
            comment: Comment for the credential
4670
4671
        Returns:
4672
            The response. See :py:meth:`send_command` for details.
4673
        """
4674
        if not agent_id:
4675
            raise RequiredArgument("modify_agent requires agent_id argument")
4676
4677
        cmd = XmlCommand("modify_agent")
4678
        cmd.set_attribute("agent_id", str(agent_id))
4679
4680
        if name:
4681
            cmd.add_element("name", name)
4682
4683
        if comment:
4684
            cmd.add_element("comment", comment)
4685
4686
        return self._send_xml_command(cmd)
4687
4688
    def modify_alert(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (19/15).
Loading history...
4689
        self,
4690
        alert_id: str,
4691
        *,
4692
        name: Optional[str] = None,
4693
        comment: Optional[str] = None,
4694
        filter_id: Optional[str] = None,
4695
        event: Optional[AlertEvent] = None,
4696
        event_data: Optional[dict] = None,
4697
        condition: Optional[AlertCondition] = None,
4698
        condition_data: Optional[dict] = None,
4699
        method: Optional[AlertMethod] = None,
4700
        method_data: Optional[dict] = None
4701
    ) -> Any:
4702
        """Modifies an existing alert.
4703
4704
        Arguments:
4705
            alert_id: UUID of the alert to be modified.
4706
            name: Name of the Alert.
4707
            condition: The condition that must be satisfied for the alert to
4708
                occur. If the event is either 'Updated SecInfo
4709
                arrived' or 'New SecInfo arrived', condition must be 'Always'.
4710
                Otherwise, condition can also be on of 'Severity at least',
4711
                'Filter count changed' or 'Filter count at least'.
4712
            condition_data: Data that defines the condition
4713
            event: The event that must happen for the alert to occur, one of
4714
                'Task run status changed', 'Updated SecInfo arrived' or
4715
                'New SecInfo arrived'
4716
            event_data: Data that defines the event
4717
            method: The method by which the user is alerted, one of 'SCP',
4718
                'Send', 'SMB', 'SNMP', 'Syslog' or 'Email';
4719
                if the event is neither 'Updated SecInfo arrived' nor
4720
                'New SecInfo arrived', method can also be one of 'Start Task',
4721
                'HTTP Get', 'Sourcefire Connector' or 'verinice Connector'.
4722
            method_data: Data that defines the method
4723
            filter_id: Filter to apply when executing alert
4724
            comment: Comment for the alert
4725
4726
        Returns:
4727
            The response. See :py:meth:`send_command` for details.
4728
        """
4729
4730
        if not alert_id:
4731
            raise RequiredArgument("modify_alert requires an alert_id argument")
4732
4733
        cmd = XmlCommand("modify_alert")
4734
        cmd.set_attribute("alert_id", str(alert_id))
4735
4736
        if name:
4737
            cmd.add_element("name", name)
4738
4739
        if comment:
4740
            cmd.add_element("comment", comment)
4741
4742
        if filter_id:
4743
            cmd.add_element("filter", attrs={"id": filter_id})
4744
4745
        if condition:
4746
            if not isinstance(condition, AlertCondition):
4747
                raise InvalidArgument(
4748
                    function="modify_alert", argument="condition"
4749
                )
4750
4751
            conditions = cmd.add_element("condition", condition.value)
4752
4753
            if not condition_data is None:
4754
                for key, value in condition_data.items():
4755
                    _data = conditions.add_element("data", value)
4756
                    _data.add_element("name", key)
4757
4758
        if method:
4759
            if not isinstance(method, AlertMethod):
4760
                raise InvalidArgument(
4761
                    function="modify_alert", argument="method"
4762
                )
4763
4764
            methods = cmd.add_element("method", method.value)
4765
4766
            if not method_data is None:
4767
                for key, value in method_data.items():
4768
                    _data = methods.add_element("data", value)
4769
                    _data.add_element("name", key)
4770
4771
        if event:
4772
            if not isinstance(event, AlertEvent):
4773
                raise InvalidArgument(function="modify_alert", argument="event")
4774
4775
            _check_event(event, condition, method)
4776
4777
            events = cmd.add_element("event", event.value)
4778
4779
            if not event_data is None:
4780
                for key, value in event_data.items():
4781
                    _data = events.add_element("data", value)
4782
                    _data.add_element("name", key)
4783
4784
        return self._send_xml_command(cmd)
4785
4786
    def modify_asset(self, asset_id: str, comment: Optional[str] = "") -> Any:
4787
        """Modifies an existing asset.
4788
4789
        Arguments:
4790
            asset_id: UUID of the asset to be modified.
4791
            comment: Comment for the asset.
4792
4793
        Returns:
4794
            The response. See :py:meth:`send_command` for details.
4795
        """
4796
        if not asset_id:
4797
            raise RequiredArgument("modify_asset requires an asset_id argument")
4798
4799
        cmd = XmlCommand("modify_asset")
4800
        cmd.set_attribute("asset_id", asset_id)
4801
        cmd.add_element("comment", comment)
4802
4803
        return self._send_xml_command(cmd)
4804
4805
    def modify_auth(self, group_name: str, auth_conf_settings: dict) -> Any:
4806
        """Modifies an existing auth.
4807
4808
        Arguments:
4809
            group_name: Name of the group to be modified.
4810
            auth_conf_settings: The new auth config.
4811
4812
        Returns:
4813
            The response. See :py:meth:`send_command` for details.
4814
        """
4815
        if not group_name:
4816
            raise RequiredArgument("modify_auth requires a group_name argument")
4817
        if not auth_conf_settings:
4818
            raise RequiredArgument(
4819
                "modify_auth requires an " "auth_conf_settings argument"
4820
            )
4821
        cmd = XmlCommand("modify_auth")
4822
        _xmlgroup = cmd.add_element("group", attrs={"name": str(group_name)})
4823
4824
        for key, value in auth_conf_settings.items():
4825
            _xmlauthconf = _xmlgroup.add_element("auth_conf_setting")
4826
            _xmlauthconf.add_element("key", key)
4827
            _xmlauthconf.add_element("value", value)
4828
4829
        return self._send_xml_command(cmd)
4830
4831
    def modify_config_set_nvt_preference(
4832
        self,
4833
        config_id: str,
4834
        name: str,
4835
        nvt_oid: str,
4836
        *,
4837
        value: Optional[str] = None
4838
    ) -> Any:
4839
        """Modifies the nvt preferences of an existing scan config.
4840
4841
        Arguments:
4842
            config_id: UUID of scan config to modify.
4843
            name: Name for preference to change.
4844
            nvt_oid: OID of the NVT associated with preference to modify
4845
            value: New value for the preference. None to delete the preference
4846
                and to use the default instead.
4847
        """
4848
        if not config_id:
4849
            raise RequiredArgument(
4850
                "modify_config_set_nvt_preference requires config_id argument"
4851
            )
4852
4853
        if not nvt_oid:
4854
            raise RequiredArgument(
4855
                "modify_config_set_nvt_preference requires a nvt_oid argument"
4856
            )
4857
4858
        if not name:
4859
            raise RequiredArgument(
4860
                "modify_config_set_nvt_preference requires a name argument"
4861
            )
4862
4863
        cmd = XmlCommand("modify_config")
4864
        cmd.set_attribute("config_id", str(config_id))
4865
4866
        _xmlpref = cmd.add_element("preference")
4867
4868
        _xmlpref.add_element("nvt", attrs={"oid": nvt_oid})
4869
        _xmlpref.add_element("name", name)
4870
4871
        if value:
4872
            _xmlpref.add_element("value", _to_base64(value))
4873
4874
        return self._send_xml_command(cmd)
4875
4876
    def modify_config_set_comment(
4877
        self, config_id: str, comment: Optional[str] = ""
4878
    ) -> Any:
4879
        """Modifies the comment of an existing scan config
4880
4881
        Arguments:
4882
            config_id: UUID of scan config to modify.
4883
            comment: Comment to set on a config. Default: ''
4884
        """
4885
        if not config_id:
4886
            raise RequiredArgument(
4887
                "modify_config_set_comment requires a config_id argument"
4888
            )
4889
4890
        cmd = XmlCommand("modify_config")
4891
        cmd.set_attribute("config_id", str(config_id))
4892
4893
        cmd.add_element("comment", comment)
4894
4895
        return self._send_xml_command(cmd)
4896
4897
    def modify_config_set_scanner_preference(
4898
        self, config_id: str, name: str, *, value: Optional[str] = None
4899
    ) -> Any:
4900
        """Modifies the scanner preferences of an existing scan config
4901
4902
        Arguments:
4903
            config_id: UUID of scan config to modify.
4904
            name: Name of the scanner preference to change
4905
            value: New value for the preference. None to delete the preference
4906
                and to use the default instead.
4907
4908
        """
4909
        if not config_id:
4910
            raise RequiredArgument(
4911
                "modify_config_set_scanner_preference requires a config_id "
4912
                "argument"
4913
            )
4914
4915
        if not name:
4916
            raise RequiredArgument(
4917
                "modify_config_set_scanner_preference requires a name argument"
4918
            )
4919
4920
        cmd = XmlCommand("modify_config")
4921
        cmd.set_attribute("config_id", str(config_id))
4922
4923
        _xmlpref = cmd.add_element("preference")
4924
4925
        _xmlpref.add_element("name", name)
4926
4927
        if value:
4928
            _xmlpref.add_element("value", _to_base64(value))
4929
4930
        return self._send_xml_command(cmd)
4931
4932
    def modify_config_set_nvt_selection(
4933
        self, config_id: str, family: str, nvt_oids: List[str]
4934
    ) -> Any:
4935
        """Modifies the selected nvts of an existing scan config
4936
4937
        The manager updates the given family in the config to include only the
4938
        given NVTs.
4939
4940
        Arguments:
4941
            config_id: UUID of scan config to modify.
4942
            family: Name of the NVT family to include NVTs from
4943
            nvt_oids: List of NVTs to select for the family.
4944
        """
4945
        if not config_id:
4946
            raise RequiredArgument(
4947
                "modify_config_set_nvt_selection requires a config_id "
4948
                "argument"
4949
            )
4950
4951
        if not family:
4952
            raise RequiredArgument(
4953
                "modify_config_set_nvt_selection requires a family argument"
4954
            )
4955
4956
        if not _is_list_like(nvt_oids):
4957
            raise InvalidArgument(
4958
                "modify_config_set_nvt_selection requires an iterable as "
4959
                "nvt_oids argument"
4960
            )
4961
4962
        cmd = XmlCommand("modify_config")
4963
        cmd.set_attribute("config_id", str(config_id))
4964
4965
        _xmlnvtsel = cmd.add_element("nvt_selection")
4966
        _xmlnvtsel.add_element("family", family)
4967
4968
        for nvt in nvt_oids:
4969
            _xmlnvtsel.add_element("nvt", attrs={"oid": nvt})
4970
4971
        return self._send_xml_command(cmd)
4972
4973
    def modify_config_set_family_selection(
4974
        self,
4975
        config_id: str,
4976
        families: List[str],
4977
        *,
4978
        auto_add_new_families: Optional[bool] = True,
4979
        auto_add_new_nvts: Optional[bool] = True
4980
    ) -> Any:
4981
        """
4982
        Selected the NVTs of a scan config at a family level.
4983
4984
        Arguments:
4985
            config_id: UUID of scan config to modify.
4986
            families: List of NVT family names to select.
4987
            auto_add_new_families: Whether new families should be added to the
4988
                scan config automatically. Default: True.
4989
            auto_add_new_nvts: Whether new NVTs in the selected families should
4990
                be added to the scan config automatically. Default: True.
4991
        """
4992
        if not config_id:
4993
            raise RequiredArgument(
4994
                "modify_config_set_family_selection requires a config_id "
4995
                "argument"
4996
            )
4997
4998
        if not _is_list_like(families):
4999
            raise InvalidArgument(
5000
                "modify_config_set_family_selection requires a list as "
5001
                "families argument"
5002
            )
5003
5004
        cmd = XmlCommand("modify_config")
5005
        cmd.set_attribute("config_id", str(config_id))
5006
5007
        _xmlfamsel = cmd.add_element("family_selection")
5008
        _xmlfamsel.add_element("growing", _to_bool(auto_add_new_families))
5009
5010
        for family in families:
5011
            _xmlfamily = _xmlfamsel.add_element("family")
5012
            _xmlfamily.add_element("name", family)
5013
            _xmlfamily.add_element("all", "1")
5014
            _xmlfamily.add_element("growing", _to_bool(auto_add_new_nvts))
5015
5016
        return self._send_xml_command(cmd)
5017
5018
    def modify_config(
5019
        self, config_id: str, selection: Optional[str] = None, **kwargs
5020
    ) -> Any:
5021
        """Modifies an existing scan config.
5022
5023
        DEPRECATED. Please use *modify_config_set_* methods instead.
5024
5025
        modify_config has four modes to operate depending on the selection.
5026
5027
        Arguments:
5028
            config_id: UUID of scan config to modify.
5029
            selection: one of 'scan_pref', 'nvt_pref', 'nvt_selection' or
5030
                'family_selection'
5031
            name: New name for preference.
5032
            value: New value for preference.
5033
            nvt_oids: List of NVTs associated with preference to modify.
5034
            family: Name of family to modify.
5035
5036
        Returns:
5037
            The response. See :py:meth:`send_command` for details.
5038
        """
5039
        if not config_id:
5040
            raise RequiredArgument("modify_config required config_id argument")
5041
5042
        if selection is None:
5043
            deprecation(
5044
                "Using modify_config to update the comment of a scan config is"
5045
                "deprecated. Please use modify_config_set_comment instead."
5046
            )
5047
            return self.modify_config_set_comment(
5048
                config_id, kwargs.get("comment")
5049
            )
5050
5051
        if selection not in (
5052
            "nvt_pref",
5053
            "scan_pref",
5054
            "family_selection",
5055
            "nvt_selection",
5056
        ):
5057
            raise InvalidArgument(
5058
                "selection must be one of nvt_pref, "
5059
                "scan_pref, family_selection or "
5060
                "nvt_selection"
5061
            )
5062
5063
        if selection == "nvt_pref":
5064
            deprecation(
5065
                "Using modify_config to update a nvt preference of a scan "
5066
                "config is deprecated. Please use "
5067
                "modify_config_set_nvt_preference instead."
5068
            )
5069
            return self.modify_config_set_nvt_preference(config_id, **kwargs)
5070
5071
        if selection == "scan_pref":
5072
            deprecation(
5073
                "Using modify_config to update a scanner preference of a "
5074
                "scan config is deprecated. Please use "
5075
                "modify_config_set_scanner_preference instead."
5076
            )
5077
            return self.modify_config_set_scanner_preference(
5078
                config_id, **kwargs
5079
            )
5080
5081
        if selection == "nvt_selection":
5082
            deprecation(
5083
                "Using modify_config to update a nvt selection of a "
5084
                "scan config is deprecated. Please use "
5085
                "modify_config_set_nvt_selection instead."
5086
            )
5087
            return self.modify_config_set_nvt_selection(config_id, **kwargs)
5088
5089
        deprecation(
5090
            "Using modify_config to update a family selection of a "
5091
            "scan config is deprecated. Please use "
5092
            "modify_config_set_family_selection instead."
5093
        )
5094
        return self.modify_config_set_family_selection(config_id, **kwargs)
5095
5096
    def modify_credential(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (18/15).
Loading history...
5097
        self,
5098
        credential_id: str,
5099
        *,
5100
        name: Optional[str] = None,
5101
        comment: Optional[str] = None,
5102
        allow_insecure: Optional[bool] = None,
5103
        certificate: Optional[str] = None,
5104
        key_phrase: Optional[str] = None,
5105
        private_key: Optional[str] = None,
5106
        login: Optional[str] = None,
5107
        password: Optional[str] = None,
5108
        auth_algorithm: Optional[SnmpAuthAlgorithm] = None,
5109
        community: Optional[str] = None,
5110
        privacy_algorithm: Optional[SnmpPrivacyAlgorithm] = None,
5111
        privacy_password: Optional[str] = None
5112
    ) -> Any:
5113
        """Modifies an existing credential.
5114
5115
        Arguments:
5116
            credential_id: UUID of the credential
5117
            name: Name of the credential
5118
            comment: Comment for the credential
5119
            allow_insecure: Whether to allow insecure use of the credential
5120
            certificate: Certificate for the credential
5121
            key_phrase: Key passphrase for the private key
5122
            private_key: Private key to use for login
5123
            login: Username for the credential
5124
            password: Password for the credential
5125
            auth_algorithm: The SNMP auth algorithm.
5126
            community: The SNMP community
5127
            privacy_algorithm: The SNMP privacy algorithm.
5128
            privacy_password: The SNMP privacy password
5129
5130
        Returns:
5131
            The response. See :py:meth:`send_command` for details.
5132
        """
5133
        if not credential_id:
5134
            raise RequiredArgument(
5135
                "modify_credential requires " "a credential_id attribute"
5136
            )
5137
5138
        cmd = XmlCommand("modify_credential")
5139
        cmd.set_attribute("credential_id", credential_id)
5140
5141
        if comment:
5142
            cmd.add_element("comment", comment)
5143
5144
        if name:
5145
            cmd.add_element("name", name)
5146
5147
        if allow_insecure is not None:
5148
            cmd.add_element("allow_insecure", _to_bool(allow_insecure))
5149
5150
        if certificate:
5151
            cmd.add_element("certificate", certificate)
5152
5153
        if key_phrase is not None or private_key:
5154
            if key_phrase is not None and not private_key:
5155
                raise RequiredArgument(
5156
                    "modify_credential requires "
5157
                    "key_phrase and private_key arguments"
5158
                )
5159
5160
            _xmlkey = cmd.add_element("key")
5161
            _xmlkey.add_element("private", private_key)
5162
5163
            if key_phrase is not None:
5164
                _xmlkey.add_element("phrase", key_phrase)
5165
5166
        if login:
5167
            cmd.add_element("login", login)
5168
5169
        if password:
5170
            cmd.add_element("password", password)
5171
5172
        if auth_algorithm is not None:
5173
            if not isinstance(auth_algorithm, SnmpAuthAlgorithm):
5174
                raise InvalidArgument(
5175
                    function="modify_credential", argument="auth_algorithm"
5176
                )
5177
            cmd.add_element("auth_algorithm", auth_algorithm.value)
5178
5179
        if community:
5180
            cmd.add_element("community", community)
5181
5182
        if privacy_algorithm is not None:
5183
            if not isinstance(privacy_algorithm, SnmpPrivacyAlgorithm):
5184
                raise InvalidArgument(
5185
                    function="modify_credential", argument="privacy_algorithm"
5186
                )
5187
5188
            _xmlprivacy = cmd.add_element("privacy")
5189
            _xmlprivacy.add_element("algorithm", privacy_algorithm.value)
5190
5191
            if privacy_password is not None:
5192
                _xmlprivacy.add_element("password", privacy_password)
5193
5194
        return self._send_xml_command(cmd)
5195
5196 View Code Duplication
    def modify_filter(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5197
        self,
5198
        filter_id: str,
5199
        *,
5200
        comment: Optional[str] = None,
5201
        name: Optional[str] = None,
5202
        term: Optional[str] = None,
5203
        filter_type: Optional[FilterType] = None
5204
    ) -> Any:
5205
        """Modifies an existing filter.
5206
5207
        Arguments:
5208
            filter_id: UUID of the filter to be modified
5209
            comment: Comment on filter.
5210
            name: Name of filter.
5211
            term: Filter term.
5212
            filter_type: Filter type the filter applies to.
5213
5214
        Returns:
5215
            The response. See :py:meth:`send_command` for details.
5216
        """
5217
        if not filter_id:
5218
            raise RequiredArgument(
5219
                "modify_filter requires a filter_id " "attribute"
5220
            )
5221
5222
        cmd = XmlCommand("modify_filter")
5223
        cmd.set_attribute("filter_id", filter_id)
5224
5225
        if comment:
5226
            cmd.add_element("comment", comment)
5227
5228
        if name:
5229
            cmd.add_element("name", name)
5230
5231
        if term:
5232
            cmd.add_element("term", term)
5233
5234
        if filter_type:
5235
            if not isinstance(filter_type, self._filter_type):
5236
                raise InvalidArgument(
5237
                    "modify_filter requires filter_type to be a FilterType "
5238
                    "instance. was {}".format(filter_type),
5239
                    function="modify_filter",
5240
                    argument="filter_type",
5241
                )
5242
            cmd.add_element("type", filter_type.value)
5243
5244
        return self._send_xml_command(cmd)
5245
5246 View Code Duplication
    def modify_group(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5247
        self,
5248
        group_id: str,
5249
        *,
5250
        comment: Optional[str] = None,
5251
        name: Optional[str] = None,
5252
        users: Optional[List[str]] = None
5253
    ) -> Any:
5254
        """Modifies an existing group.
5255
5256
        Arguments:
5257
            group_id: UUID of group to modify.
5258
            comment: Comment on group.
5259
            name: Name of group.
5260
            users: List of user names to be in the group
5261
5262
        Returns:
5263
            The response. See :py:meth:`send_command` for details.
5264
        """
5265
        if not group_id:
5266
            raise RequiredArgument("modify_group requires a group_id argument")
5267
5268
        cmd = XmlCommand("modify_group")
5269
        cmd.set_attribute("group_id", group_id)
5270
5271
        if comment:
5272
            cmd.add_element("comment", comment)
5273
5274
        if name:
5275
            cmd.add_element("name", name)
5276
5277
        if users:
5278
            cmd.add_element("users", _to_comma_list(users))
5279
5280
        return self._send_xml_command(cmd)
5281
5282 View Code Duplication
    def modify_note(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5283
        self,
5284
        note_id: str,
5285
        text: str,
5286
        *,
5287
        seconds_active: Optional[int] = None,
5288
        hosts: Optional[List[str]] = None,
5289
        port: Optional[int] = None,
5290
        result_id: Optional[str] = None,
5291
        severity: Optional[Severity] = None,
5292
        task_id: Optional[str] = None,
5293
        threat: Optional[SeverityLevel] = None
5294
    ) -> Any:
5295
        """Modifies an existing note.
5296
5297
        Arguments:
5298
            note_id: UUID of note to modify.
5299
            text: The text of the note.
5300
            seconds_active: Seconds note will be active. -1 on always, 0 off.
5301
            hosts: A list of hosts addresses
5302
            port: Port to which note applies.
5303
            result_id: Result to which note applies.
5304
            severity: Severity to which note applies.
5305
            task_id: Task to which note applies.
5306
            threat: Threat level to which note applies. Will be converted to
5307
                severity.
5308
5309
        Returns:
5310
            The response. See :py:meth:`send_command` for details.
5311
        """
5312
        if not note_id:
5313
            raise RequiredArgument("modify_note requires a note_id attribute")
5314
5315
        if not text:
5316
            raise RequiredArgument("modify_note requires a text element")
5317
5318
        cmd = XmlCommand("modify_note")
5319
        cmd.set_attribute("note_id", note_id)
5320
        cmd.add_element("text", text)
5321
5322
        if not seconds_active is None:
5323
            cmd.add_element("active", str(seconds_active))
5324
5325
        if hosts:
5326
            cmd.add_element("hosts", _to_comma_list(hosts))
5327
5328
        if port:
5329
            cmd.add_element("port", str(port))
5330
5331
        if result_id:
5332
            cmd.add_element("result", attrs={"id": result_id})
5333
5334
        if severity:
5335
            cmd.add_element("severity", str(severity))
5336
5337
        if task_id:
5338
            cmd.add_element("task", attrs={"id": task_id})
5339
5340
        if threat is not None:
5341
5342
            if not isinstance(threat, SeverityLevel):
5343
                raise InvalidArgument(
5344
                    "modify_note threat argument {} is invalid. threat must "
5345
                    "be a SeverityLevel instance".format(threat),
5346
                    function="modify_note",
5347
                    argument="threat",
5348
                )
5349
5350
            cmd.add_element("threat", threat.value)
5351
5352
        return self._send_xml_command(cmd)
5353
5354 View Code Duplication
    def modify_override(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5355
        self,
5356
        override_id: str,
5357
        text: str,
5358
        *,
5359
        seconds_active: Optional[int] = None,
5360
        hosts: Optional[List[str]] = None,
5361
        port: Optional[int] = None,
5362
        result_id: Optional[str] = None,
5363
        severity: Optional[Severity] = None,
5364
        new_severity: Optional[Severity] = None,
5365
        task_id: Optional[str] = None,
5366
        threat: Optional[SeverityLevel] = None,
5367
        new_threat: Optional[SeverityLevel] = None
5368
    ) -> Any:
5369
        """Modifies an existing override.
5370
5371
        Arguments:
5372
            override_id: UUID of override to modify.
5373
            text: The text of the override.
5374
            seconds_active: Seconds override will be active. -1 on always,
5375
                0 off.
5376
            hosts: A list of host addresses
5377
            port: Port to which override applies.
5378
            result_id: Result to which override applies.
5379
            severity: Severity to which override applies.
5380
            new_severity: New severity score for result.
5381
            task_id: Task to which override applies.
5382
            threat: Threat level to which override applies.
5383
                Will be converted to severity.
5384
            new_threat: New threat level for results. Will be converted to
5385
                new_severity.
5386
5387
        Returns:
5388
            The response. See :py:meth:`send_command` for details.
5389
        """
5390
        if not override_id:
5391
            raise RequiredArgument(
5392
                "modify_override requires a override_id argument"
5393
            )
5394
        if not text:
5395
            raise RequiredArgument("modify_override requires a text argument")
5396
5397
        cmd = XmlCommand("modify_override")
5398
        cmd.set_attribute("override_id", override_id)
5399
        cmd.add_element("text", text)
5400
5401
        if not seconds_active is None:
5402
            cmd.add_element("active", str(seconds_active))
5403
5404
        if hosts:
5405
            cmd.add_element("hosts", _to_comma_list(hosts))
5406
5407
        if port:
5408
            cmd.add_element("port", str(port))
5409
5410
        if result_id:
5411
            cmd.add_element("result", attrs={"id": result_id})
5412
5413
        if severity:
5414
            cmd.add_element("severity", str(severity))
5415
5416
        if new_severity:
5417
            cmd.add_element("new_severity", str(new_severity))
5418
5419
        if task_id:
5420
            cmd.add_element("task", attrs={"id": task_id})
5421
5422
        if threat is not None:
5423
            if not isinstance(threat, SeverityLevel):
5424
                raise InvalidArgument(
5425
                    "modify_override threat argument {} is invalid. threat "
5426
                    "must be a SeverityLevel instance".format(threat),
5427
                    function="modify_override",
5428
                    argument="threat",
5429
                )
5430
            cmd.add_element("threat", threat.value)
5431
5432
        if new_threat is not None:
5433
            if not isinstance(new_threat, SeverityLevel):
5434
                raise InvalidArgument(
5435
                    "modify_override new_threat argument {} is invalid. "
5436
                    "new_threat must be a SeverityLevel instance".format(
5437
                        new_threat
5438
                    ),
5439
                    function="modify_override",
5440
                    argument="new_threat",
5441
                )
5442
5443
            cmd.add_element("new_threat", new_threat.value)
5444
5445
        return self._send_xml_command(cmd)
5446
5447
    def modify_permission(
5448
        self,
5449
        permission_id: str,
5450
        *,
5451
        comment: Optional[str] = None,
5452
        name: Optional[str] = None,
5453
        resource_id: Optional[str] = None,
5454
        resource_type: Optional[EntityType] = None,
5455
        subject_id: Optional[str] = None,
5456
        subject_type: Optional[PermissionSubjectType] = None
5457
    ) -> Any:
5458
        """Modifies an existing permission.
5459
5460
        Arguments:
5461
            permission_id: UUID of permission to be modified.
5462
            comment: The comment on the permission.
5463
            name: Permission name, currently the name of a command.
5464
            subject_id: UUID of subject to whom the permission is granted
5465
            subject_type: Type of the subject user, group or role
5466
            resource_id: UUID of entity to which the permission applies
5467
            resource_type: Type of the resource. For Super permissions user,
5468
                group or role
5469
5470
        Returns:
5471
            The response. See :py:meth:`send_command` for details.
5472
        """
5473
        if not permission_id:
5474
            raise RequiredArgument(
5475
                "modify_permission requires " "a permission_id element"
5476
            )
5477
5478
        cmd = XmlCommand("modify_permission")
5479
        cmd.set_attribute("permission_id", permission_id)
5480
5481
        if comment:
5482
            cmd.add_element("comment", comment)
5483
5484
        if name:
5485
            cmd.add_element("name", name)
5486
5487 View Code Duplication
        if resource_id or resource_type:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5488
            if not resource_id:
5489
                raise RequiredArgument(
5490
                    "modify_permission requires resource_id for resource_type"
5491
                )
5492
5493
            if not resource_type:
5494
                raise RequiredArgument(
5495
                    "modify_permission requires resource_type for resource_id"
5496
                )
5497
5498
            if not isinstance(resource_type, self._entity_type):
5499
                raise InvalidArgument(
5500
                    function="modify_permission", argument="resource_type"
5501
                )
5502
5503
            _xmlresource = cmd.add_element(
5504
                "resource", attrs={"id": resource_id}
5505
            )
5506
            _xmlresource.add_element("type", resource_type.value)
5507
5508
        if subject_id or subject_type:
5509
            if not subject_id:
5510
                raise RequiredArgument(
5511
                    "modify_permission requires a subject_id for subject_type"
5512
                )
5513
5514
            if not isinstance(subject_type, PermissionSubjectType):
5515
                raise InvalidArgument(
5516
                    "modify_permission requires subject_type to be a "
5517
                    "PermissionSubjectType instance",
5518
                    function="modify_permission",
5519
                    argument="subject_type",
5520
                )
5521
5522
            _xmlsubject = cmd.add_element("subject", attrs={"id": subject_id})
5523
            _xmlsubject.add_element("type", subject_type.value)
5524
5525
        return self._send_xml_command(cmd)
5526
5527
    def modify_port_list(
5528
        self,
5529
        port_list_id: str,
5530
        *,
5531
        comment: Optional[str] = None,
5532
        name: Optional[str] = None
5533
    ) -> Any:
5534
        """Modifies an existing port list.
5535
5536
        Arguments:
5537
            port_list_id: UUID of port list to modify.
5538
            name: Name of port list.
5539
            comment: Comment on port list.
5540
5541
        Returns:
5542
            The response. See :py:meth:`send_command` for details.
5543
        """
5544
        if not port_list_id:
5545
            raise RequiredArgument(
5546
                "modify_port_list requires " "a port_list_id attribute"
5547
            )
5548
        cmd = XmlCommand("modify_port_list")
5549
        cmd.set_attribute("port_list_id", port_list_id)
5550
5551
        if comment:
5552
            cmd.add_element("comment", comment)
5553
5554
        if name:
5555
            cmd.add_element("name", name)
5556
5557
        return self._send_xml_command(cmd)
5558
5559
    def modify_report_format(
5560
        self,
5561
        report_format_id: str,
5562
        *,
5563
        active: Optional[bool] = None,
5564
        name: Optional[str] = None,
5565
        summary: Optional[str] = None,
5566
        param_name: Optional[str] = None,
5567
        param_value: Optional[str] = None
5568
    ) -> Any:
5569
        """Modifies an existing report format.
5570
5571
        Arguments:
5572
            report_format_id: UUID of report format to modify.
5573
            active: Whether the report format is active.
5574
            name: The name of the report format.
5575
            summary: A summary of the report format.
5576
            param_name: The name of the param.
5577
            param_value: The value of the param.
5578
5579
        Returns:
5580
            The response. See :py:meth:`send_command` for details.
5581
        """
5582
        if not report_format_id:
5583
            raise RequiredArgument(
5584
                "modify_report requires " "a report_format_id attribute"
5585
            )
5586
5587
        cmd = XmlCommand("modify_report_format")
5588
        cmd.set_attribute("report_format_id", report_format_id)
5589
5590
        if active is not None:
5591
            cmd.add_element("active", _to_bool(active))
5592
5593
        if name:
5594
            cmd.add_element("name", name)
5595
5596
        if summary:
5597
            cmd.add_element("summary", summary)
5598
5599
        if param_name:
5600
            _xmlparam = cmd.add_element("param")
5601
            _xmlparam.add_element("name", param_name)
5602
5603
            if param_value is not None:
5604
                _xmlparam.add_element("value", param_value)
5605
5606
        return self._send_xml_command(cmd)
5607
5608 View Code Duplication
    def modify_role(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5609
        self,
5610
        role_id: str,
5611
        *,
5612
        comment: Optional[str] = None,
5613
        name: Optional[str] = None,
5614
        users: Optional[List[str]] = None
5615
    ) -> Any:
5616
        """Modifies an existing role.
5617
5618
        Arguments:
5619
            role_id: UUID of role to modify.
5620
            comment: Name of role.
5621
            name: Comment on role.
5622
            users: List of user names.
5623
5624
        Returns:
5625
            The response. See :py:meth:`send_command` for details.
5626
        """
5627
        if not role_id:
5628
            raise RequiredArgument("modify_role requires a role_id argument")
5629
5630
        cmd = XmlCommand("modify_role")
5631
        cmd.set_attribute("role_id", role_id)
5632
5633
        if comment:
5634
            cmd.add_element("comment", comment)
5635
5636
        if name:
5637
            cmd.add_element("name", name)
5638
5639
        if users:
5640
            cmd.add_element("users", _to_comma_list(users))
5641
5642
        return self._send_xml_command(cmd)
5643
5644
    def modify_scanner(
5645
        self,
5646
        scanner_id: str,
5647
        *,
5648
        scanner_type: Optional[ScannerType] = None,
5649
        host: Optional[str] = None,
5650
        port: Optional[int] = None,
5651
        comment: Optional[str] = None,
5652
        name: Optional[str] = None,
5653
        ca_pub: Optional[str] = None,
5654
        credential_id: Optional[str] = None
5655
    ) -> Any:
5656
        """Modifies an existing scanner.
5657
5658
        Arguments:
5659
            scanner_id: UUID of scanner to modify.
5660
            scanner_type: New type of the Scanner.
5661
            host: Host of the scanner.
5662
            port: Port of the scanner.
5663
            comment: Comment on scanner.
5664
            name: Name of scanner.
5665
            ca_pub: Certificate of CA to verify scanner's certificate.
5666
            credential_id: UUID of the client certificate credential for the
5667
                Scanner.
5668
5669
        Returns:
5670
            The response. See :py:meth:`send_command` for details.
5671
        """
5672
        if not scanner_id:
5673
            raise RequiredArgument(
5674
                "modify_scanner requires a scanner_id argument"
5675
            )
5676
5677
        cmd = XmlCommand("modify_scanner")
5678
        cmd.set_attribute("scanner_id", scanner_id)
5679
5680
        if scanner_type is not None:
5681
            if not isinstance(scanner_type, ScannerType):
5682
                raise InvalidArgument(
5683
                    function="modify_scanner", argument="scanner_type"
5684
                )
5685
5686
            cmd.add_element("type", scanner_type.value)
5687
5688
        if host:
5689
            cmd.add_element("host", host)
5690
5691
        if port:
5692
            cmd.add_element("port", str(port))
5693
5694
        if comment:
5695
            cmd.add_element("comment", comment)
5696
5697
        if name:
5698
            cmd.add_element("name", name)
5699
5700
        if ca_pub:
5701
            cmd.add_element("ca_pub", ca_pub)
5702
5703
        if credential_id:
5704
            cmd.add_element("credential", attrs={"id": str(credential_id)})
5705
5706
        return self._send_xml_command(cmd)
5707
5708 View Code Duplication
    def modify_schedule(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
Comprehensibility introduced by
This function exceeds the maximum number of variables (19/15).
Loading history...
5709
        self,
5710
        schedule_id: str,
5711
        *,
5712
        comment: Optional[str] = None,
5713
        name: Optional[str] = None,
5714
        first_time_minute: Optional[int] = None,
5715
        first_time_hour: Optional[int] = None,
5716
        first_time_day_of_month: Optional[int] = None,
5717
        first_time_month: Optional[int] = None,
5718
        first_time_year: Optional[int] = None,
5719
        duration: Optional[int] = None,
5720
        duration_unit: Optional[TimeUnit] = None,
5721
        period: Optional[int] = None,
5722
        period_unit: Optional[TimeUnit] = None,
5723
        timezone: Optional[str] = None
5724
    ) -> Any:
5725
        """Modifies an existing schedule.
5726
5727
        Arguments:
5728
            schedule_id: UUID of schedule to modify.
5729
            name: Name of the schedule
5730
            comment: Comment for the schedule
5731
            first_time_minute: First time minute the schedule will run. Must be
5732
                an integer >= 0.
5733
            first_time_hour: First time hour the schedule will run. Must be an
5734
                integer >= 0.
5735
            first_time_day_of_month: First time day of month the schedule will
5736
                run. Must be an integer > 0 <= 31.
5737
            first_time_month: First time month the schedule will run. Must be an
5738
                integer >= 1 <= 12.
5739
            first_time_year: First time year the schedule will run
5740
            duration: How long the Manager will run the scheduled task for until
5741
                it gets paused if not finished yet.
5742
            duration_unit: Unit of the duration. One of second, minute, hour,
5743
                day, week, month, year, decade. Required if duration is set.
5744
            period: How often the Manager will repeat the scheduled task. Must
5745
                be an integer > 0.
5746
            period_unit: Unit of the period. One of second, minute, hour, day,
5747
                week, month, year, decade. Required if period is set.
5748
            timezone: The timezone the schedule will follow
5749
5750
        Returns:
5751
            The response. See :py:meth:`send_command` for details.
5752
        """
5753
        if not schedule_id:
5754
            raise RequiredArgument(
5755
                "modify_schedule requires a schedule_id" "argument"
5756
            )
5757
5758
        cmd = XmlCommand("modify_schedule")
5759
        cmd.set_attribute("schedule_id", schedule_id)
5760
5761
        if comment:
5762
            cmd.add_element("comment", comment)
5763
5764
        if name:
5765
            cmd.add_element("name", name)
5766
5767
        if (
5768
            first_time_minute is not None
5769
            or first_time_hour is not None
5770
            or first_time_day_of_month is not None
5771
            or first_time_month is not None
5772
            or first_time_year is not None
5773
        ):
5774
5775
            if first_time_minute is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
5776
                raise RequiredArgument(
5777
                    "Setting first_time requires first_time_minute argument"
5778
                )
5779
            elif (
5780
                not isinstance(first_time_minute, numbers.Integral)
5781
                or first_time_minute < 0
5782
            ):
5783
                raise InvalidArgument(
5784
                    "first_time_minute argument of modify_schedule needs to be "
5785
                    "an integer greater or equal 0"
5786
                )
5787
5788
            if first_time_hour is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
5789
                raise RequiredArgument(
5790
                    "Setting first_time requires first_time_hour argument"
5791
                )
5792
            elif (
5793
                not isinstance(first_time_hour, numbers.Integral)
5794
                or first_time_hour < 0
5795
            ):
5796
                raise InvalidArgument(
5797
                    "first_time_hour argument of modify_schedule needs to be "
5798
                    "an integer greater or equal 0"
5799
                )
5800
5801
            if first_time_day_of_month is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
5802
                raise RequiredArgument(
5803
                    "Setting first_time requires first_time_day_of_month "
5804
                    "argument"
5805
                )
5806
            elif (
5807
                not isinstance(first_time_day_of_month, numbers.Integral)
5808
                or first_time_day_of_month < 1
5809
                or first_time_day_of_month > 31
5810
            ):
5811
                raise InvalidArgument(
5812
                    "first_time_day_of_month argument of modify_schedule needs "
5813
                    "to be an integer between 1 and 31"
5814
                )
5815
5816
            if first_time_month is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
5817
                raise RequiredArgument(
5818
                    "Setting first_time requires first_time_month argument"
5819
                )
5820
            elif (
5821
                not isinstance(first_time_month, numbers.Integral)
5822
                or first_time_month < 1
5823
                or first_time_month > 12
5824
            ):
5825
                raise InvalidArgument(
5826
                    "first_time_month argument of modify_schedule needs "
5827
                    "to be an integer between 1 and 12"
5828
                )
5829
5830
            if first_time_year is None:
0 ignored issues
show
Unused Code introduced by
Unnecessary "elif" after "raise"
Loading history...
5831
                raise RequiredArgument(
5832
                    "Setting first_time requires first_time_year argument"
5833
                )
5834
            elif (
5835
                not isinstance(first_time_year, numbers.Integral)
5836
                or first_time_year < 1970
5837
            ):
5838
                raise InvalidArgument(
5839
                    "first_time_year argument of create_schedule needs "
5840
                    "to be an integer greater or equal 1970"
5841
                )
5842
5843
            _xmlftime = cmd.add_element("first_time")
5844
            _xmlftime.add_element("minute", str(first_time_minute))
5845
            _xmlftime.add_element("hour", str(first_time_hour))
5846
            _xmlftime.add_element("day_of_month", str(first_time_day_of_month))
5847
            _xmlftime.add_element("month", str(first_time_month))
5848
            _xmlftime.add_element("year", str(first_time_year))
5849
5850
        if duration is not None:
5851
            if not duration_unit:
5852
                raise RequiredArgument(
5853
                    "Setting duration requires duration_unit argument"
5854
                )
5855
5856
            if not isinstance(duration_unit, TimeUnit):
5857
                raise InvalidArgument(
5858
                    function="modify_schedule", argument="duration_unit"
5859
                )
5860
5861
            if not isinstance(duration, numbers.Integral) or duration < 1:
5862
                raise InvalidArgument(
5863
                    "duration argument must be an integer greater than 0"
5864
                )
5865
5866
            _xmlduration = cmd.add_element("duration", str(duration))
5867
            _xmlduration.add_element("unit", duration_unit.value)
5868
5869
        if period is not None:
5870
            if not period_unit:
5871
                raise RequiredArgument(
5872
                    "Setting period requires period_unit argument"
5873
                )
5874
5875
            if not isinstance(period_unit, TimeUnit):
5876
                raise InvalidArgument(
5877
                    function="modify_schedule", argument="period_unit"
5878
                )
5879
5880
            if not isinstance(period, numbers.Integral) or period < 1:
5881
                raise InvalidArgument(
5882
                    "period argument must be an integer greater than 0"
5883
                )
5884
5885
            _xmlperiod = cmd.add_element("period", str(period))
5886
            _xmlperiod.add_element("unit", period_unit.value)
5887
5888
        if timezone:
5889
            cmd.add_element("timezone", timezone)
5890
5891
        return self._send_xml_command(cmd)
5892
5893
    def modify_setting(
5894
        self,
5895
        setting_id: Optional[str] = None,
5896
        name: Optional[str] = None,
5897
        value: Optional[str] = None,
5898
    ) -> Any:
5899
        """Modifies an existing setting.
5900
5901
        Arguments:
5902
            setting_id: UUID of the setting to be changed.
5903
            name: The name of the setting. Either setting_id or name must be
5904
                passed.
5905
            value: The value of the setting.
5906
5907
        Returns:
5908
            The response. See :py:meth:`send_command` for details.
5909
        """
5910
        if not setting_id and not name:
5911
            raise RequiredArgument(
5912
                "modify_setting requires a setting_id or name argument"
5913
            )
5914
5915
        if value is None:
5916
            raise RequiredArgument("modify_setting requires a value argument")
5917
5918
        cmd = XmlCommand("modify_setting")
5919
5920
        if setting_id:
5921
            cmd.set_attribute("setting_id", setting_id)
5922
        else:
5923
            cmd.add_element("name", name)
5924
5925
        cmd.add_element("value", _to_base64(value))
5926
5927
        return self._send_xml_command(cmd)
5928
5929
    def modify_tag(
5930
        self,
5931
        tag_id: str,
5932
        *,
5933
        comment: Optional[str] = None,
5934
        name: Optional[str] = None,
5935
        value: Optional[str] = None,
5936
        active: Optional[bool] = None,
5937
        resource_id: Optional[str] = None,
5938
        resource_type: Optional[EntityType] = None
5939
    ) -> Any:
5940
        """Modifies an existing tag.
5941
5942
        Arguments:
5943
            tag_id: UUID of the tag.
5944
            comment: Comment to add to the tag.
5945
            name: Name of the tag.
5946
            value: Value of the tag.
5947
            active: Whether the tag is active.
5948
            resource_id: ID of the resource to which to attach the tag.
5949
                Required if resource_type is set.
5950
            resource_type: Type of the resource to which to attach the tag.
5951
                Required if resource_id is set.
5952
5953
        Returns:
5954
            The response. See :py:meth:`send_command` for details.
5955
        """
5956
        if not tag_id:
5957
            raise RequiredArgument("modify_tag requires a tag_id element")
5958
5959
        cmd = XmlCommand("modify_tag")
5960
        cmd.set_attribute("tag_id", str(tag_id))
5961
5962
        if comment:
5963
            cmd.add_element("comment", comment)
5964
5965
        if name:
5966
            cmd.add_element("name", name)
5967
5968
        if value:
5969
            cmd.add_element("value", value)
5970
5971
        if active is not None:
5972
            cmd.add_element("active", _to_bool(active))
5973
5974 View Code Duplication
        if resource_id or resource_type:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5975
            if not resource_id:
5976
                raise RequiredArgument(
5977
                    "modify_tag requires resource_id argument when "
5978
                    "resource_type is set"
5979
                )
5980
5981
            if not resource_type:
5982
                raise RequiredArgument(
5983
                    "modify_tag requires resource_type argument when "
5984
                    "resource_id is set"
5985
                )
5986
5987
            if not isinstance(resource_type, self._entity_type):
5988
                raise InvalidArgument(
5989
                    function="modify_tag", argument="resource_type"
5990
                )
5991
5992
            _xmlresource = cmd.add_element(
5993
                "resource", attrs={"id": resource_id}
5994
            )
5995
            _xmlresource.add_element("type", resource_type.value)
5996
5997
        return self._send_xml_command(cmd)
5998
5999
    def modify_target(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (18/15).
Loading history...
6000
        self,
6001
        target_id: str,
6002
        *,
6003
        name: Optional[str] = None,
6004
        comment: Optional[str] = None,
6005
        hosts: Optional[List[str]] = None,
6006
        exclude_hosts: Optional[List[str]] = None,
6007
        ssh_credential_id: Optional[str] = None,
6008
        ssh_credential_port: Optional[bool] = None,
6009
        smb_credential_id: Optional[str] = None,
6010
        esxi_credential_id: Optional[str] = None,
6011
        snmp_credential_id: Optional[str] = None,
6012
        alive_test: Optional[AliveTest] = None,
6013
        reverse_lookup_only: Optional[bool] = None,
6014
        reverse_lookup_unify: Optional[bool] = None,
6015
        port_list_id: Optional[str] = None
6016
    ) -> Any:
6017
        """Modifies an existing target.
6018
6019
        Arguments:
6020
            target_id: ID of target to modify.
6021
            comment: Comment on target.
6022
            name: Name of target.
6023
            hosts: List of target hosts.
6024
            exclude_hosts: A list of hosts to exclude.
6025
            ssh_credential_id: UUID of SSH credential to use on target.
6026
            ssh_credential_port: The port to use for ssh credential
6027
            smb_credential_id: UUID of SMB credential to use on target.
6028
            esxi_credential_id: UUID of ESXi credential to use on target.
6029
            snmp_credential_id: UUID of SNMP credential to use on target.
6030
            port_list_id: UUID of port list describing ports to scan.
6031
            alive_test: Which alive tests to use.
6032
            reverse_lookup_only: Whether to scan only hosts that have names.
6033
            reverse_lookup_unify: Whether to scan only one IP when multiple IPs
6034
                have the same name.
6035
6036
        Returns:
6037
            The response. See :py:meth:`send_command` for details.
6038
        """
6039
        if not target_id:
6040
            raise RequiredArgument(
6041
                "modify_target requires a " "target_id argument"
6042
            )
6043
6044
        cmd = XmlCommand("modify_target")
6045
        cmd.set_attribute("target_id", target_id)
6046
6047
        if comment:
6048
            cmd.add_element("comment", comment)
6049
6050
        if name:
6051
            cmd.add_element("name", name)
6052
6053
        if hosts:
6054
            cmd.add_element("hosts", _to_comma_list(hosts))
6055
6056
        if exclude_hosts:
6057
            cmd.add_element("exclude_hosts", _to_comma_list(exclude_hosts))
6058
6059
        if alive_test:
6060
            if not isinstance(alive_test, AliveTest):
6061
                raise InvalidArgument(
6062
                    function="modify_target", argument="alive_test"
6063
                )
6064
            cmd.add_element("alive_tests", alive_test.value)
6065
6066
        if ssh_credential_id:
6067
            _xmlssh = cmd.add_element(
6068
                "ssh_credential", attrs={"id": ssh_credential_id}
6069
            )
6070
6071
            if ssh_credential_port:
6072
                _xmlssh.add_element("port", str(ssh_credential_port))
6073
6074
        if smb_credential_id:
6075
            cmd.add_element("smb_credential", attrs={"id": smb_credential_id})
6076
6077
        if esxi_credential_id:
6078
            cmd.add_element("esxi_credential", attrs={"id": esxi_credential_id})
6079
6080
        if snmp_credential_id:
6081
            cmd.add_element("snmp_credential", attrs={"id": snmp_credential_id})
6082
6083
        if not reverse_lookup_only is None:
6084
            cmd.add_element(
6085
                "reverse_lookup_only", _to_bool(reverse_lookup_only)
6086
            )
6087
6088
        if not reverse_lookup_unify is None:
6089
            cmd.add_element(
6090
                "reverse_lookup_unify", _to_bool(reverse_lookup_unify)
6091
            )
6092
6093
        if port_list_id:
6094
            cmd.add_element("port_list", attrs={"id": port_list_id})
6095
6096
        return self._send_xml_command(cmd)
6097
6098
    def modify_task(
0 ignored issues
show
Comprehensibility introduced by
This function exceeds the maximum number of variables (21/15).
Loading history...
6099
        self,
6100
        task_id: str,
6101
        *,
6102
        name: Optional[str] = None,
6103
        config_id: Optional[str] = None,
6104
        target_id: Optional[str] = None,
6105
        scanner_id: Optional[str] = None,
6106
        alterable: Optional[bool] = None,
6107
        hosts_ordering: Optional[HostsOrdering] = None,
6108
        schedule_id: Optional[str] = None,
6109
        schedule_periods: Optional[int] = None,
6110
        comment: Optional[str] = None,
6111
        alert_ids: Optional[List[str]] = None,
6112
        observers: Optional[List[str]] = None,
6113
        preferences: Optional[dict] = None
6114
    ) -> Any:
6115
        """Modifies an existing task.
6116
6117
        Arguments:
6118
            task_id: UUID of task to modify.
6119
            name: The name of the task.
6120
            config_id: UUID of scan config to use by the task
6121
            target_id: UUID of target to be scanned
6122
            scanner_id: UUID of scanner to use for scanning the target
6123
            comment: The comment on the task.
6124
            alert_ids: List of UUIDs for alerts to be applied to the task
6125
            hosts_ordering: The order hosts are scanned in
6126
            schedule_id: UUID of a schedule when the task should be run.
6127
            schedule_periods: A limit to the number of times the task will be
6128
                scheduled, or 0 for no limit.
6129
            observers: List of names or ids of users which should be allowed to
6130
                observe this task
6131
            preferences: Name/Value pairs of scanner preferences.
6132
6133
        Returns:
6134
            The response. See :py:meth:`send_command` for details.
6135
        """
6136
        if not task_id:
6137
            raise RequiredArgument("modify_task requires a task_id argument")
6138
6139
        cmd = XmlCommand("modify_task")
6140
        cmd.set_attribute("task_id", task_id)
6141
6142
        if name:
6143
            cmd.add_element("name", name)
6144
6145
        if comment:
6146
            cmd.add_element("comment", comment)
6147
6148
        if config_id:
6149
            cmd.add_element("config", attrs={"id": config_id})
6150
6151
        if target_id:
6152
            cmd.add_element("target", attrs={"id": target_id})
6153
6154
        if not alterable is None:
6155
            cmd.add_element("alterable", _to_bool(alterable))
6156
6157
        if hosts_ordering:
6158
            if not isinstance(hosts_ordering, HostsOrdering):
6159
                raise InvalidArgument(
6160
                    function="modify_tasks", argument="hosts_ordering"
6161
                )
6162
            cmd.add_element("hosts_ordering", hosts_ordering.value)
6163
6164
        if scanner_id:
6165
            cmd.add_element("scanner", attrs={"id": scanner_id})
6166
6167
        if schedule_id:
6168
            cmd.add_element("schedule", attrs={"id": schedule_id})
6169
6170 View Code Duplication
        if schedule_periods is not None:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
6171
            if (
6172
                not isinstance(schedule_periods, numbers.Integral)
6173
                or schedule_periods < 0
6174
            ):
6175
                raise InvalidArgument(
6176
                    "schedule_periods must be an integer greater or equal "
6177
                    "than 0"
6178
                )
6179
            cmd.add_element("schedule_periods", str(schedule_periods))
6180
6181
        if alert_ids is not None:
6182
            if not _is_list_like(alert_ids):
6183
                raise InvalidArgument("alert_ids argument must be a list")
6184
6185
            for alert in alert_ids:
6186
                cmd.add_element("alert", attrs={"id": str(alert)})
6187
6188
        if observers is not None:
6189
            if not _is_list_like(observers):
6190
                raise InvalidArgument("obeservers argument must be a list")
6191
6192
            cmd.add_element("observers", _to_comma_list(observers))
6193
6194
        if preferences is not None:
6195
            if not isinstance(preferences, collections.abc.Mapping):
6196
                raise InvalidArgument('preferences argument must be a dict')
6197
6198
            _xmlprefs = cmd.add_element("preferences")
6199
            for pref_name, pref_value in preferences.items():
6200
                _xmlpref = _xmlprefs.add_element("preference")
6201
                _xmlpref.add_element("scanner_name", pref_name)
6202
                _xmlpref.add_element("value", str(pref_value))
6203
6204
        return self._send_xml_command(cmd)
6205
6206
    def modify_user(
6207
        self,
6208
        user_id: str = None,
6209
        name: str = None,
6210
        *,
6211
        new_name: Optional[str] = None,
6212
        password: Optional[str] = None,
6213
        role_ids: Optional[List[str]] = None,
6214
        hosts: Optional[List[str]] = None,
6215
        hosts_allow: Optional[bool] = False,
6216
        ifaces: Optional[List[str]] = None,
6217
        ifaces_allow: Optional[bool] = False
6218
    ) -> Any:
6219
        """Modifies an existing user.
6220
6221
        Arguments:
6222
            user_id: UUID of the user to be modified. Overrides name element
6223
                argument.
6224
            name: The name of the user to be modified. Either user_id or name
6225
                must be passed.
6226
            new_name: The new name for the user.
6227
            password: The password for the user.
6228
            roles_id: List of roles UUIDs for the user.
6229
            hosts: User access rules: List of hosts.
6230
            hosts_allow: If True, allow only listed, otherwise forbid listed.
6231
            ifaces: User access rules: List of ifaces.
6232
            ifaces_allow: If True, allow only listed, otherwise forbid listed.
6233
6234
        Returns:
6235
            The response. See :py:meth:`send_command` for details.
6236
        """
6237
        if not user_id and not name:
6238
            raise RequiredArgument(
6239
                "modify_user requires an user_id or name argument"
6240
            )
6241
6242
        cmd = XmlCommand("modify_user")
6243
6244
        if user_id:
6245
            cmd.set_attribute("user_id", user_id)
6246
        else:
6247
            cmd.add_element("name", name)
6248
6249
        if new_name:
6250
            cmd.add_element("new_name", new_name)
6251
6252
        if password:
6253
            cmd.add_element("password", password)
6254
6255
        if role_ids:
6256
            for role in role_ids:
6257
                cmd.add_element("role", attrs={"id": role})
6258
6259
        if hosts:
6260
            cmd.add_element(
6261
                "hosts",
6262
                _to_comma_list(hosts),
6263
                attrs={"allow": _to_bool(hosts_allow)},
6264
            )
6265
6266
        if ifaces:
6267
            cmd.add_element(
6268
                "ifaces",
6269
                _to_comma_list(ifaces),
6270
                attrs={"allow": _to_bool(ifaces_allow)},
6271
            )
6272
6273
        return self._send_xml_command(cmd)
6274
6275
    def move_task(self, task_id: str, *, slave_id: Optional[str] = None) -> Any:
6276
        """Move an existing task to another GMP slave scanner or the master
6277
6278
        Arguments:
6279
            task_id: UUID of the task to be moved
6280
            slave_id: UUID of slave to reassign the task to, empty for master.
6281
6282
        Returns:
6283
            The response. See :py:meth:`send_command` for details.
6284
        """
6285
        if not task_id:
6286
            raise InvalidArgument("move_task requires an task_id argument")
6287
6288
        cmd = XmlCommand("move_task")
6289
        cmd.set_attribute("task_id", task_id)
6290
6291
        if not slave_id is None:
6292
            cmd.set_attribute("slave_id", slave_id)
6293
6294
        return self._send_xml_command(cmd)
6295
6296
    def restore(self, entity_id: str) -> Any:
6297
        """Restore an entity from the trashcan
6298
6299
        Arguments:
6300
            entity_id: ID of the entity to be restored from the trashcan
6301
6302
        Returns:
6303
            The response. See :py:meth:`send_command` for details.
6304
        """
6305
        if not entity_id:
6306
            raise InvalidArgument("restore requires an entity_id argument")
6307
6308
        cmd = XmlCommand("restore")
6309
        cmd.set_attribute("id", entity_id)
6310
6311
        return self._send_xml_command(cmd)
6312
6313
    def resume_task(self, task_id: str) -> Any:
6314
        """Resume an existing stopped task
6315
6316
        Arguments:
6317
            task_id: UUID of the task to be resumed
6318
6319
        Returns:
6320
            The response. See :py:meth:`send_command` for details.
6321
        """
6322
        if not task_id:
6323
            raise InvalidArgument("resume_task requires an task_id argument")
6324
6325
        cmd = XmlCommand("resume_task")
6326
        cmd.set_attribute("task_id", task_id)
6327
6328
        return self._send_xml_command(cmd)
6329
6330
    def start_task(self, task_id: str) -> Any:
6331
        """Start an existing task
6332
6333
        Arguments:
6334
            task_id: UUID of the task to be started
6335
6336
        Returns:
6337
            The response. See :py:meth:`send_command` for details.
6338
        """
6339
        if not task_id:
6340
            raise InvalidArgument("start_task requires an task_id argument")
6341
6342
        cmd = XmlCommand("start_task")
6343
        cmd.set_attribute("task_id", task_id)
6344
6345
        return self._send_xml_command(cmd)
6346
6347
    def stop_task(self, task_id: str) -> Any:
6348
        """Stop an existing running task
6349
6350
        Arguments:
6351
            task_id: UUID of the task to be stopped
6352
6353
        Returns:
6354
            The response. See :py:meth:`send_command` for details.
6355
        """
6356
        if not task_id:
6357
            raise InvalidArgument("stop_task requires an task_id argument")
6358
6359
        cmd = XmlCommand("stop_task")
6360
        cmd.set_attribute("task_id", task_id)
6361
6362
        return self._send_xml_command(cmd)
6363
6364
    def sync_cert(self) -> Any:
6365
        """Request a synchronization with the CERT feed service
6366
6367
        Returns:
6368
            The response. See :py:meth:`send_command` for details.
6369
        """
6370
        return self._send_xml_command(XmlCommand("sync_cert"))
6371
6372
    def sync_config(self) -> Any:
6373
        """Request an OSP config synchronization with scanner
6374
6375
        Returns:
6376
            The response. See :py:meth:`send_command` for details.
6377
        """
6378
        return self._send_xml_command(XmlCommand("sync_config"))
6379
6380
    def sync_feed(self) -> Any:
6381
        """Request a synchronization with the NVT feed service
6382
6383
        Returns:
6384
            The response. See :py:meth:`send_command` for details.
6385
        """
6386
        return self._send_xml_command(XmlCommand("sync_feed"))
6387
6388
    def sync_scap(self) -> Any:
6389
        """Request a synchronization with the SCAP feed service
6390
6391
        Returns:
6392
            The response. See :py:meth:`send_command` for details.
6393
        """
6394
        return self._send_xml_command(XmlCommand("sync_scap"))
6395
6396
    def test_alert(self, alert_id: str) -> Any:
6397
        """Run an alert
6398
6399
        Invoke a test run of an alert
6400
6401
        Arguments:
6402
            alert_id: UUID of the alert to be tested
6403
6404
        Returns:
6405
            The response. See :py:meth:`send_command` for details.
6406
        """
6407
        if not alert_id:
6408
            raise InvalidArgument("test_alert requires an alert_id argument")
6409
6410
        cmd = XmlCommand("test_alert")
6411
        cmd.set_attribute("alert_id", alert_id)
6412
6413
        return self._send_xml_command(cmd)
6414
6415
    def trigger_alert(
6416
        self,
6417
        alert_id: str,
6418
        report_id: str,
6419
        *,
6420
        filter: Optional[str] = None,
6421
        filter_id: Optional[str] = None,
6422
        report_format_id: Optional[str] = None,
6423
        delta_report_id: Optional[str] = None
6424
    ) -> Any:
6425
        """Run an alert by ignoring its event and conditions
6426
6427
        The alert is triggered to run immediately with the provided filtered
6428
        report by ignoring the even and condition settings.
6429
6430
        Arguments:
6431
            alert_id: UUID of the alert to be run
6432
            report_id: UUID of the report to be provided to the alert
6433
            filter: Filter term to use to filter results in the report
6434
            filter_id: UUID of filter to use to filter results in the report
6435
            report_format_id: UUID of report format to use
6436
            delta_report_id: UUID of an existing report to compare report to.
6437
6438
        Returns:
6439
            The response. See :py:meth:`send_command` for details.
6440
        """
6441
        if not alert_id:
6442
            raise RequiredArgument("run_alert requires a alert_id argument")
6443
6444
        if not report_id:
6445
            raise RequiredArgument("run_alert requires a report_id argument")
6446
6447
        cmd = XmlCommand("get_reports")
6448
        cmd.set_attribute("report_id", report_id)
6449
        cmd.set_attribute("alert_id", alert_id)
6450
6451
        if filter:
6452
            cmd.set_attribute("filter", filter)
6453
6454
        if filter_id:
6455
            cmd.set_attribute("filt_id", filter_id)
6456
6457
        if report_format_id:
6458
            cmd.set_attribute("format_id", report_format_id)
6459
6460
        if delta_report_id:
6461
            cmd.set_attribute("delta_report_id", delta_report_id)
6462
6463
        return self._send_xml_command(cmd)
6464
6465
    def verify_agent(self, agent_id: str) -> Any:
6466
        """Verify an existing agent
6467
6468
        Verifies the trust level of an existing agent. It will be checked
6469
        whether signature of the agent currently matches the agent. This
6470
        includes the agent installer file. It is *not* verified if the agent
6471
        works as expected by the user.
6472
6473
        Arguments:
6474
            agent_id: UUID of the agent to be verified
6475
6476
        Returns:
6477
            The response. See :py:meth:`send_command` for details.
6478
        """
6479
        if not agent_id:
6480
            raise InvalidArgument("verify_agent requires an agent_id argument")
6481
6482
        cmd = XmlCommand("verify_agent")
6483
        cmd.set_attribute("agent_id", agent_id)
6484
6485
        return self._send_xml_command(cmd)
6486
6487
    def verify_report_format(self, report_format_id: str) -> Any:
6488
        """Verify an existing report format
6489
6490
        Verifies the trust level of an existing report format. It will be
6491
        checked whether the signature of the report format currently matches the
6492
        report format. This includes the script and files used to generate
6493
        reports of this format. It is *not* verified if the report format works
6494
        as expected by the user.
6495
6496
        Arguments:
6497
            report_format_id: UUID of the report format to be verified
6498
6499
        Returns:
6500
            The response. See :py:meth:`send_command` for details.
6501
        """
6502
        if not report_format_id:
6503
            raise InvalidArgument(
6504
                "verify_report_format requires a report_format_id argument"
6505
            )
6506
6507
        cmd = XmlCommand("verify_report_format")
6508
        cmd.set_attribute("report_format_id", report_format_id)
6509
6510
        return self._send_xml_command(cmd)
6511
6512
    def verify_scanner(self, scanner_id: str) -> Any:
6513
        """Verify an existing scanner
6514
6515
        Verifies if it is possible to connect to an existing scanner. It is
6516
        *not* verified if the scanner works as expected by the user.
6517
6518
        Arguments:
6519
            scanner_id: UUID of the scanner to be verified
6520
6521
        Returns:
6522
            The response. See :py:meth:`send_command` for details.
6523
        """
6524
        if not scanner_id:
6525
            raise InvalidArgument(
6526
                "verify_scanner requires a scanner_id argument"
6527
            )
6528
6529
        cmd = XmlCommand("verify_scanner")
6530
        cmd.set_attribute("scanner_id", scanner_id)
6531
6532
        return self._send_xml_command(cmd)
6533