From e17d9e14dc9087146f19758d819776ae7d63e99b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Ricks?= Date: Wed, 19 Jun 2024 10:35:53 +0200 Subject: [PATCH] Fix formatting, import order and linter warnings Run black and ruff on all the scripts. --- scripts/bulk-modify-schedules.gmp.py | 1 + scripts/certbund-report.gmp.py | 3 +- scripts/clean-sensor.gmp.py | 47 +++---- scripts/combine-reports.gmp.py | 3 +- scripts/create-alerts-from-csv.gmp.py | 72 +++++----- scripts/create-consolidated-report.gmp.py | 3 +- scripts/create-credentials-from-csv.gmp.py | 73 +++++----- scripts/create-cve-report-from-json.gmp.py | 3 +- scripts/create-dummy-data.gmp.py | 1 - scripts/create-filters-from-csv.gmp.py | 93 ++++++------- scripts/create-report-format-from-csv.gmp.py | 110 +++++++--------- scripts/create-schedules-from-csv.gmp.py | 38 +++--- scripts/create-tags-from-csv.gmp.py | 132 +++++++++++-------- scripts/create-targets-from-csv.gmp.py | 57 ++++---- scripts/create-targets-from-host-list.gmp.py | 3 +- scripts/create-tasks-from-csv.gmp.py | 83 ++++++------ scripts/empty-trash.gmp.py | 12 +- scripts/export-csv-report.gmp.py | 26 ++-- scripts/export-pdf-report.gmp.py | 9 +- scripts/export-xml-report.gmp.py | 15 ++- scripts/generate-random-reports.gmp.py | 5 +- scripts/generate-random-targets.gmp.py | 1 - scripts/list-alerts.gmp.py | 29 +++- scripts/list-credentials.gmp.py | 9 +- scripts/list-feeds.gmp.py | 17 +-- scripts/list-filters.gmp.py | 5 +- scripts/list-groups.gmp.py | 5 +- scripts/list-policies.gmp.py | 5 +- scripts/list-portlists.gmp.py | 9 +- scripts/list-report-formats.gmp.py | 6 +- scripts/list-reports.gmp.py | 72 ++++++---- scripts/list-roles.gmp.py | 5 +- scripts/list-scan-configs.gmp.py | 5 +- scripts/list-scanners.gmp.py | 5 +- scripts/list-schedules.gmp.py | 8 +- scripts/list-tags.gmp.py | 5 +- scripts/list-targets.gmp.py | 31 ++++- scripts/list-tasks.gmp.py | 9 +- scripts/list-tickets.gmp.py | 19 ++- scripts/list-users.gmp.py | 5 +- scripts/scan-new-system.gmp.py | 10 +- scripts/send-schedules.gmp.py | 3 +- scripts/send-targets.gmp.py | 3 +- scripts/send-tasks.gmp.py | 3 +- scripts/start-scans-from-csv.py | 54 ++++---- scripts/stop-all-scans.gmp.py | 21 ++- scripts/stop-scans-from-csv.py | 54 ++++---- scripts/update-task-target.gmp.py | 1 - 48 files changed, 619 insertions(+), 569 deletions(-) diff --git a/scripts/bulk-modify-schedules.gmp.py b/scripts/bulk-modify-schedules.gmp.py index 44e6421b..45ed6a50 100644 --- a/scripts/bulk-modify-schedules.gmp.py +++ b/scripts/bulk-modify-schedules.gmp.py @@ -4,6 +4,7 @@ import sys from argparse import Namespace + from gvm.protocols.gmp import Gmp diff --git a/scripts/certbund-report.gmp.py b/scripts/certbund-report.gmp.py index 592e067d..37b977c9 100644 --- a/scripts/certbund-report.gmp.py +++ b/scripts/certbund-report.gmp.py @@ -12,10 +12,11 @@ from itertools import zip_longest from typing import Dict, List, Optional, Sequence, Tuple, TypeVar, overload -import ssv_csv from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp +import ssv_csv + # from gvm.xml import pretty_print sys.path.append(os.path.dirname(args.argv[0])) # type: ignore diff --git a/scripts/clean-sensor.gmp.py b/scripts/clean-sensor.gmp.py index 422c5e20..76bd87f1 100644 --- a/scripts/clean-sensor.gmp.py +++ b/scripts/clean-sensor.gmp.py @@ -4,8 +4,8 @@ from argparse import Namespace -from gvm.protocols.gmp import Gmp from gvm.errors import GvmResponseError +from gvm.protocols.gmp import Gmp def clean_sensor(gmp: Gmp) -> None: @@ -24,7 +24,7 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass targets = gmp.get_targets(filter_string="rows=-1 not _owner=""") try: @@ -36,7 +36,7 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass configs = gmp.get_scan_configs( filter_string="rows=-1 not _owner=""" @@ -44,13 +44,13 @@ def clean_sensor(gmp: Gmp) -> None: try: for config_id in configs.xpath("config/@id"): print(f"Removing config {config_id} ... ") - status_text = gmp.delete_scan_config(config_id, ultimate=True).xpath( - "@status_text" - )[0] + status_text = gmp.delete_scan_config( + config_id, ultimate=True + ).xpath("@status_text")[0] print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass port_lists = gmp.get_port_lists( filter_string="rows=-1 not _owner=""" @@ -58,17 +58,15 @@ def clean_sensor(gmp: Gmp) -> None: try: for port_list_id in port_lists.xpath("port_list/@id"): print(f"Removing port_list {port_list_id} ... ") - status_text = gmp.delete_port_list(port_list_id, ultimate=True).xpath( - "@status_text" - )[0] + status_text = gmp.delete_port_list( + port_list_id, ultimate=True + ).xpath("@status_text")[0] print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass - alerts = gmp.get_alerts( - filter_string="rows=-1 not _owner=""" - ) + alerts = gmp.get_alerts(filter_string="rows=-1 not _owner=""") try: for alert_id in alerts.xpath("alert/@id"): print(f"Removing alert {alert_id} ... ") @@ -78,7 +76,7 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass schedules = gmp.get_schedules( filter_string="rows=-1 not _owner=""" @@ -92,11 +90,9 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass - tags = gmp.get_tags( - filter_string="rows=-1 not _owner=""" - ) + tags = gmp.get_tags(filter_string="rows=-1 not _owner=""") try: for tag_id in tags.xpath("tag/@id"): print(f"Removing tag {tag_id} ... ") @@ -106,11 +102,9 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass - filters = gmp.get_filters( - filter_string="rows=-1 not _owner=""" - ) + filters = gmp.get_filters(filter_string="rows=-1 not _owner=""") try: for filter_id in filters.xpath("filter/@id"): print(f"Removing filter {filter_id} ... ") @@ -120,7 +114,7 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass credentials = gmp.get_credentials( filter_string="rows=-1 not _owner=""" @@ -134,7 +128,7 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass print("Emptying trash... ") try: @@ -142,7 +136,8 @@ def clean_sensor(gmp: Gmp) -> None: print(status_text) except GvmResponseError as gvmerr: print(f"{gvmerr=}") - pass + pass + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=unused-argument diff --git a/scripts/combine-reports.gmp.py b/scripts/combine-reports.gmp.py index 849b8f5b..e4d162e8 100644 --- a/scripts/combine-reports.gmp.py +++ b/scripts/combine-reports.gmp.py @@ -9,9 +9,8 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp -from lxml import etree as e - from gvmtools.helper import generate_uuid +from lxml import etree as e def check_args(args: Namespace) -> None: diff --git a/scripts/create-alerts-from-csv.gmp.py b/scripts/create-alerts-from-csv.gmp.py index fa2a44aa..4614bc20 100755 --- a/scripts/create-alerts-from-csv.gmp.py +++ b/scripts/create-alerts-from-csv.gmp.py @@ -8,18 +8,14 @@ # Information on Variables to be used in alerts: https://docs.greenbone.net/GSM-Manual/gos-22.04/en/scanning.html#using-alerts # Example script: https://forum.greenbone.net/t/working-example-of-creating-an-alert-using-script/7511/2 +import csv import sys import time -import csv -import json - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError +from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -30,6 +26,7 @@ "It should be rather self explanatory." ) + def check_args(args): len_args = len(args.script) - 1 if len_args != 2: @@ -74,6 +71,7 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def alert_id( gmp: Gmp, alert_name: str, @@ -83,50 +81,55 @@ def alert_id( alert_id = "" for alert in alerts_xml: - name = "".join(alert.xpath("name/text()")) + "".join(alert.xpath("name/text()")) alert_id = alert.get("id") return alert_id + def credential_id( gmp: Gmp, credential_name: str, ): - response_xml = gmp.get_credentials(filter_string="rows=-1, name=" + credential_name) + response_xml = gmp.get_credentials( + filter_string="rows=-1, name=" + credential_name + ) credentials_xml = response_xml.xpath("credential") credential_id = "" for credential in credentials_xml: - name = "".join(credential.xpath("name/text()")) credential_id = credential.get("id") return credential_id + def report_format_id( gmp: Gmp, report_format_name: str, ): - response_xml = gmp.get_report_formats(details=True, filter_string="rows=-1, name=" + report_format_name) + response_xml = gmp.get_report_formats( + details=True, filter_string="rows=-1, name=" + report_format_name + ) report_formats_xml = response_xml.xpath("report_format") report_format_id = "" for report_format in report_formats_xml: - name = "".join(report_format.xpath("name/text()")) report_format_id = report_format.get("id") return report_format_id + def event_list(string): event_list = list(string.split(" ")) return event_list - -def create_alerts( + +def create_alerts( gmp: Gmp, alert_file: Path, ): try: numberalerts = 0 with open(alert_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue alert_name = row[0] @@ -140,12 +143,12 @@ def create_alerts( event_data = row[8] comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}" - alert_type=getattr(gmp.types.AlertMethod, str_alert_type) + alert_type = getattr(gmp.types.AlertMethod, str_alert_type) if alert_id(gmp, alert_name): print(f"Alert: {alert_name} exist, not creating...") continue - + if str_alert_type == "EMAIL": sender_email = strRow2 recipient_email = strRow3 @@ -174,7 +177,7 @@ def create_alerts( numberalerts = numberalerts + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {alert_name}") - pass + pass else: smb_credential = credential_id(gmp, strRow2) smb_share_path = strRow3 @@ -185,33 +188,34 @@ def create_alerts( try: print("Creating alert: " + alert_name) gmp.create_alert( - name=alert_name, - comment=comment, - event=gmp.types.AlertEvent.TASK_RUN_STATUS_CHANGED, - event_data={"status": event_data}, - condition=gmp.types.AlertCondition.ALWAYS, - method=alert_type, - method_data={ - "smb_credential": smb_credential, - "smb_share_path": smb_share_path, - "smb_report_format": report_format, - "smb_file_path": smb_file_path, - }, + name=alert_name, + comment=comment, + event=gmp.types.AlertEvent.TASK_RUN_STATUS_CHANGED, + event_data={"status": event_data}, + condition=gmp.types.AlertCondition.ALWAYS, + method=alert_type, + method_data={ + "smb_credential": smb_credential, + "smb_share_path": smb_share_path, + "smb_report_format": report_format, + "smb_file_path": smb_file_path, + }, ) numberalerts = numberalerts + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {alert_name}") - pass - csvFile.close() #close the csv file + pass + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read alert_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("alerts file is empty (exit)") - + return numberalerts - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: diff --git a/scripts/create-consolidated-report.gmp.py b/scripts/create-consolidated-report.gmp.py index 7fed753c..febf93d9 100755 --- a/scripts/create-consolidated-report.gmp.py +++ b/scripts/create-consolidated-report.gmp.py @@ -9,9 +9,8 @@ from gvm.errors import GvmError from gvm.protocols.gmp import Gmp -from lxml import etree as e - from gvmtools.helper import error_and_exit, generate_uuid +from lxml import etree as e HELP_TEXT = ( "This script creates a consolidated report and imports it to the GSM. " diff --git a/scripts/create-credentials-from-csv.gmp.py b/scripts/create-credentials-from-csv.gmp.py index 66e8f6e1..6d912179 100755 --- a/scripts/create-credentials-from-csv.gmp.py +++ b/scripts/create-credentials-from-csv.gmp.py @@ -8,17 +8,14 @@ # # Run with gvm-script --gmp-username admin-user --gmp-password password socket create-credentials-from-csv.gmp.py credentials.csv +import csv import sys import time -import csv - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError +from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -75,28 +72,31 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def credential_id( gmp: Gmp, credName: str, ): - response_xml = gmp.get_credentials(filter_string="rows=-1, name=" + credName) + response_xml = gmp.get_credentials( + filter_string="rows=-1, name=" + credName + ) credentials_xml = response_xml.xpath("credential") cred_id = "" for credential in credentials_xml: - name = "".join(credential.xpath("name/text()")) cred_id = credential.get("id") return cred_id -def create_credentials( + +def create_credentials( gmp: Gmp, cred_file: Path, ): try: numberCredentials = 0 with open(cred_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue cred_name = row[0] @@ -113,11 +113,11 @@ def create_credentials( try: print("Creating credential: " + cred_name) gmp.create_credential( - name=cred_name, - credential_type=gmp.types.CredentialType.USERNAME_PASSWORD, - login=userName, - password=userPW, - comment=comment, + name=cred_name, + credential_type=gmp.types.CredentialType.USERNAME_PASSWORD, + login=userName, + password=userPW, + comment=comment, ) numberCredentials = numberCredentials + 1 except GvmResponseError as gvmerr: @@ -127,7 +127,7 @@ def create_credentials( with open(row[4]) as key_file: key = key_file.read() - try: + try: print("Creating credential: " + cred_name) gmp.create_credential( name=cred_name, @@ -136,22 +136,22 @@ def create_credentials( key_phrase=userPW, private_key=key, comment=comment, - ) + ) numberCredentials = numberCredentials + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {cred_name}") pass elif cred_type == "SNMP": - # Unfinished, copy of UP for now + # Unfinished, copy of UP for now try: print("Creating credential: " + cred_name) gmp.create_credential( - name=cred_name, - credential_type=gmp.types.CredentialType.USERNAME_SSH_KEY, - login=userName, - key_phrase=userPW, - private_key=key, - comment=comment, + name=cred_name, + credential_type=gmp.types.CredentialType.USERNAME_SSH_KEY, + login=userName, + key_phrase=userPW, + private_key=key, + comment=comment, ) numberCredentials = numberCredentials + 1 except GvmResponseError as gvmerr: @@ -159,31 +159,32 @@ def create_credentials( pass elif cred_type == "ESX": - # Unfinished, copy of UP for now + # Unfinished, copy of UP for now try: print("Creating credential: " + cred_name) gmp.create_credential( - name=cred_name, - credential_type=gmp.types.CredentialType.USERNAME_SSH_KEY, - login=userName, - key_phrase=userPW, - private_key=key, - comment=comment, + name=cred_name, + credential_type=gmp.types.CredentialType.USERNAME_SSH_KEY, + login=userName, + key_phrase=userPW, + private_key=key, + comment=comment, ) numberCredentials = numberCredentials + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {cred_name}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read cred_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("Credentials file is empty (exit)") - + return numberCredentials - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: @@ -191,9 +192,7 @@ def main(gmp: Gmp, args: Namespace) -> None: parsed_args = parse_args(args=args) - print( - "Creating credentials.\n" - ) + print("Creating credentials.\n") numberCredentials = create_credentials( gmp, diff --git a/scripts/create-cve-report-from-json.gmp.py b/scripts/create-cve-report-from-json.gmp.py index 73ef728a..a930754c 100644 --- a/scripts/create-cve-report-from-json.gmp.py +++ b/scripts/create-cve-report-from-json.gmp.py @@ -12,9 +12,8 @@ from cpe import CPE from gvm.protocols.gmp import Gmp -from lxml import etree as e - from gvmtools.helper import error_and_exit, generate_uuid +from lxml import etree as e HELP_TEXT = ( "This script creates a cve report from a JSON document.\n" diff --git a/scripts/create-dummy-data.gmp.py b/scripts/create-dummy-data.gmp.py index b7374d74..3d57c771 100644 --- a/scripts/create-dummy-data.gmp.py +++ b/scripts/create-dummy-data.gmp.py @@ -7,7 +7,6 @@ from random import choice from gvm.protocols.gmp import Gmp - from gvmtools.helper import generate_id diff --git a/scripts/create-filters-from-csv.gmp.py b/scripts/create-filters-from-csv.gmp.py index f9023d74..3263ee38 100755 --- a/scripts/create-filters-from-csv.gmp.py +++ b/scripts/create-filters-from-csv.gmp.py @@ -7,17 +7,14 @@ # # Run with gvm-script --gmp-username admin-user --gmp-password password socket create-filters-from-csv.gmp.py hostname-server filters.csv +import csv import sys import time -import csv - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError +from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -72,6 +69,7 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def filter_id( gmp: Gmp, filter_name: str, @@ -81,100 +79,109 @@ def filter_id( filter_id = "" for filter in filters_xml: - name = "".join(filter.xpath("name/text()")) filter_id = filter.get("id") return filter_id -def create_filters( + +def create_filters( gmp: Gmp, filter_csv_file: Path, ): try: numberfilters = 0 with open(filter_csv_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue filterType = row[0] filterName = row[1] filterDescription = row[2] filterTerm = row[3] - filterNameFull = filterName + ":" + filterDescription + ":" + filterType + filterNameFull = ( + filterName + ":" + filterDescription + ":" + filterType + ) comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}" - filterResources = [] if filterType == "FAIL!": print(filterType.upper()) elif filterType.upper() == "ALERT": - resource_type=gmp.types.FilterType.ALERT + resource_type = gmp.types.FilterType.ALERT elif filterType.upper() == "ASSET": - resource_type=gmp.types.FilterType.ASSET + resource_type = gmp.types.FilterType.ASSET elif filterType.upper() == "CONFIG": - resource_type=gmp.types.FilterType.SCAN_CONFIG + resource_type = gmp.types.FilterType.SCAN_CONFIG elif filterType.upper() == "CREDENTIAL": - resource_type=gmp.types.FilterType.CREDENTIAL + resource_type = gmp.types.FilterType.CREDENTIAL elif filterType.upper() == "HOST": - resource_type=gmp.types.FilterType.HOST + resource_type = gmp.types.FilterType.HOST elif filterType.upper() == "SECINFO": - resource_type=gmp.types.FilterType.ALL_SECINFO + resource_type = gmp.types.FilterType.ALL_SECINFO elif filterType.upper() == "NOTE": - resource_type=gmp.types.FilterType.NOTE + resource_type = gmp.types.FilterType.NOTE elif filterType.upper() == "OS": - resource_type=gmp.types.FilterType.OPERATING_SYSTEM + resource_type = gmp.types.FilterType.OPERATING_SYSTEM elif filterType.upper() == "OVERRIDE": - resource_type=gmp.types.FilterType.OVERRIDE + resource_type = gmp.types.FilterType.OVERRIDE elif filterType.upper() == "PERMISSION": - resource_type=gmp.types.FilterType.PERMISSION + resource_type = gmp.types.FilterType.PERMISSION elif filterType.upper() == "PORT_LIST": - resource_type=gmp.types.FilterType.PORT_LIST + resource_type = gmp.types.FilterType.PORT_LIST elif filterType.upper() == "REPORT": - resource_type=gmp.types.FilterType.REPORT + resource_type = gmp.types.FilterType.REPORT elif filterType.upper() == "REPORT_FORMAT": - resource_type=gmp.types.FilterType.REPORT_FORMAT + resource_type = gmp.types.FilterType.REPORT_FORMAT elif filterType.upper() == "RESULT": - resource_type=gmp.types.FilterType.RESULT + resource_type = gmp.types.FilterType.RESULT elif filterType.upper() == "ROLE": - resource_type=gmp.types.FilterType.ROLE + resource_type = gmp.types.FilterType.ROLE elif filterType.upper() == "SCHEDULE": - resource_type=gmp.types.FilterType.SCHEDULE + resource_type = gmp.types.FilterType.SCHEDULE elif filterType.upper() == "TAG": - resource_type=gmp.types.FilterType.TAG + resource_type = gmp.types.FilterType.TAG elif filterType.upper() == "TARGET": - resource_type=gmp.types.FilterType.TARGET + resource_type = gmp.types.FilterType.TARGET elif filterType.upper() == "TASK": - resource_type=gmp.types.FilterType.TASK + resource_type = gmp.types.FilterType.TASK elif filterType.upper() == "TICKET": - resource_type=gmp.types.FilterType.TICKET + resource_type = gmp.types.FilterType.TICKET elif filterType.upper() == "TLS_CERTIFICATE": - resource_type=gmp.types.FilterType.TLS_CERTIFICATE + resource_type = gmp.types.FilterType.TLS_CERTIFICATE elif filterType.upper() == "USER": - resource_type=gmp.types.FilterType.USER + resource_type = gmp.types.FilterType.USER elif filterType.upper() == "VULNERABILITY": - resource_type=gmp.types.FilterType.VULNERABILITY - else: - print("FilterType: " + filterType.upper() + " Not supported") + resource_type = gmp.types.FilterType.VULNERABILITY + else: + print( + "FilterType: " + filterType.upper() + " Not supported" + ) try: if filter_id(gmp, filterNameFull): - print(f"Filter: {filterNameFull} exist, not creating...") + print( + f"Filter: {filterNameFull} exist, not creating..." + ) continue print("Creating filter: " + filterNameFull) gmp.create_filter( - name=filterNameFull, comment=comment, filter_type=resource_type, term=filterTerm, + name=filterNameFull, + comment=comment, + filter_type=resource_type, + term=filterTerm, ) numberfilters = numberfilters + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {filterNameFull}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read filter_csv_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("filter file is empty (exit)") - + return numberfilters - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: @@ -182,9 +189,7 @@ def main(gmp: Gmp, args: Namespace) -> None: parsed_args = parse_args(args=args) - print( - "Creating filters.\n" - ) + print("Creating filters.\n") numberfilters = create_filters( gmp, diff --git a/scripts/create-report-format-from-csv.gmp.py b/scripts/create-report-format-from-csv.gmp.py index f3549ac0..5fa3c206 100755 --- a/scripts/create-report-format-from-csv.gmp.py +++ b/scripts/create-report-format-from-csv.gmp.py @@ -5,17 +5,12 @@ # Run with gvm-script --gmp-username admin-user --gmp-password password socket create-report_formats-from-csv.gmp.py report_formats.csv -import sys -import time import csv - +import sys from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -71,77 +66,74 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args -def create_report_formats( + +def create_report_formats( gmp: Gmp, cred_file: Path, ): try: numberreport_formats = 0 with open(cred_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row numberreport_formats = numberreport_formats + 1 REPORT_FORMAT_XML_STRING = ( - '' - '' - "CSV vulnscan.dk" - 'name=CSV first=1 rows=10 sort=name' - '' - '' - 'name' - '=' - 'CSV' - '' - '' - 'first' - '=' - '1' - '' - '' - 'rows' - '=' - '10' - '' - '' - 'sort' - '=' - 'name' - '' - '' - 'csv' - 'text/csv' - "vulnscan.dk CSV Report Format. Version 2023-03-31." - "vulnscan.dk CSV Report Format" - 'Complete scan report in GMP XML format. Version 20200827.' - '1' - '0' - '1' - '1' - "2024-03-31T10:48:03Z" - "2024-03-31T10:48:03Z" - '' - '500' - "" - "" + '' + '' + "CSV vulnscan.dk" + "name=CSV first=1 rows=10 sort=name" + "" + "" + "name" + "=" + "CSV" + "" + "" + "first" + "=" + "1" + "" + "" + "rows" + "=" + "10" + "" + "" + "sort" + "=" + "name" + "" + "" + "csv" + "text/csv" + "vulnscan.dk CSV Report Format. Version 2023-03-31." + "vulnscan.dk CSV Report Format" + "Complete scan report in GMP XML format. Version 20200827." + "1" + "0" + "1" + "1" + "2024-03-31T10:48:03Z" + "2024-03-31T10:48:03Z" + '' + "500" + "" + "" ) - - rf_copy = "c1645568-627a-11e3-a660-406186ea4fc5" - comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}" - gmp.import_report_format( - REPORT_FORMAT_XML_STRING - ) + gmp.import_report_format(REPORT_FORMAT_XML_STRING) - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read cred_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("report_formats file is empty (exit)") - + return numberreport_formats - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: diff --git a/scripts/create-schedules-from-csv.gmp.py b/scripts/create-schedules-from-csv.gmp.py index 593844e7..ddc07693 100755 --- a/scripts/create-schedules-from-csv.gmp.py +++ b/scripts/create-schedules-from-csv.gmp.py @@ -5,17 +5,14 @@ # Run with gvm-script --gmp-username admin-user --gmp-password password socket create-schedules-from-csv.gmp.py schedules.csv +import csv import sys import time -import csv - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError +from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -72,29 +69,31 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def schedule_id( gmp: Gmp, schedule_name: str, ): - response_xml = gmp.get_schedules(filter_string="rows=-1, name=" + schedule_name) + response_xml = gmp.get_schedules( + filter_string="rows=-1, name=" + schedule_name + ) schedules_xml = response_xml.xpath("schedule") schedule_id = "" for schedule in schedules_xml: - name = "".join(schedule.xpath("name/text()")) schedule_id = schedule.get("id") return schedule_id -def create_schedules( +def create_schedules( gmp: Gmp, sched_file: Path, ): try: numberschedules = 0 with open(sched_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue sched_name = row[0] @@ -107,25 +106,26 @@ def create_schedules( continue print("Creating schedule: " + sched_name) gmp.create_schedule( - name=sched_name, - timezone=sched_tz, - icalendar=sched_ical, - comment=comment + name=sched_name, + timezone=sched_tz, + icalendar=sched_ical, + comment=comment, ) numberschedules = numberschedules + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {sched_name}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read sched_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("schedules file is empty (exit)") - + return numberschedules - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: @@ -133,9 +133,7 @@ def main(gmp: Gmp, args: Namespace) -> None: parsed_args = parse_args(args=args) - print( - "Creating schedules.\n" - ) + print("Creating schedules.\n") numberschedules = create_schedules( gmp, diff --git a/scripts/create-tags-from-csv.gmp.py b/scripts/create-tags-from-csv.gmp.py index ed7a04c5..4d76dffb 100755 --- a/scripts/create-tags-from-csv.gmp.py +++ b/scripts/create-tags-from-csv.gmp.py @@ -5,16 +5,14 @@ # Run with gvm-script --gmp-username admin-user --gmp-password password socket create-tags-from-csv.gmp.py hostname-server tags.csv +import csv import sys import time -import csv - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.protocols.gmp import Gmp from gvm.errors import GvmResponseError +from gvm.protocols.gmp import Gmp from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -69,19 +67,22 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def config_id( gmp: Gmp, config_name: str, ): - response_xml = gmp.get_scan_configs(filter_string="rows=-1, name= " + config_name) + response_xml = gmp.get_scan_configs( + filter_string="rows=-1, name= " + config_name + ) scan_configs_xml = response_xml.xpath("config") config_id = "" for scan_config in scan_configs_xml: - name = "".join(scan_config.xpath("name/text()")) config_id = scan_config.get("id") return config_id + def alert_id( gmp: Gmp, alert_name: str, @@ -91,23 +92,25 @@ def alert_id( alert_id = "" for alert in alerts_xml: - name = "".join(alert.xpath("name/text()")) alert_id = alert.get("id") return alert_id + def credential_id( gmp: Gmp, credName: str, ): - response_xml = gmp.get_credentials(filter_string="rows=-1, name=" + credName) + response_xml = gmp.get_credentials( + filter_string="rows=-1, name=" + credName + ) credentials_xml = response_xml.xpath("credential") cred_id = "" for credential in credentials_xml: - name = "".join(credential.xpath("name/text()")) cred_id = credential.get("id") return cred_id + def target_id( gmp: Gmp, targetName: str, @@ -117,10 +120,10 @@ def target_id( target_id = "" for target in targets_xml: - name = "".join(target.xpath("name/text()")) target_id = target.get("id") return target_id + def task_id( gmp: Gmp, taskName: str, @@ -130,10 +133,10 @@ def task_id( task_id = "" for task in tasks_xml: - name = "".join(task.xpath("name/text()")) task_id = task.get("id") return task_id + def tag_id( gmp: Gmp, tagName: str, @@ -143,45 +146,49 @@ def tag_id( tag_id = "" for tag in tags_xml: - name = "".join(tag.xpath("name/text()")) tag_id = tag.get("id") return tag_id + def scanner_id( gmp: Gmp, scanner_name: str, ): - response_xml = gmp.get_scanners(filter_string="rows=-1, name=" + scanner_name) + response_xml = gmp.get_scanners( + filter_string="rows=-1, name=" + scanner_name + ) scanners_xml = response_xml.xpath("scanner") scanner_id = "" for scanner in scanners_xml: - name = "".join(scanner.xpath("name/text()")) scanner_id = scanner.get("id") return scanner_id + def schedule_id( gmp: Gmp, schedule_name: str, ): - response_xml = gmp.get_schedules(filter_string="rows=-1, name=" + schedule_name) + response_xml = gmp.get_schedules( + filter_string="rows=-1, name=" + schedule_name + ) schedules_xml = response_xml.xpath("schedule") schedule_id = "" for schedule in schedules_xml: - name = "".join(schedule.xpath("name/text()")) schedule_id = schedule.get("id") return schedule_id -def create_tags( + +def create_tags( gmp: Gmp, tag_csv_file: Path, ): try: numbertags = 0 with open(tag_csv_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue tagType = row[0] @@ -196,62 +203,64 @@ def create_tags( if tagType.upper() == "FAIL!": print("Failed!") elif tagType.upper() == "ALERT": - getUUID=alert_id - resource_type=gmp.types.EntityType.ALERT + getUUID = alert_id + resource_type = gmp.types.EntityType.ALERT elif tagType.upper() == "CONFIG": - getUUID=config_id - resource_type=gmp.types.EntityType.SCAN_CONFIG + getUUID = config_id + resource_type = gmp.types.EntityType.SCAN_CONFIG elif tagType.upper() == "CREDENTIAL": - getUUID=credential_id - resource_type=gmp.types.EntityType.CREDENTIAL + getUUID = credential_id + resource_type = gmp.types.EntityType.CREDENTIAL elif tagType.upper() == "REPORT": filter = "~" + tagName - resource_type=gmp.types.EntityType.REPORT + resource_type = gmp.types.EntityType.REPORT elif tagType.upper() == "SCANNER": - getUUID=scanner_id - resource_type=gmp.types.EntityType.SCANNER + getUUID = scanner_id + resource_type = gmp.types.EntityType.SCANNER elif tagType.upper() == "SCHEDULE": - getUUID=schedule_id - resource_type=gmp.types.EntityType.SCHEDULE + getUUID = schedule_id + resource_type = gmp.types.EntityType.SCHEDULE elif tagType.upper() == "TARGET": - getUUID=target_id - resource_type=gmp.types.EntityType.TARGET + getUUID = target_id + resource_type = gmp.types.EntityType.TARGET elif tagType.upper() == "TASK": - getUUID=task_id - resource_type=gmp.types.EntityType.TASK + getUUID = task_id + resource_type = gmp.types.EntityType.TASK else: - print("Only alert, config, credential, report, scanner, schedule, target, and task supported") + print( + "Only alert, config, credential, report, scanner, schedule, target, and task supported" + ) exit() - + if len(row[3]) >= 1: - tagResource = (getUUID(gmp, row[3])) - tagResources.append(tagResource) + tagResource = getUUID(gmp, row[3]) + tagResources.append(tagResource) if len(row[4]) >= 1: - tagResource = (getUUID(gmp, row[4])) - tagResources.append(tagResource) - if len (row[5]) >= 1: - tagResource = (getUUID(gmp, row[5])) + tagResource = getUUID(gmp, row[4]) + tagResources.append(tagResource) + if len(row[5]) >= 1: + tagResource = getUUID(gmp, row[5]) tagResources.append(tagResource) if len(row[6]) >= 1: - tagResource = (getUUID(gmp, row[6])) + tagResource = getUUID(gmp, row[6]) tagResources.append(tagResource) if len(row[7]) >= 1: - tagResource = (getUUID(gmp, row[7])) + tagResource = getUUID(gmp, row[7]) tagResources.append(tagResource) - if len (row[8]) >= 1: - tagResource = (getUUID(gmp, row[8])) + if len(row[8]) >= 1: + tagResource = getUUID(gmp, row[8]) tagResources.append(tagResource) if len(row[9]) >= 1: - tagResource = (getUUID(gmp, row[9])) + tagResource = getUUID(gmp, row[9]) tagResources.append(tagResource) - tagResource = (getUUID(gmp, row[10])) + tagResource = getUUID(gmp, row[10]) if len(row[10]) >= 1: tagResources.append(tagResource) if len(row[11]) >= 1: - tagResource = (getUUID(gmp, row[11])) + tagResource = getUUID(gmp, row[11]) tagResources.append(tagResource) if len(row[12]) >= 1: - tagResource = (getUUID(gmp, row[12])) + tagResource = getUUID(gmp, row[12]) tagResources.append(tagResource) comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}" @@ -259,7 +268,11 @@ def create_tags( try: print("Creating tag: " + tagNameFull) gmp.create_tag( - name=tagNameFull, comment=comment, value=tagName, resource_type=resource_type, resource_filter=filter, + name=tagNameFull, + comment=comment, + value=tagName, + resource_type=resource_type, + resource_filter=filter, ) numbertags = numbertags + 1 except GvmResponseError as gvmerr: @@ -269,21 +282,26 @@ def create_tags( try: print("Creating tag: " + tagNameFull) gmp.create_tag( - name=tagNameFull, comment=comment, value=tagName, resource_type=resource_type, resource_ids=tagResources, + name=tagNameFull, + comment=comment, + value=tagName, + resource_type=resource_type, + resource_ids=tagResources, ) numbertags = numbertags + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {tagNameFull}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read tag_csv_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("tag file is empty (exit)") - + return numbertags - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: @@ -291,9 +309,7 @@ def main(gmp: Gmp, args: Namespace) -> None: parsed_args = parse_args(args=args) - print( - "Creating tags.\n" - ) + print("Creating tags.\n") numbertags = create_tags( gmp, diff --git a/scripts/create-targets-from-csv.gmp.py b/scripts/create-targets-from-csv.gmp.py index 3028e858..b8d310e1 100755 --- a/scripts/create-targets-from-csv.gmp.py +++ b/scripts/create-targets-from-csv.gmp.py @@ -5,13 +5,12 @@ # Run with gvm-script --gmp-username admin-user --gmp-password password socket create-targets-from-csv.gmp.py hostname-server targets.csv +import csv import sys import time -import csv - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List + from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp from gvmtools.helper import error_and_exit @@ -88,7 +87,7 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument port_list_id="730ef368-57e2-11e1-a90f-406186ea4fc5" ) # All TCP and Nmap top 100 UDP # Default portlists see also script list-portlists.gmp.py - # | Name | ID + # | Name | ID # - | ----------------------------- | ------------------------------------ # 1 | All IANA assigned TCP | 33d0cd82-57c6-11e1-8ed1-406186ea4fc5 # 2 | All IANA assigned TCP and UDP | 4a4717fe-57d2-11e1-9a26-406186ea4fc5 @@ -97,19 +96,22 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def credential_id( gmp: Gmp, credName: str, ): - response_xml = gmp.get_credentials(filter_string="rows=-1, name=" + credName) + response_xml = gmp.get_credentials( + filter_string="rows=-1, name=" + credName + ) credentials_xml = response_xml.xpath("credential") cred_id = "" for credential in credentials_xml: - name = "".join(credential.xpath("name/text()")) cred_id = credential.get("id") return cred_id + def target_id( gmp: Gmp, targetName: str, @@ -119,11 +121,11 @@ def target_id( target_id = "" for target in targets_xml: - name = "".join(target.xpath("name/text()")) target_id = target.get("id") return target_id -def create_targets( + +def create_targets( gmp: Gmp, target_csv_file: Path, port_list_id: str, @@ -131,22 +133,18 @@ def create_targets( try: numberTargets = 0 with open(target_csv_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue name = row[0] hosts = [row[1]] smbCred = credential_id(gmp, row[2]) sshCred = credential_id(gmp, row[3]) - snmpCred = credential_id(gmp, row[4]) - esxCred = credential_id(gmp, row[5]) aliveTest = row[6] if not aliveTest: - aliveTest = "Scan Config Default" - alive_test = gmp.types.AliveTest( - (aliveTest) - ) + aliveTest = "Scan Config Default" + alive_test = gmp.types.AliveTest((aliveTest)) comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}" try: if target_id(gmp, name): @@ -155,37 +153,40 @@ def create_targets( print("Creating target: " + name) gmp.create_target( - name=name, comment=comment, hosts=hosts, port_list_id=port_list_id, smb_credential_id=smbCred, ssh_credential_id=sshCred, alive_test=alive_test + name=name, + comment=comment, + hosts=hosts, + port_list_id=port_list_id, + smb_credential_id=smbCred, + ssh_credential_id=sshCred, + alive_test=alive_test, ) numberTargets = numberTargets + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {name}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read target_csv_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("Host file is empty (exit)") - + return numberTargets - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: args = args.script[1:] parsed_args = parse_args(args=args) - #port_list_id="4a4717fe-57d2-11e1-9a26-406186ea4fc5" + # port_list_id="4a4717fe-57d2-11e1-9a26-406186ea4fc5" + + print("Creating targets.\n") - print( - "Creating targets.\n" - ) - numberTargets = create_targets( - gmp, - parsed_args.targets_csv_file, - parsed_args.port_list_id + gmp, parsed_args.targets_csv_file, parsed_args.port_list_id ) numberTargets = str(numberTargets) diff --git a/scripts/create-targets-from-host-list.gmp.py b/scripts/create-targets-from-host-list.gmp.py index f6217277..9533194e 100644 --- a/scripts/create-targets-from-host-list.gmp.py +++ b/scripts/create-targets-from-host-list.gmp.py @@ -9,7 +9,6 @@ from typing import List from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -26,7 +25,7 @@ def check_args(args): for each. One parameter after the script name is required. - 1. -- IP of the GVM host + 1. -- IP of the GVM host 2. -- text file containing hostnames Example: diff --git a/scripts/create-tasks-from-csv.gmp.py b/scripts/create-tasks-from-csv.gmp.py index 840554e7..80bf2096 100755 --- a/scripts/create-tasks-from-csv.gmp.py +++ b/scripts/create-tasks-from-csv.gmp.py @@ -10,16 +10,14 @@ # Note: for some weird reason theres a space in front of the default scan config " Full and fast" # Examples of all defaults in tasks.csv +import csv import sys import time -import csv - from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.protocols.gmpv208.entities.hosts import HostsOrdering #Only available in version 20.8 -from gvm.protocols.gmp import Gmp + from gvm.errors import GvmResponseError +from gvm.protocols.gmp import Gmp from gvmtools.helper import error_and_exit HELP_TEXT = ( @@ -94,7 +92,7 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument port_list_id="730ef368-57e2-11e1-a90f-406186ea4fc5" ) # All IANA assigned TCP and Top 100 UDP, use the list-portlists.gmp.py script to get the UUID for all. # Defaults are - # # | Name | ID + # # | Name | ID # - | ----------------------------- | ------------------------------------ # 1 | All IANA assigned TCP | 33d0cd82-57c6-11e1-8ed1-406186ea4fc5 # 2 | All IANA assigned TCP and UDP | 4a4717fe-57d2-11e1-9a26-406186ea4fc5 @@ -103,20 +101,22 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def config_id( gmp: Gmp, config_name: str, ): - response_xml = gmp.get_scan_configs(filter_string="rows=-1, name= " + config_name -) + response_xml = gmp.get_scan_configs( + filter_string="rows=-1, name= " + config_name + ) scan_configs_xml = response_xml.xpath("config") config_id = "" for scan_config in scan_configs_xml: - name = "".join(scan_config.xpath("name/text()")) config_id = scan_config.get("id") return config_id + def alert_id( gmp: Gmp, alert_name: str, @@ -126,10 +126,10 @@ def alert_id( alert_id = "" for alert in alerts_xml: - name = "".join(alert.xpath("name/text()")) alert_id = alert.get("id") return alert_id + def target_id( gmp: Gmp, target_name: str, @@ -139,36 +139,40 @@ def target_id( target_id = "" for target in targets_xml: - name = "".join(target.xpath("name/text()")) target_id = target.get("id") return target_id + def scanner_id( gmp: Gmp, scanner_name: str, ): - response_xml = gmp.get_scanners(filter_string="rows=-1, name=" + scanner_name) + response_xml = gmp.get_scanners( + filter_string="rows=-1, name=" + scanner_name + ) scanners_xml = response_xml.xpath("scanner") scanner_id = "" for scanner in scanners_xml: - name = "".join(scanner.xpath("name/text()")) scanner_id = scanner.get("id") return scanner_id + def schedule_id( gmp: Gmp, schedule_name: str, ): - response_xml = gmp.get_schedules(filter_string="rows=-1, name=" + schedule_name) + response_xml = gmp.get_schedules( + filter_string="rows=-1, name=" + schedule_name + ) schedules_xml = response_xml.xpath("schedule") schedule_id = "" for schedule in schedules_xml: - name = "".join(schedule.xpath("name/text()")) schedule_id = schedule.get("id") return schedule_id + def task_id( gmp: Gmp, taskName: str, @@ -178,11 +182,11 @@ def task_id( task_id = "" for task in tasks_xml: - name = "".join(task.xpath("name/text()")) task_id = task.get("id") return task_id -def create_tasks( + +def create_tasks( gmp: Gmp, task_csv_file: Path, port_list_id: str, @@ -190,8 +194,8 @@ def create_tasks( try: numberTasks = 0 with open(task_csv_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data - for row in content: #loop through each row + content = csv.reader(csvFile, delimiter=",") # read the data + for row in content: # loop through each row if len(row) == 0: continue name = row[0] @@ -203,13 +207,13 @@ def create_tasks( newOrder = row[5].upper() if newOrder == "RANDOM": - order = HostsOrdering.RANDOM + order = gmp.types.HostsOrdering.RANDOM elif newOrder == "SEQUENTIAL": - order = HostsOrdering.SEQUENTIAL + order = gmp.types.HostsOrdering.SEQUENTIAL elif newOrder == "REVERSE": - order = HostsOrdering.REVERSE + order = gmp.types.HostsOrdering.REVERSE else: - order = HostsOrdering.RANDOM + order = gmp.types.HostsOrdering.RANDOM alerts = [] if len(row[6]) > 1: @@ -218,7 +222,7 @@ def create_tasks( if len(row[7]) > 1: alert = alert_id(gmp, row[7]) alerts.append(alert) - if len (row[8]) > 1: + if len(row[8]) > 1: alert = alert_id(gmp, row[8]) alerts.append(alert) if len(row[9]) > 1: @@ -228,47 +232,52 @@ def create_tasks( alert = alert_id(gmp, row[10]) alerts.append(alert) - scanOrder = order # Use SEQUENTIAL, REVERSE, or RANDOM + scanOrder = order # Use SEQUENTIAL, REVERSE, or RANDOM comment = f"Created: {time.strftime('%Y/%m/%d-%H:%M:%S')}" - + try: if task_id(gmp, name): print(f"Task: {name} exist already") continue print("Creating task: " + name) gmp.create_task( - name=name, comment=comment, config_id=configId, target_id=targetId, hosts_ordering=scanOrder, scanner_id=scannerId, alterable=alterable, schedule_id=scheduleId, alert_ids=alerts + name=name, + comment=comment, + config_id=configId, + target_id=targetId, + hosts_ordering=scanOrder, + scanner_id=scannerId, + alterable=alterable, + schedule_id=scheduleId, + alert_ids=alerts, ) numberTasks = numberTasks + 1 except GvmResponseError as gvmerr: print(f"{gvmerr=}, name: {name}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read task_csv_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("Host file is empty (exit)") - + return numberTasks - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: args = args.script[1:] parsed_args = parse_args(args=args) - #port_list_id="4a4717fe-57d2-11e1-9a26-406186ea4fc5" + # port_list_id="4a4717fe-57d2-11e1-9a26-406186ea4fc5" - print( - "Creating tasks\n" - ) + print("Creating tasks\n") numberTasks = create_tasks( - gmp, - parsed_args.tasks_csv_file, - parsed_args.port_list_id + gmp, parsed_args.tasks_csv_file, parsed_args.port_list_id ) numberTasks = str(numberTasks) diff --git a/scripts/empty-trash.gmp.py b/scripts/empty-trash.gmp.py index 492da539..6c4b8b41 100755 --- a/scripts/empty-trash.gmp.py +++ b/scripts/empty-trash.gmp.py @@ -6,21 +6,17 @@ from gvm.protocols.gmp import Gmp -from gvmtools.helper import Table - - def main(gmp: Gmp, args: Namespace) -> None: - print( - "Emptying Trash...\n" - ) + print("Emptying Trash...\n") try: status_text = gmp.empty_trashcan().xpath("@status_text")[0] print(status_text) - except: - pass + except Exception as e: + print(f"{e=}") + if __name__ == "__gmp__": main(gmp, args) diff --git a/scripts/export-csv-report.gmp.py b/scripts/export-csv-report.gmp.py index f906754a..a1377619 100755 --- a/scripts/export-csv-report.gmp.py +++ b/scripts/export-csv-report.gmp.py @@ -5,9 +5,11 @@ # Based on the export-pdf-report script and modified to # create csv and return more (all) details. +import sys +from argparse import Namespace from base64 import b64decode from pathlib import Path -from argparse import Namespace + from gvm.protocols.gmp import Gmp @@ -15,11 +17,11 @@ def check_args(args): len_args = len(args.script) - 1 if len_args < 1: message = """ - This script requests the given report and exports it as a csv + This script requests the given report and exports it as a csv file locally. It requires one parameter after the script name. 1. -- ID of the report - + Optional a file name to save the csv in. Examples: @@ -45,7 +47,10 @@ def main(gmp: Gmp, args: Namespace) -> None: csv_report_format_id = "c1645568-627a-11e3-a660-406186ea4fc5" response = gmp.get_report( - report_id=report_id, report_format_id=csv_report_format_id, ignore_pagination=True, details=True + report_id=report_id, + report_format_id=csv_report_format_id, + ignore_pagination=True, + details=True, ) report_element = response.find("report") @@ -54,15 +59,15 @@ def main(gmp: Gmp, args: Namespace) -> None: if not content: print( - 'Requested report is empty. Either the report does not contain any ' - ' results or the necessary tools for creating the report are ' - 'not installed.', + "Requested report is empty. Either the report does not contain any " + " results or the necessary tools for creating the report are " + "not installed.", file=sys.stderr, ) sys.exit(1) # convert content to 8-bit ASCII bytes - binary_base64_encoded_csv = content.encode('ascii') + binary_base64_encoded_csv = content.encode("ascii") # decode base64 binary_csv = b64decode(binary_base64_encoded_csv) @@ -72,9 +77,8 @@ def main(gmp: Gmp, args: Namespace) -> None: csv_path.write_bytes(binary_csv) - print('Done. CSV created: ' + str(csv_path)) + print("Done. CSV created: " + str(csv_path)) -if __name__ == '__gmp__': +if __name__ == "__gmp__": main(gmp, args) - diff --git a/scripts/export-pdf-report.gmp.py b/scripts/export-pdf-report.gmp.py index f18a3f9b..3e45db98 100644 --- a/scripts/export-pdf-report.gmp.py +++ b/scripts/export-pdf-report.gmp.py @@ -15,11 +15,11 @@ def check_args(args): len_args = len(args.script) - 1 if len_args < 1: message = """ - This script requests the given report and exports it as a pdf + This script requests the given report and exports it as a pdf file locally. It requires one parameters after the script name. 1. -- ID of the report - + Optional a file name to save the pdf in. Example: @@ -44,7 +44,10 @@ def main(gmp: Gmp, args: Namespace) -> None: pdf_report_format_id = "c402cc3e-b531-11e1-9163-406186ea4fc5" response = gmp.get_report( - report_id=report_id, report_format_id=pdf_report_format_id, ignore_pagination=True, details=True + report_id=report_id, + report_format_id=pdf_report_format_id, + ignore_pagination=True, + details=True, ) report_element = response.find("report") diff --git a/scripts/export-xml-report.gmp.py b/scripts/export-xml-report.gmp.py index b6cd3fd2..aab6ab9e 100755 --- a/scripts/export-xml-report.gmp.py +++ b/scripts/export-xml-report.gmp.py @@ -8,18 +8,18 @@ from pathlib import Path from gvm.protocols.gmp import Gmp - from gvm.xml import pretty_print + def check_args(args): len_args = len(args.script) - 1 if len_args < 1: message = """ - This script requests the given report and exports it as a xml + This script requests the given report and exports it as a xml file locally. It requires one parameters after the script name. 1. -- ID of the report - + Optional a file name to save the xml in. Example: @@ -44,11 +44,14 @@ def main(gmp: Gmp, args: Namespace) -> None: xml_report_format_id = "5057e5cc-b825-11e4-9d0e-28d24461215b" response = gmp.get_report( - report_id=report_id, report_format_id=xml_report_format_id, ignore_pagination=True, details=True + report_id=report_id, + report_format_id=xml_report_format_id, + ignore_pagination=True, + details=True, ) report_element = response.find("report") - data = pretty_print(report_element) + pretty_print(report_element) # get the full content of the report element content = report_element.find("report_format").tail @@ -70,7 +73,7 @@ def main(gmp: Gmp, args: Namespace) -> None: # write to file and support ~ in filename path xml_path = Path(xml_filename).expanduser() - xml_path.write_bytes(data) + xml_path.write_bytes(binary_xml) print("Done. xml created: " + str(xml_path)) diff --git a/scripts/generate-random-reports.gmp.py b/scripts/generate-random-reports.gmp.py index acc81014..82f6b6ee 100755 --- a/scripts/generate-random-reports.gmp.py +++ b/scripts/generate-random-reports.gmp.py @@ -5,14 +5,13 @@ import json import textwrap from argparse import ArgumentParser, Namespace, RawTextHelpFormatter +from datetime import datetime, timedelta from pathlib import Path from random import choice, gauss, randrange, seed -from datetime import datetime, timedelta from gvm.protocols.gmp import Gmp -from lxml import etree as e - from gvmtools.helper import generate_id, generate_random_ips, generate_uuid +from lxml import etree as e __version__ = "0.3.1" diff --git a/scripts/generate-random-targets.gmp.py b/scripts/generate-random-targets.gmp.py index 165a1269..482a50c9 100644 --- a/scripts/generate-random-targets.gmp.py +++ b/scripts/generate-random-targets.gmp.py @@ -7,7 +7,6 @@ from random import choice, gauss from gvm.protocols.gmp import Gmp - from gvmtools.helper import generate_random_ips diff --git a/scripts/list-alerts.gmp.py b/scripts/list-alerts.gmp.py index 950da1eb..b7f194c9 100755 --- a/scripts/list-alerts.gmp.py +++ b/scripts/list-alerts.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -15,14 +14,21 @@ def main(gmp: Gmp, args: Namespace) -> None: response_xml = gmp.get_alerts(filter_string="rows=-1") alerts_xml = response_xml.xpath("alert") - heading = ["#", "Name", "Id", "Event", "Event type", "Method", "Condition", "In use"] + heading = [ + "#", + "Name", + "Id", + "Event", + "Event type", + "Method", + "Condition", + "In use", + ] rows = [] numberRows = 0 - print( - "Listing alerts.\n" - ) + print("Listing alerts.\n") for alert in alerts_xml: # Count number of reports @@ -42,7 +48,18 @@ def main(gmp: Gmp, args: Namespace) -> None: else: alert_inuse = "No" - rows.append([rowNumber, name, alert_id, alert_event, alert_event_type, alert_method, alert_condition, alert_inuse]) + rows.append( + [ + rowNumber, + name, + alert_id, + alert_event, + alert_event_type, + alert_method, + alert_condition, + alert_inuse, + ] + ) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-credentials.gmp.py b/scripts/list-credentials.gmp.py index 8bd4f719..9988fbd1 100755 --- a/scripts/list-credentials.gmp.py +++ b/scripts/list-credentials.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing credentials.\n" - ) + print("Listing credentials.\n") for credential in credentials_xml: # Count number of reports @@ -51,7 +48,9 @@ def main(gmp: Gmp, args: Namespace) -> None: else: cred_insecureuse = "No" - rows.append([rowNumber, credential_id, name, cred_type, cred_insecureuse]) + rows.append( + [rowNumber, credential_id, name, cred_type, cred_insecureuse] + ) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-feeds.gmp.py b/scripts/list-feeds.gmp.py index bd17355b..adffa24a 100755 --- a/scripts/list-feeds.gmp.py +++ b/scripts/list-feeds.gmp.py @@ -5,24 +5,22 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table -#from gvm.xml import pretty_print +# from gvm.xml import pretty_print + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=unused-argument response_xml = gmp.get_feeds() feeds_xml = response_xml.xpath("feed") - heading = ["#", "Name", "Version", "Status"] + heading = ["#", "Name", "Version", "Type", "Status"] rows = [] numberRows = 0 -# pretty_print(feeds_xml) + # pretty_print(feeds_xml) - print( - "Listing feeds and their status.\n" - ) + print("Listing feeds and their status.\n") for feed in feeds_xml: # Count number of reports @@ -31,15 +29,14 @@ def main(gmp: Gmp, args: Namespace) -> None: rowNumber = str(numberRows) name = "".join(feed.xpath("name/text()")) version = "".join(feed.xpath("version/text()")) - type = "".join(feed.xpath("type/text()")) + feed_type = "".join(feed.xpath("type/text()")) status = "".join(feed.xpath("currently_syncing/timestamp/text()")) if not status: status = "Up-to-date..." else: status = "Update in progress..." - - rows.append([rowNumber, name, version, status]) + rows.append([rowNumber, name, version, feed_type, status]) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-filters.gmp.py b/scripts/list-filters.gmp.py index 9cf15387..7bae83d4 100755 --- a/scripts/list-filters.gmp.py +++ b/scripts/list-filters.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing filters.\n" - ) + print("Listing filters.\n") for filter in filters_xml: # Count number of reports diff --git a/scripts/list-groups.gmp.py b/scripts/list-groups.gmp.py index 3b327b40..d52954ba 100755 --- a/scripts/list-groups.gmp.py +++ b/scripts/list-groups.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing groups.\n" - ) + print("Listing groups.\n") for group in groups_xml: # Count number of reports diff --git a/scripts/list-policies.gmp.py b/scripts/list-policies.gmp.py index 5f65b4e4..7aa03e92 100755 --- a/scripts/list-policies.gmp.py +++ b/scripts/list-policies.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing compliance policies.\n" - ) + print("Listing compliance policies.\n") for policy in policies_xml: # Count number of reports diff --git a/scripts/list-portlists.gmp.py b/scripts/list-portlists.gmp.py index e90e60fd..0733833c 100755 --- a/scripts/list-portlists.gmp.py +++ b/scripts/list-portlists.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing portlists.\n" - ) + print("Listing portlists.\n") for portlist in portlists_xml: # Count number of reports @@ -36,7 +33,9 @@ def main(gmp: Gmp, args: Namespace) -> None: port_tcp = "".join(portlist.xpath("port_count/tcp/text()")) port_udp = "".join(portlist.xpath("port_count/udp/text()")) - rows.append([rowNumber, name, port_list_id, port_all, port_tcp, port_udp]) + rows.append( + [rowNumber, name, port_list_id, port_all, port_tcp, port_udp] + ) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-report-formats.gmp.py b/scripts/list-report-formats.gmp.py index bc2f285b..b2fb62ad 100755 --- a/scripts/list-report-formats.gmp.py +++ b/scripts/list-report-formats.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -18,9 +17,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing report formats.\n" - ) + print("Listing report formats.\n") for report_format in report_formats_xml: # Count number of reports @@ -30,7 +27,6 @@ def main(gmp: Gmp, args: Namespace) -> None: name = "".join(report_format.xpath("name/text()")) report_format_id = report_format.get("id") report_format_summary = "".join(report_format.xpath("summary/text()")) - report_format_description = "".join(report_format.xpath("description/text()")) rows.append([rowNumber, name, report_format_id, report_format_summary]) diff --git a/scripts/list-reports.gmp.py b/scripts/list-reports.gmp.py index 015eddd7..32c8c853 100755 --- a/scripts/list-reports.gmp.py +++ b/scripts/list-reports.gmp.py @@ -2,12 +2,12 @@ # # SPDX-License-Identifier: GPL-3.0-or-later -from gvm.protocols.gmp import Gmp +import sys +from argparse import ArgumentParser, Namespace, RawTextHelpFormatter +from gvm.protocols.gmp import Gmp from gvmtools.helper import Table -from argparse import ArgumentParser, Namespace, RawTextHelpFormatter - HELP_TEXT = ( "This script list reports with the status " "defined on the commandline. Status can be: \n" @@ -31,7 +31,8 @@ def check_args(args): """ print(message) sys.exit() - + + def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument """Parsing args ...""" @@ -52,12 +53,15 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument parser.add_argument( "status_cmd", type=str, - help=("Status: \"All\", \"Queued\", \"Requested\", \"Interrupted\", \"Running\", \"Stop Requested\", \"Stopped\" or \"Done\""), + help=( + 'Status: "All", "Queued", "Requested", "Interrupted", "Running", "Stop Requested", "Stopped" or "Done"' + ), ) script_args, _ = parser.parse_known_args(args) return script_args -def list_reports ( + +def list_reports( gmp: Gmp, status: str, ): @@ -81,17 +85,33 @@ def list_reports ( elif status.upper() == "STOPPED": str_status = "Stopped" else: - str_status="All" + str_status = "All" print("Reports with status: " + str_status + "\n") if str_status == "All": - response_xml = gmp.get_reports(ignore_pagination=True, details=True, filter_string="rows=-1") + response_xml = gmp.get_reports( + ignore_pagination=True, details=True, filter_string="rows=-1" + ) else: - response_xml = gmp.get_reports(ignore_pagination=True, details=True, filter_string="status=" + str_status + " and sort-reverse=name and rows=-1") + response_xml = gmp.get_reports( + ignore_pagination=True, + details=True, + filter_string="status=" + + str_status + + " and sort-reverse=name and rows=-1", + ) reports_xml = response_xml.xpath("report") - heading = ["#", "Id", "Creation Time", "Modification Time", "Task Name", "Status", "Progress"] + heading = [ + "#", + "Id", + "Creation Time", + "Modification Time", + "Task Name", + "Status", + "Progress", + ] rows = [] numberRows = 0 @@ -101,32 +121,40 @@ def list_reports ( # Cast/convert to text to show in list rowNumber = str(numberRows) creation_time = "".join(report.xpath("creation_time/text()")) - #report_name = "".join(report.xpath("name/text()")) # Report name is the same as Creation Time + # report_name = "".join(report.xpath("name/text()")) # Report name is the same as Creation Time report_id = report.get("id") report_task = "".join(report.xpath("task/name/text()")) mod_time = "".join(report.xpath("modification_time/text()")) report_status = "".join(report.xpath("report/scan_run_status/text()")) - report_progress = "".join(report.xpath("report/task/progress/text()")) + "%" - rows.append([rowNumber, report_id, creation_time, mod_time, report_task, report_status, report_progress]) + report_progress = ( + "".join(report.xpath("report/task/progress/text()")) + "%" + ) + rows.append( + [ + rowNumber, + report_id, + creation_time, + mod_time, + report_task, + report_status, + report_progress, + ] + ) print(Table(heading=heading, rows=rows)) + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=unused-argument if args.script: args = args.script[1:] - parsed_args = parse_args(args = args) + parsed_args = parse_args(args=args) - print( - "Listing reports.\n" - ) + print("Listing reports.\n") + + list_reports(gmp, parsed_args.status_cmd) - list_reports ( - gmp, - parsed_args.status_cmd - ) if __name__ == "__gmp__": main(gmp, args) - diff --git a/scripts/list-roles.gmp.py b/scripts/list-roles.gmp.py index 11a0c108..2cba68d6 100755 --- a/scripts/list-roles.gmp.py +++ b/scripts/list-roles.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing roles.\n" - ) + print("Listing roles.\n") for role in roles_xml: # Count number of reports diff --git a/scripts/list-scan-configs.gmp.py b/scripts/list-scan-configs.gmp.py index 4ceccda8..eb0f7c6e 100755 --- a/scripts/list-scan-configs.gmp.py +++ b/scripts/list-scan-configs.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing scan configurations.\n" - ) + print("Listing scan configurations.\n") for scan_config in scan_configs_xml: # Count number of reports diff --git a/scripts/list-scanners.gmp.py b/scripts/list-scanners.gmp.py index f22f4221..868245da 100755 --- a/scripts/list-scanners.gmp.py +++ b/scripts/list-scanners.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing scanners.\n" - ) + print("Listing scanners.\n") for scanner in scanners_xml: # Count number of reports diff --git a/scripts/list-schedules.gmp.py b/scripts/list-schedules.gmp.py index 56280d8b..f504724f 100755 --- a/scripts/list-schedules.gmp.py +++ b/scripts/list-schedules.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing schedules.\n" - ) + print("Listing schedules.\n") for schedule in schedules_xml: # Count number of reports @@ -35,11 +32,10 @@ def main(gmp: Gmp, args: Namespace) -> None: icalendar = "".join(schedule.xpath("icalendar/text()")) timezone = "".join(schedule.xpath("timezone/text()")) rows.append([rowNumber, name, schedule_id, timezone, icalendar]) - #print(icalendar) + # print(icalendar) print(Table(heading=heading, rows=rows)) if __name__ == "__gmp__": main(gmp, args) - diff --git a/scripts/list-tags.gmp.py b/scripts/list-tags.gmp.py index 8ef410a3..8de78c42 100755 --- a/scripts/list-tags.gmp.py +++ b/scripts/list-tags.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing tags.\n" - ) + print("Listing tags.\n") for tag in tags_xml: # Count number of reports diff --git a/scripts/list-targets.gmp.py b/scripts/list-targets.gmp.py index 1dc1bc32..94b8bf3b 100755 --- a/scripts/list-targets.gmp.py +++ b/scripts/list-targets.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -15,14 +14,22 @@ def main(gmp: Gmp, args: Namespace) -> None: response_xml = gmp.get_targets(filter_string="rows=-1") targets_xml = response_xml.xpath("target") - heading = ["#", "Name", "Id", "Count", "SSH Credential", "SMB Cred", "ESXi Cred", "SNMP Cred", "Alive test"] + heading = [ + "#", + "Name", + "Id", + "Count", + "SSH Credential", + "SMB Cred", + "ESXi Cred", + "SNMP Cred", + "Alive test", + ] rows = [] numberRows = 0 - print( - "Listing targets.\n" - ) + print("Listing targets.\n") for target in targets_xml: # Count number of reports @@ -38,7 +45,19 @@ def main(gmp: Gmp, args: Namespace) -> None: snmpcred = "".join(target.xpath("snmp_credential/name/text()")) target_id = target.get("id") alive_test = "".join(target.xpath("alive_tests/text()")) - rows.append([rowNumber, name, target_id, maxhosts, sshcred, smbcred, esxicred, snmpcred, alive_test]) + rows.append( + [ + rowNumber, + name, + target_id, + maxhosts, + sshcred, + smbcred, + esxicred, + snmpcred, + alive_test, + ] + ) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-tasks.gmp.py b/scripts/list-tasks.gmp.py index 7a1e7074..1c9c9cb4 100644 --- a/scripts/list-tasks.gmp.py +++ b/scripts/list-tasks.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing tasks.\n" - ) + print("Listing tasks.\n") for task in tasks_xml: # Count number of reports @@ -36,7 +33,9 @@ def main(gmp: Gmp, args: Namespace) -> None: scanner = "".join(task.xpath("scanner/name/text()")) severity = "".join(task.xpath("last_report/report/severity/text()")) order = "".join(task.xpath("hosts_ordering/text()")) - rows.append([rowNumber, name, task_id, targetname, scanner, order, severity]) + rows.append( + [rowNumber, name, task_id, targetname, scanner, order, severity] + ) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-tickets.gmp.py b/scripts/list-tickets.gmp.py index 15d48240..d664c0f8 100755 --- a/scripts/list-tickets.gmp.py +++ b/scripts/list-tickets.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -15,14 +14,12 @@ def main(gmp: Gmp, args: Namespace) -> None: response_xml = gmp.get_tickets(filter_string="rows=-1") tickets_xml = response_xml.xpath("ticket") - heading = ["#", "Name", "Host", "Task", "Status", "Note"] + heading = ["#", "ID", "Name", "Host", "Task", "Status", "Note"] rows = [] numberRows = 0 - print( - "Listing tickets.\n" - ) + print("Listing tickets.\n") for ticket in tickets_xml: # Count number of reports @@ -42,7 +39,17 @@ def main(gmp: Gmp, args: Namespace) -> None: elif ticket_status.upper() == "CLOSED": ticket_note = "".join(ticket.xpath("closed_note/text()")) - rows.append([rowNumber, name, ticket_host, ticket_task, ticket_status, ticket_note]) + rows.append( + [ + rowNumber, + ticket_id, + name, + ticket_host, + ticket_task, + ticket_status, + ticket_note, + ] + ) print(Table(heading=heading, rows=rows)) diff --git a/scripts/list-users.gmp.py b/scripts/list-users.gmp.py index 6f319ae9..16ded67d 100755 --- a/scripts/list-users.gmp.py +++ b/scripts/list-users.gmp.py @@ -5,7 +5,6 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp - from gvmtools.helper import Table @@ -20,9 +19,7 @@ def main(gmp: Gmp, args: Namespace) -> None: rows = [] numberRows = 0 - print( - "Listing users.\n" - ) + print("Listing users.\n") for user in users_xml: # Count number of reports diff --git a/scripts/scan-new-system.gmp.py b/scripts/scan-new-system.gmp.py index e8f26e67..12098a2a 100644 --- a/scripts/scan-new-system.gmp.py +++ b/scripts/scan-new-system.gmp.py @@ -16,12 +16,12 @@ def check_args(args): It needs one parameters after the script name. 1. IP Address of the host system - 2. Port List UUID for scanning the host system. - Preconfigured UUID might be under - /var/lib/gvm/data-objects/gvmd/20.08/port_lists/. - ex. iana-tcp-udp is + 2. Port List UUID for scanning the host system. + Preconfigured UUID might be under + /var/lib/gvm/data-objects/gvmd/20.08/port_lists/. + ex. iana-tcp-udp is "4a4717fe-57d2-11e1-9a26-406186ea4fc5". - + Example: $ gvm-script --gmp-username name --gmp-password pass \ ssh --hostname scripts/scan-new-system.gmp.py diff --git a/scripts/send-schedules.gmp.py b/scripts/send-schedules.gmp.py index f9249a1c..aa0e70b0 100644 --- a/scripts/send-schedules.gmp.py +++ b/scripts/send-schedules.gmp.py @@ -6,9 +6,8 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp -from lxml.etree import Element - from gvmtools.helper import create_xml_tree +from lxml.etree import Element def check_args(gmp: Gmp, args: Namespace) -> None: diff --git a/scripts/send-targets.gmp.py b/scripts/send-targets.gmp.py index b4124358..72900602 100644 --- a/scripts/send-targets.gmp.py +++ b/scripts/send-targets.gmp.py @@ -6,9 +6,8 @@ from argparse import Namespace from gvm.protocols.gmp import Gmp -from lxml.etree import Element - from gvmtools.helper import create_xml_tree, yes_or_no +from lxml.etree import Element def check_args(args: Namespace) -> None: diff --git a/scripts/send-tasks.gmp.py b/scripts/send-tasks.gmp.py index dcc0e288..5c22943c 100644 --- a/scripts/send-tasks.gmp.py +++ b/scripts/send-tasks.gmp.py @@ -6,13 +6,12 @@ from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from gvm.protocols.gmp import Gmp - from gvmtools.helper import create_xml_tree, error_and_exit, yes_or_no HELP_TEXT = """ This script pulls tasks data from an xml document and feeds it to \ a desired GSM - Usage examples: + Usage examples: $ gvm-script --gmp-username name --gmp-password pass ssh --hostname ... send-task.gmp.py +h ... send-task.gmp.py ++x xml_file diff --git a/scripts/start-scans-from-csv.py b/scripts/start-scans-from-csv.py index 03061c2e..559b170a 100755 --- a/scripts/start-scans-from-csv.py +++ b/scripts/start-scans-from-csv.py @@ -4,23 +4,17 @@ # Run with gvm-script --gmp-username admin-user --gmp-password password socket start-scans-from-csv.gmp.py startscans.csv -import sys -import time import csv -import json - +import sys from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError +from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit -HELP_TEXT = ( - "This script pulls task names from a csv file and starts the tasks listed in every row. \n" -) +HELP_TEXT = "This script pulls task names from a csv file and starts the tasks listed in every row. \n" + def check_args(args): len_args = len(args.script) - 1 @@ -66,55 +60,64 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def task_id( gmp: Gmp, task_name: str, ): - response_xml = gmp.get_tasks(filter_string="rows=-1, not status=Running and " + response_xml = gmp.get_tasks( + filter_string="rows=-1, not status=Running and " "not status=Requested and not " "status=Queued " - "and name=" + task_name) + "and name=" + task_name + ) tasks_xml = response_xml.xpath("task") task_id = "" for task in tasks_xml: - name = "".join(task.xpath("name/text()")) task_id = task.get("id") - #print("Requesting start of task: " + task_name + " Task UUID: " + task_id) return task_id -def start_tasks( + +def start_tasks( gmp: Gmp, task_file: Path, ): try: numbertasks = 0 with open(task_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data + content = csv.reader(csvFile, delimiter=",") # read the data try: - for row in content: #loop through each row + for row in content: # loop through each row if len(row) == 0: continue task_start = task_id(gmp, row[0]) if task_start: numbertasks = numbertasks + 1 - print(f"Starting task name: {row[0]} with uuid: {task_start} ...") + print( + f"Starting task name: {row[0]} with uuid: {task_start} ..." + ) status_text = gmp.start_task(task_start).xpath( - "@status_text" + "@status_text" )[0] print(status_text) else: - print("Task " + row[0] + " is either in status Requested, Queued, Running, or does not exist on this system.\n") + print( + "Task " + + row[0] + + " is either in status Requested, Queued, Running, or does not exist on this system.\n" + ) except GvmResponseError as gvmerr: print(f"{gvmerr=}, task: {task_start}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read task_file: {str(e)} (exit)") - + return numbertasks - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: @@ -122,9 +125,7 @@ def main(gmp: Gmp, args: Namespace) -> None: parsed_args = parse_args(args=args) - print( - "Starting tasks.\n" - ) + print("Starting tasks.\n") numbertasks = start_tasks( gmp, @@ -134,5 +135,6 @@ def main(gmp: Gmp, args: Namespace) -> None: numbertasks = str(numbertasks) print(" \n [" + numbertasks + "] task(s)/scan(s) started!\n") + if __name__ == "__gmp__": main(gmp, args) diff --git a/scripts/stop-all-scans.gmp.py b/scripts/stop-all-scans.gmp.py index 0556b8cb..be245374 100755 --- a/scripts/stop-all-scans.gmp.py +++ b/scripts/stop-all-scans.gmp.py @@ -6,29 +6,26 @@ from gvm.protocols.gmp import Gmp -from gvmtools.helper import Table def stop_tasks(gmp: Gmp) -> None: tasks = gmp.get_tasks( - filter_string="rows=-1 status=Running or status=Requested or status=Queued" - ) + filter_string="rows=-1 status=Running or status=Requested or status=Queued" + ) try: for task_id in tasks.xpath("task/@id"): print(f"Stopping task {task_id} ... ") - gmp.stop_task(task_id).xpath( - "@status_text" - )[0] + status_text = gmp.stop_task(task_id).xpath("@status_text")[0] print(status_text) - except: - pass + except Exception as e: + print(f"{e=}") + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable - print( - "This script stops all tasks on the system.\n" - ) + print("This script stops all tasks on the system.\n") stop_tasks(gmp) - + + if __name__ == "__gmp__": main(gmp, args) diff --git a/scripts/stop-scans-from-csv.py b/scripts/stop-scans-from-csv.py index c17dcb2f..40e3d86d 100755 --- a/scripts/stop-scans-from-csv.py +++ b/scripts/stop-scans-from-csv.py @@ -4,23 +4,17 @@ # Run with gvm-script --gmp-username admin-user --gmp-password password socket start-scans-from-csv.gmp.py startscans.csv -import sys -import time import csv -import json - +import sys from argparse import ArgumentParser, Namespace, RawTextHelpFormatter from pathlib import Path -from typing import List -from gvm.errors import GvmResponseError +from gvm.errors import GvmResponseError from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit -HELP_TEXT = ( - "This script pulls task names from a csv file and starts the tasks listed in every row. \n" -) +HELP_TEXT = "This script pulls task names from a csv file and starts the tasks listed in every row. \n" + def check_args(args): len_args = len(args.script) - 1 @@ -66,58 +60,67 @@ def parse_args(args: Namespace) -> Namespace: # pylint: disable=unused-argument script_args, _ = parser.parse_known_args(args) return script_args + def task_id( gmp: Gmp, task_name: str, ): - response_xml = gmp.get_tasks(filter_string="rows=-1, status=Running " + response_xml = gmp.get_tasks( + filter_string="rows=-1, status=Running " "or status=Requested " "or status=Queued " - "and name=" + task_name) + "and name=" + task_name + ) tasks_xml = response_xml.xpath("task") task_id = "" for task in tasks_xml: - name = "".join(task.xpath("name/text()")) task_id = task.get("id") - #print("Requesting stop of task: " + task_name + " Task UUID: " + task_id) return task_id -def stop_tasks( + +def stop_tasks( gmp: Gmp, task_file: Path, ): try: numbertasks = 0 with open(task_file, encoding="utf-8") as csvFile: - content = csv.reader(csvFile, delimiter=',') #read the data + content = csv.reader(csvFile, delimiter=",") # read the data try: - for row in content: #loop through each row + for row in content: # loop through each row if len(row) == 0: continue task_stop = task_id(gmp, row[0]) if task_stop: numbertasks = numbertasks + 1 - print(f"Stopping task name: {row[0]} with uuid: {task_stop} ...") + print( + f"Stopping task name: {row[0]} with uuid: {task_stop} ..." + ) status_text = gmp.stop_task(task_stop).xpath( - "@status_text" + "@status_text" )[0] print(status_text) else: - print("Task " + row[0] + " is either in status Stopped, Stop Requested, or does not exist on this system.\n") + print( + "Task " + + row[0] + + " is either in status Stopped, Stop Requested, or does not exist on this system.\n" + ) except GvmResponseError as gvmerr: print(f"{gvmerr=}, task: {task_stop}") pass - csvFile.close() #close the csv file + csvFile.close() # close the csv file except IOError as e: error_and_exit(f"Failed to read task_file: {str(e)} (exit)") if len(row) == 0: error_and_exit("tasks file is empty (exit)") - + return numbertasks - + + def main(gmp: Gmp, args: Namespace) -> None: # pylint: disable=undefined-variable if args.script: @@ -125,9 +128,7 @@ def main(gmp: Gmp, args: Namespace) -> None: parsed_args = parse_args(args=args) - print( - "Stopping tasks.\n" - ) + print("Stopping tasks.\n") numbertasks = stop_tasks( gmp, @@ -137,5 +138,6 @@ def main(gmp: Gmp, args: Namespace) -> None: numbertasks = str(numbertasks) print(" \n [" + numbertasks + "] task(s)/scan(s) stopped!\n") + if __name__ == "__gmp__": main(gmp, args) diff --git a/scripts/update-task-target.gmp.py b/scripts/update-task-target.gmp.py index a4a125bb..645bc04f 100644 --- a/scripts/update-task-target.gmp.py +++ b/scripts/update-task-target.gmp.py @@ -7,7 +7,6 @@ from typing import List from gvm.protocols.gmp import Gmp - from gvmtools.helper import error_and_exit HELP_TEXT = (