Generates filenames for all scans that don't already have a filename.
00291 : """Generates filenames for all scans that don't already have a filename.""" # The directory must not contain filenames other than those in the self.filenames dictionary for filename in os.listdir(path): if os.path.basename(filename) not in self.filenames.values(): raise Exception("The destination directory contains a file (%s) that's not a part " "of the current inventory. The inventory will not be saved." % os.path.basename(filename)) for scan in self.scans: if scan in self.filenames: # This scan already has a filename continue date = "%04d%02d%02d%02d%02d" % (scan.date, scan.date, scan.date, scan.date, scan.date) if scan.profile_name != "": filename = "%s on %s" % (scan.profile_name, scan.target) else: filename = scan.nmap_command # Prepend the date filename = "%s %s" % (date, filename) # Sanitize the filename for char in ["\"", "'", "/", "\\", "?", "*", ":", ";"]: if char in filename: filename = filename.replace(char, "_") # Filename length check # (http://en.wikipedia.org/wiki/Filename#Comparison_of_file_name_limitations) if len(filename) > 250: filename = filename[:250] # TODO: Filename security checks? # Try to open the file in append mode. If file.tell() returns a greater-than-zero # value, this means that the file already exists and has some data in it, so we # choose another filename until we successfully open a zero-length file. filename_full = filename + ".xml" counter = 2 while filename_full in self.filenames.values(): # There's already a scan with this filename, so we generate a new name by appending # the counter value before the file extension. filename_full = "%s %s.xml" % (filename, str(counter)) counter += 1 # Add the filename to the list of saved filenames self.filenames[scan] = filename_full def save_to_dir(self, path):