暫無描述

createTargers.py 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import csv
  2. from gvm.connections import TLSConnection
  3. from gvm.protocols.gmp import Gmp
  4. from gvm.transforms import EtreeTransform
  5. # OpenVAS Configuration
  6. OPENVAS_HOST = "localhost"
  7. OPENVAS_PORT = 9390
  8. USERNAME = "admin"
  9. PASSWORD = "admin"
  10. # CSV files
  11. ACTIVE_HOSTS_CSV = "active_hosts.csv"
  12. TARGET_ID_CSV = "target_id.csv"
  13. def get_port_list_id(gmp):
  14. """
  15. Retrieve a valid port list ID.
  16. """
  17. port_lists = gmp.get_port_lists()
  18. default_port_list_id = None
  19. for port_list in port_lists.findall("port_list"):
  20. name = port_list.find("name").text
  21. port_list_id = port_list.get("id")
  22. print(f"Port List: {name} (ID: {port_list_id})")
  23. if "OpenVAS Default" in name:
  24. default_port_list_id = port_list_id
  25. # If "OpenVAS Default" is not found, use the first available port list
  26. if not default_port_list_id and port_lists:
  27. default_port_list_id = port_lists.find("port_list").get("id")
  28. print(f"'OpenVAS Default' not found. Using the first available port list with ID: {default_port_list_id}")
  29. return default_port_list_id
  30. def target_exists(gmp, ip):
  31. """
  32. Check if a target already exists for the given IP and return its target_id if it does.
  33. """
  34. targets = gmp.get_targets()
  35. for target in targets.findall("target"):
  36. if target.find("hosts").text == ip:
  37. target_id = target.get("id")
  38. print(f"Target for IP {ip} already exists with ID: {target_id}")
  39. return target_id
  40. return None
  41. def create_target(gmp, name, ip, port_list_id):
  42. """
  43. Create a target in OpenVAS.
  44. """
  45. response = gmp.create_target(name=name, hosts=ip, port_list_id=port_list_id)
  46. target_id = response.get("id")
  47. if target_id:
  48. print(f"Created target '{name}' for IP '{ip}' with ID: {target_id}")
  49. else:
  50. print(f"Failed to create target for IP {ip}. Check logs.")
  51. return target_id
  52. def save_target_id_to_csv(ip, target_id):
  53. """
  54. Save the target ID to the target_id.csv file if it's not already there.
  55. """
  56. existing_data = []
  57. try:
  58. # Read existing data from the CSV
  59. with open(TARGET_ID_CSV, "r", newline="") as csvfile:
  60. reader = csv.reader(csvfile)
  61. existing_data = list(reader)
  62. except FileNotFoundError:
  63. # If the file doesn't exist, it will be created later
  64. pass
  65. # Check if the IP is already in the CSV
  66. for row in existing_data:
  67. if row[0] == ip:
  68. print(f"IP {ip} already recorded in {TARGET_ID_CSV}")
  69. return
  70. # Append the new target ID to the CSV
  71. with open(TARGET_ID_CSV, "a", newline="") as csvfile:
  72. writer = csv.writer(csvfile)
  73. writer.writerow([ip, target_id])
  74. print(f"Saved target ID {target_id} for IP {ip} to {TARGET_ID_CSV}")
  75. def read_csv_to_ip_list(csv_file):
  76. """
  77. Read the CSV file and extract IPs into a list.
  78. """
  79. ip_list = []
  80. with open(csv_file, newline="") as csvfile:
  81. reader = csv.DictReader(csvfile)
  82. for row in reader:
  83. ip_list.append(row["IP"])
  84. return ip_list
  85. def main():
  86. connection = TLSConnection(hostname=OPENVAS_HOST, port=OPENVAS_PORT)
  87. with Gmp(connection=connection, transform=EtreeTransform()) as gmp:
  88. # Authenticate with OpenVAS
  89. gmp.authenticate(username=USERNAME, password=PASSWORD)
  90. print("Authenticated with OpenVAS")
  91. # Get a valid port list ID
  92. port_list_id = get_port_list_id(gmp)
  93. if not port_list_id:
  94. print("Failed to retrieve a valid port list. Exiting.")
  95. return
  96. # Read IPs from the active hosts CSV
  97. ip_list = read_csv_to_ip_list(ACTIVE_HOSTS_CSV)
  98. if not ip_list:
  99. print("No IPs found in the CSV file. Exiting.")
  100. return
  101. print(f"Found {len(ip_list)} active hosts.")
  102. # Process each IP
  103. for ip in ip_list:
  104. print(f"Processing IP: {ip}")
  105. # Check if target already exists
  106. target_id = target_exists(gmp, ip)
  107. if target_id:
  108. # Save the existing target ID to the CSV if not already recorded
  109. save_target_id_to_csv(ip, target_id)
  110. continue
  111. # Create target if it doesn't exist
  112. target_name = f"Target for {ip}"
  113. target_id = create_target(gmp, target_name, [ip], port_list_id)
  114. if target_id:
  115. save_target_id_to_csv(ip, target_id)
  116. else:
  117. print(f"Failed to create target for IP {ip}. Continuing.")
  118. if __name__ == "__main__":
  119. # Ensure the target_id.csv file exists with headers
  120. try:
  121. with open(TARGET_ID_CSV, "x", newline="") as csvfile:
  122. writer = csv.writer(csvfile)
  123. writer.writerow(["IP", "Target ID"]) # Write headers if the file doesn't exist
  124. except FileExistsError:
  125. pass # File already exists, no need to create
  126. main()