This commit is contained in:
2025-08-04 13:04:42 -04:00
parent 13ea5bbf8b
commit af9bb2374f
26 changed files with 613 additions and 968 deletions
-2
View File
@@ -1,2 +0,0 @@
# chapter 3
Locard's principle of transferrence
Submodule DavidsDevelopment deleted from db7cc92e66
-48
View File
@@ -1,48 +0,0 @@
import os
from markdown import markdown
from docx import Document
def convert_md_to_docx(md_file_path, docx_file_path):
"""Converts a Markdown file to a Word document."""
with open(md_file_path, 'r', encoding='utf-8') as md_file:
md_content = md_file.read()
# Convert Markdown to HTML
html_content = markdown(md_content)
# Create a Word document and add the HTML content
doc = Document()
doc.add_paragraph(html_content)
doc.save(docx_file_path)
print(f"Converted: {md_file_path} -> {docx_file_path}")
def convert_all_md_to_docx(root_directory, output_directory):
"""Traverse the directory tree and convert all .md files to .docx, storing them in a mirrored structure."""
for dirpath, dirnames, filenames in os.walk(root_directory):
for filename in filenames:
if filename.endswith('.md'):
md_file_path = os.path.join(dirpath, filename)
# Create mirrored directory structure in the output directory
relative_path = os.path.relpath(dirpath, root_directory)
target_dir = os.path.join(output_directory, relative_path)
os.makedirs(target_dir, exist_ok=True)
# Define the output .docx file path
docx_file_path = os.path.join(target_dir, os.path.splitext(filename)[0] + '.docx')
try:
convert_md_to_docx(md_file_path, docx_file_path)
except Exception as e:
print(f"Failed to convert {md_file_path}: {e}")
if __name__ == "__main__":
# Prompt user for the root directory and output directory
root_dir = input("Enter the root directory to scan for Markdown files: ").strip()
output_dir = input("Enter the output directory to store converted files: ").strip()
if os.path.exists(root_dir):
os.makedirs(output_dir, exist_ok=True) # Ensure output directory exists
convert_all_md_to_docx(root_dir, output_dir)
else:
print("The specified root directory does not exist.")
-48
View File
@@ -1,48 +0,0 @@
import os
from markdown import markdown
from docx import Document
def convert_md_to_docx(md_file_path, docx_file_path):
"""Converts a Markdown file to a Word document."""
with open(md_file_path, 'r', encoding='utf-8') as md_file:
md_content = md_file.read()
# Convert Markdown to HTML
html_content = markdown(md_content)
# Create a Word document and add the HTML content
doc = Document()
doc.add_paragraph(html_content)
doc.save(docx_file_path)
print(f"Converted: {md_file_path} -> {docx_file_path}")
def convert_all_md_to_docx(root_directory, output_directory):
"""Traverse the directory tree and convert all .md files to .docx, storing them in a mirrored structure."""
for dirpath, dirnames, filenames in os.walk(root_directory):
for filename in filenames:
if filename.endswith('.md'):
md_file_path = os.path.join(dirpath, filename)
# Create mirrored directory structure in the output directory
relative_path = os.path.relpath(dirpath, root_directory)
target_dir = os.path.join(output_directory, relative_path)
os.makedirs(target_dir, exist_ok=True)
# Define the output .docx file path
docx_file_path = os.path.join(target_dir, os.path.splitext(filename)[0] + '.docx')
try:
convert_md_to_docx(md_file_path, docx_file_path)
except Exception as e:
print(f"Failed to convert {md_file_path}: {e}")
if __name__ == "__main__":
# Prompt user for the root directory and output directory
root_dir = input("Enter the root directory to scan for Markdown files: ").strip()
output_dir = input("Enter the output directory to store converted files: ").strip()
if os.path.exists(root_dir):
os.makedirs(output_dir, exist_ok=True) # Ensure output directory exists
convert_all_md_to_docx(root_dir, output_dir)
else:
print("The specified root directory does not exist.")
+149
View File
@@ -0,0 +1,149 @@
import nvdlib
from datetime import datetime, timedelta
import pandas as pd
def get_latest_cves(days_ago=3, api_key=None):
"""
Fetches the latest CVEs registered by NIST over the past N days.
Args:
days_ago (int): The number of days back from today to search for CVEs.
api_key (str, optional): Your NVD API key. Defaults to None.
Returns:
list: A list of dictionaries, each representing a CVE with relevant details.
"""
end_date = datetime.now(tz=None)
start_date = end_date - timedelta(days=days_ago)
# Format dates to ISO-8601 for the NVD API
pub_start_date = start_date.isoformat(timespec='seconds') + 'Z'
pub_end_date = end_date.isoformat(timespec='seconds') + 'Z'
print(f"Searching for CVEs published between {pub_start_date} and {pub_end_date}...")
cve_data = []
try:
# The NVD API has a limit on the number of results per page and date range.
# We'll use pagination to retrieve all results within the date range.
# The 'lastModStartDate' and 'lastModEndDate' parameters are for when a CVE was last modified.
# We are interested in 'pubStartDate' and 'pubEndDate' for newly registered CVEs.
results = nvdlib.searchCVE(
pubStartDate=pub_start_date,
pubEndDate=pub_end_date,
key=api_key,
delay=6 if not api_key else 0, # Add delay if no API key is provided
results_per_page=2000 # Max results per page
)
for cve in results:
cve_id = cve.id
published_date = cve.published
last_modified_date = cve.lastModified
# Description
description = "No description available."
if cve.descriptions:
for desc in cve.descriptions:
if desc.lang == 'en':
description = desc.value
break
# Source (often derived from the first reference or CNA)
source = "N/A"
if cve.cve:
if cve.cve.sourceIdentifier:
source = cve.cve.sourceIdentifier
elif cve.cve.CVE_data_meta and cve.cve.CVE_data_meta.ASSIGNER:
source = cve.cve.CVE_data_meta.ASSIGNER
# Vulnerability Status (not directly available as a single field, infer from analysis status)
# The NVD API v2.0 doesn't expose a direct "Vulnerability Status" field
# like "Undergoing Analysis" or "Analyzed". We can infer based on the presence
# of CVSS scores or other enrichment. For simplicity, we'll assume "Analyzed" if CVSS exists.
vulnerability_status = "Unknown"
if cve.vulnStatus:
vulnerability_status = cve.vulnStatus
elif cve.metrics and (cve.metrics.cvssMetricV31 or cve.metrics.cvssMetricV2):
vulnerability_status = "Analyzed (CVSS available)"
else:
vulnerability_status = "Awaiting Analysis"
# CVSS Score
cvss_score = "N/A"
if cve.metrics and cve.metrics.cvssMetricV31:
cvss_score = cve.metrics.cvssMetricV31[0].cvssData.baseScore
elif cve.metrics and cve.metrics.cvssMetricV2:
cvss_score = cve.metrics.cvssMetricV2[0].cvssData.baseScore
# Products (CPEs)
products = []
if cve.configurations:
for config in cve.configurations:
if config.nodes:
for node in config.nodes:
if node.cpeMatch:
for cpe_match in node.cpeMatch:
products.append(cpe_match.criteria)
cve_data.append({
"CVE-ID": cve_id,
"Source": source,
"Published Date": published_date,
"Last Modified Date": last_modified_date,
"Vulnerability Status": vulnerability_status,
"Description": description,
"Product": "\n".join(products) if products else "N/A",
"CVSS Score": cvss_score
})
except nvdlib.NVDAPIError as e:
print(f"Error fetching CVEs: {e}")
print("Please check your API key and try again, or consider adding a delay if not using an API key.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
return cve_data
def generate_report(cve_list):
"""
Generates a formatted report from the list of CVE data.
Args:
cve_list (list): A list of dictionaries, each representing a CVE.
"""
if not cve_list:
print("No new CVEs found for the specified period.")
return
df = pd.DataFrame(cve_list)
# Reorder columns for the report
report_columns = [
"CVE-ID",
"Source",
"Published Date",
"Last Modified Date",
"Vulnerability Status",
"Description",
"Product",
"CVSS Score"
]
df = df[report_columns]
print("\n--- Latest NIST CVE Report ---")
print(df.to_string(index=False)) # Use to_string for full display without truncation
# You can also save this to a CSV or other formats
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_filename = f"nist_cve_report_{timestamp}.csv"
df.to_csv(output_filename, index=False)
print(f"\nReport saved to {output_filename}")
if __name__ == "__main__":
# Replace 'YOUR_NVD_API_KEY' with your actual API key if you have one
# If you don't have one, leave it as None, but be aware of rate limits.
NVD_API_KEY = None
#2586b8ea-afbb-4309-9853-311f161f5568
cves = get_latest_cves(days_ago=3, api_key=NVD_API_KEY)
generate_report(cves)
Binary file not shown.
Binary file not shown.
@@ -1,63 +1,63 @@
s1 = [2, 1, 4, 3] s1 = [2, 1, 4, 3]
s2 = ["c","a","b"] s2 = ["c","a","b"]
print("------------Discussion Part 1----------") print("------------Discussion Part 1----------")
# s1 + s2 # s1 + s2
print("-----s1 + s2-----") print("-----s1 + s2-----")
print(s1 + s2) print(s1 + s2)
print()
#b) 3 * s1 + 2 * s2 #b) 3 * s1 + 2 * s2
print("--------3 * s1 + 2 * s2-----") print("--------3 * s1 + 2 * s2-----")
print(3 * s1 + 2 * s2) print(3 * s1 + 2 * s2)
print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}")
print() print()
#c) s1[1] #c) s1[1]
print("--------s1[1]-----") print("--------s1[1]-----")
print(s1[1]) print(s1[1])
print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}")
print() print()
#d) s1[1:3] #d) s1[1:3]
print("--------s1[1:3]-----") print("--------s1[1:3]-----")
print(s1[1:3]) print(s1[1:3])
print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}")
print() print()
#e) s1 + s2[-1] #e) s1 + s2[-1]
print("--------s1[1:3]------") print("--------s1 + [s2[-1]])------")
print(s1 + [s2[-1]]) print(s1 + [s2[-1]])
print() print()
print("------------Discussion Part 2----------") print("------------Discussion Part 2----------")
#a)s1.remove(2) #a)s1.remove(2)
print("s1.remove(2)")
print(s1.remove(2)) print(s1.remove(2))
print(f"This is the value of s1: {s1}") print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}") print(f"This is the value of s2: {s2}")
print() print()
#b)s1.sort() #b)s1.sort()
print("s1.sort()")
print(s1.sort()) print(s1.sort())
print(f"This is the value of s1: {s1}") print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}") print(f"This is the value of s2: {s2}")
print() print()
#c)s1.append([s2.index("b")] #c)s1.append([s2.index("b")]
print("s1.append([s2.index("'b'")])")
print(s1.append([s2.index("b")])) print(s1.append([s2.index("b")]))
print(f"This is the value of s1: {s1}") print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}") print(f"This is the value of s2: {s2}")
print() print()
#d)s2.pop(s1.pop(0)) #d)s2.pop(s1.pop(0))
print("s2.pop(s1.pop(0))")
print(s2.pop(s1.pop(0))) print(s2.pop(s1.pop(0)))
print(f"This is the value of s1: {s1}") print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}") print(f"This is the value of s2: {s2}")
print() print()
#e)s2.insert(s1[1], "d" #e)s2.insert(s1[1], "d")
print("s2.insert(s1[1], "'d'")")
print(s2.insert(s1[1], "d")) print(s2.insert(s1[1], "d"))
print(f"This is the value of s1: {s1}") print(f"This is the value of s1: {s1}")
print(f"This is the value of s2: {s2}") print(f"This is the value of s2: {s2}")
@@ -0,0 +1,114 @@
import random
def makedeck():
ranks = list(range(2, 11)) + ['J', 'Q', 'K', 'A']
suits = ['h', 'd', 'c', 's']
deck = [(rank, suit) for suit in suits for rank in ranks]
return deck
def shuffledeck(deck):
random.shuffle(deck)
return deck
def dealcard(deck):
return deck.pop()
def straight_flush(hand):
return flush(hand) and straight(hand)
def four_of_a_kind(hand):
ranks = [card[0] for card in hand]
return any(ranks.count(rank) == 4 for rank in ranks)
def fullhouse(hand):
ranks = [card[0] for card in hand]
rank_counts = {rank: ranks.count(rank) for rank in set(ranks)}
return 3 in rank_counts.values() and 2 in rank_counts.values()
def flush(hand):
suits = [card[1] for card in hand]
return len(set(suits)) == 1
def straight(hand):
rank_order = {str(k): k for k in range(2, 11)}
rank_order.update({'J': 11, 'Q': 12, 'K': 13, 'A': 14})
ranks = sorted(rank_order[str(card[0])] for card in hand)
return all(ranks[i + 1] - ranks[i] == 1 for i in range(len(ranks) - 1))
def three_of_a_kind(hand):
ranks = [card[0] for card in hand]
return any(ranks.count(rank) == 3 for rank in ranks)
def two_pair(hand):
ranks = [card[0] for card in hand]
unique_pairs = [rank for rank in set(ranks) if ranks.count(rank) == 2]
return len(unique_pairs) == 2
def pair(hand):
ranks = [card[0] for card in hand]
return any(ranks.count(rank) == 2 for rank in ranks)
def testhands():
hand1 = [(2, 'h'), (3, 'h'), (4, 'h'), (5, 'h'), (6, 'h')] # Straight flush
hand2 = [(10, 'c'), (10, 'd'), (10, 'h'), (10, 's'), (2, 'h')] # Four of a kind
hand3 = [(10, 'c'), (10, 'd'), (10, 'h'), (2, 's'), (2, 'h')] # Full house
hand4 = [(2, 'h'), (4, 'h'), (6, 'h'), (8, 'h'), (10, 'h')] # Flush
hand5 = [(2, 'h'), (3, 'd'), (4, 'c'), (5, 's'), (6, 'h')] # Straight
hand6 = [(10, 'c'), (10, 'd'), (10, 'h'), (2, 's'), (3, 'h')] # Three of a kind
hand7 = [(10, 'c'), (10, 'd'), (2, 's'), (2, 'h'), (3, 'h')] # Two pair
hand8 = [(10, 'c'), (10, 'd'), (2, 's'), (3, 'h'), (4, 'h')] # Pair
print("-------------------This is a test case -----------------------")
print(f"Hand 1 Straight Flush: {straight_flush(hand1)}") # True
print(f"Hand 2 Four of a Kind: {four_of_a_kind(hand2)}") # True
print(f"Hand 3 Full House: {fullhouse(hand3)}") # True
print(f"Hand 4 Flush: {flush(hand4)}") # True
print(f"Hand 5 Straight: {straight(hand5)}") # True
print(f"Hand 6 Three of a Kind: {three_of_a_kind(hand6)}") # True
print(f"Hand 7 Two Pair: {two_pair(hand7)}") # True
print(f"Hand 8 Pair: {pair(hand8)}") # True
def discussion1():
cards_per_hand = 5
#First assignment printout
fulldeck = makedeck()
print("Full Deck: ")
for card in fulldeck:
print(f"Card: {card}")
#Ask how many players
while True:
try:
num_hands = int(input('How many players are there? '))
if num_hands > 0:
print(f"The number of players is {num_hands} players")
break
else:
print('Please enter a positive number of players')
except ValueError:
print('Please enter a number of players instead.')
#Create a list of hand values
hands = [[] for _ in range(num_hands)]
#Deal the cards
for round_nm in range(1):
shuffled_deck = shuffledeck(fulldeck)
print(f"Round {round_nm + 1}:")
for hand_index in range(num_hands): # Iterate through each hand
print(f"Hand {hand_index + 1}:")
for card_num in range(cards_per_hand): # Deal cards to the current hand
card = shuffled_deck.pop()
hands[hand_index].append(card)
print(hands[hand_index])
def main():
discussion1()
testhands()
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
# sumnN(n) returns the sum of the first n natural numbers.
# sumNCubes(n) returns the sum of the cubes of the first n natural numbers.
# Then use these functions in a program that prompts a user for an n and prints out the sum of the first n natural numbers and the sub of the cubes of the first n natural numbers.
# What the heck is a natural number?
# number that is positive and whole
# Prompt function
def prompt():
promptresponse = int(input("Please enter a number for n:"))
return promptresponse
def sumN(n):
sum = 0 #initialize sum for use
print("Let's show the work for the sum of the natural numbers:\n")
for i in range(1,n+1): # start building the natural numbers leading up to n.
sum += i
if sum != n+1:
string_concatenate = f"{i} + " # concatenate the string to show the user the sum
else:
string_concatenate = f"{i}"
print(string_concatenate, end="") # print the string
print(f" = {sum}") # print the sum
return sum # return the sum to the function
def sumNCubes(n):
sum = 0 #initialize sum for use
for i in range(1,n+1): # start building the natural numbers leading up to n.
sum += i**3 # add the cube of the number to the sum
if sum!=n+1:
string_concatenate = f"{i}^3 + "
else:
string_concatenate = f"{i}^3"
print(string_concatenate, end="") # print the string
return sum # return the sum to the function
# Main Function
def main():
# Prompt the user for n.
n=prompt()
print(f"The sum for sumN of the 'natural numbers is': {sumN(n)}")
print(f"The sum for sumN of the 'natural numbers is': {sumNCubes(n)}")
# Ask the user to see if they want to continue
continueprompt = input("Would you like to continue? (y/n)")
if continueprompt == "y":
main()
else:
print("Goodbye!")
if __name__ == "__main__":
main()
@@ -0,0 +1,79 @@
# Implement a class to represent a playing card. Your class should have the following methods:
# __init__(self, rank, suit) rank is an integer from 1 to 13, indicating the suit (diamonds, clubs, hearts or spades).
# Create the corresponding card.
# getRank(self) returns the rank of the card.
# getSuit(self) Returns the sute of the card
#value(self) Returns the blackjack value of a card. Ace counts as 1, ace cards count as 10.
#__str__(self) Returns a string that names the card. For example, "Ace of Spades".
#Note: A method named __str__ is special in Python. If asked to convert an object into a string, python uses this method, if it's present. For example,
# c = Card(1,"s")
# print callable
# will print "Ace of Spades"
#Test your card class with a program that prints out n randomly generated cards and the associated blackjack value where n is a number supplied by the user.
import random
class PlayingCard:
def __init__(self, rank, suit): #initialize the rank and suit of the card object
self.rank = rank #assign the rank to the card object
self.suit = suit #assign the suit to the card
def getRank(self):
return self.rank #return the rank of the card
def getSuit(self):
return self.suit #return the suit of the card
def value(self):
if self.rank == 1: #if the rank of the card is 1, return 1
return 1
elif self.rank > 10: #if the rank of the card is greater than 10, return 10
return 10
else:
return self.rank #return the rank of the card
def __str__(self):
if self.rank == 1:
rank = "Ace"
elif self.rank == 11:
rank = "Jack"
elif self.rank == 12:
rank = "Queen"
elif self.rank == 13:
rank = "King"
else:
rank = self.rank
if self.suit == "d":
suit = "Diamonds"
elif self.suit == "c":
suit = "Clubs"
elif self.suit == "h":
suit = "Hearts"
elif self.suit == "s":
suit = "Spades"
return f"{rank} of {suit}"
def main():
while True:
try:
n = int(input("Enter the number of cards: ")) # ask the user to choose how many cards to "draw"
for i in range(n): # loop through the number of card the user has selected to draw
rank = random.randint(1, 13) #randomly generate the rank of the card in n round between 1 and 13
suit = random.choice("dchs") #randomly generate the suite of the card in n round between d, c, h, s
card = PlayingCard(rank, suit) # assign the previously generated values to the card object and create the card by calling the class and passing the rank and suit as arguments and assign it to the card variable and create the card object and assign it to the card variable and create the card object and assign it to the card variable
print(f"Card: {card}, Value of Card: {card.value()}") # print out the card tuple and the value of the card
except ValueError:
print("Please enter a valid number")
except:
print("An error occured")
if __name__ == "__main__":
main()
@@ -0,0 +1,39 @@
# Write an automated censor program that reads in the text from a file and creates a new file where all of the four letter words have been replaced by "****". You can ignore punctuation and you may assume that no words in the file are split across multiple lines.
import os
def Censor_Words(input_file, output_file):
print(f"Censoring words in file: , {input_file} and writing them to {output_file}\n")
#check if output file exists and if not then create it
if not os.path.exists(output_file):
open(output_file, 'w').close()
else:
print(f"{output_file} already exists. Overwriting it.\n")
try: # try to open the file and write to the output file
with open(input_file, 'r') as f: # open the file, using r to read read it
text = f.read() # read the file
words = text.split() # split up the words
for i in range(len(words)): # loop through the words. Len(words) gives the number of words in the list
if len(words[i]) == 4: # if the word is 4 characters, then replace it with ****
print(f"Word {words[i]} censored.\n") #output the word that was censored for troubleshooting.
words[i] = "****"
with open(output_file, 'w') as f: # open the output file, using w to write to it
f.write(" ".join(words))
print("Censoring document complete. Results found in output.txt\n")
except FileNotFoundError:
print("File wasn't found.")
except:
print("An error occurred.")
def __main__():
script_directory = os.path.dirname(os.path.abspath(__file__)) # get the directory of the script
input_file = os.path.join(script_directory, "input.txt") #had to use os.path.join to get the correct path. Wasn't working with just the file name
output_file = os.path.join(script_directory, "output.txt") # had to use the os.path.join to get the correct path dynamically. Wasn't working with just the file name
print(f"Input file: {input_file}\n, Output file: {output_file}\n") # troubleshooting the file name issues. Show the input and output in console.
Censor_Words(input_file, output_file) # call the function to start censoring
if __name__ == "__main__":
__main__() # call the main function and get things started.
@@ -0,0 +1,123 @@
# Week 8 - Lab: Python Program
# Assignment Value: 10 points
# Description:
# Create a Python program that demonstrates exception handling.
# Your program should include at least three custom-defined exceptions and handle them appropriately.
# Implement try-except blocks to handle exceptions and provide meaningful error messages.
# Test your program with various scenarios to ensure proper exception handling.
# Instructions:
# Create a Python script named exception_handling.py.
# Define three custom exceptions: CustomError1, CustomError2, and CustomError3.
# Implement a function divide_numbers() that takes two numbers as input and returns the result of dividing the first number by the second number.
# Handle the ZeroDivisionError exception. If the second number is zero, raise CustomError1.
# Implement a function open_file() that takes a filename as input and tries to open the file.
# Handle the FileNotFoundError exception. If the file does not exist, raise CustomError2.
# Implement a function process_data() that takes a list as input and tries to access an element at a specific index.
# Handle the IndexError exception. If the index is out of range, raise CustomError3.
# In the main part of your script, demonstrate the usage of all the implemented functions by invoking them and handling exceptions appropriately.
# Take a screenshot of Thonny showing both the code and output at the end of the exercise.
# Upload the screenshot.
# Directions for submitting your written assignment as an attachment:
# When you have completed the assignment, save the file on your computer with your name as part of the file name, for example, a_student_assignment1.docx [using your first initial and last name]
# Click on the title of the assignment above.
# Click on "Upload Files".
# Click on the "Browse Local Files" button to attach your file to this assignment.
# Once you have attached your file, click on the "Submit" button to send your file to your instructor.
# Note: This assignment is due 11:59 PM ET, Sunday of Week 8.
import os
def divide_numbers(num1, num2):
try:
print(f"Dividing numbers {num1} / {num2}")
if num2 == 0:
raise CustomError1
return num1 / num2
except CustomError1:
print("CustomError1: Cannot divide by zero.")
def open_file(input_file):
try:
print(f"Trying to open the {input_file}")
with open(input_file, 'r') as f:
print(f"{input_file} has been opened successfully.")
pass
except FileNotFoundError:
raise CustomError2
def process_data(data, index):
try:
print(f"Trying to return the data for each index.")
return data[index]
except IndexError:
raise CustomError3
class CustomError1(Exception):
pass
class CustomError2(Exception):
pass
class CustomError3(Exception):
pass
def __main__():
script_directory = os.path.dirname(os.path.abspath(__file__)) # get the directory of the script
input_file = os.path.join(script_directory, "input.txt") #had to use os.path.join to get the correct path. Wasn't working with just the file name
fail_input_file = os.path.join(script_directory, "doesnotexist.txt")
try:
print("\n\n----------Division Function-------------")
print("----------------------------------------")
print(f"Failure case: {divide_numbers(10, 0)}")
print(f"Success case: {divide_numbers(100, 10)}")
except CustomError1:
print("CustomError1 handled.")
print("----------End Division Function---------\n\n")
try:
print("---------Open File Function-------------")
print("----------------------------------------")
print(f"Success Case: Trying to open {input_file}")
open_file(input_file)
print(f"Fail Case: Trying to open {fail_input_file}")
open_file(fail_input_file)
except CustomError2:
print("CustomError2 handled.")
print("---------End Open File Function---------\n\n")
try:
print("-------Process List Input Function------")
print("----------------------------------------")
print(f"Failure case: {process_data([1, 2, 3], 3)}")
print(process_data([1, 2, 3], 2))
except CustomError3:
print("CustomError3 handled.")
try:
print("-------Process List Input Function------")
print("----------------------------------------")
print(f"Success case: {process_data([1, 2, 3], 2)}")
except CustomError3:
print("CustomError3 handled.")
print("----End Process List Input Function-----\n\n")
if __name__ == "__main__":
__main__()
+9
View File
@@ -0,0 +1,9 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor cursus arcu non interdum. Phasellus lacus diam, cursus a quam vel, molestie tincidunt nisl. Suspendisse congue finibus lectus, in imperdiet eros imperdiet sit amet. Curabitur hendrerit a magna ultrices aliquet. Pellentesque tortor felis, varius quis aliquam ultrices, dictum nec lorem. Duis diam mauris, semper et enim vel, lobortis porta tellus. Sed nec venenatis urna, in pharetra justo. Vestibulum ac fringilla mi, eget vulputate nisi. Fusce eget vehicula velit. Nullam vel mauris lectus. Cras eleifend condimentum pulvinar. Nulla congue, elit id iaculis aliquet, quam mauris volutpat magna, ut semper nisi lectus vitae neque. In ornare vehicula metus, ac placerat erat pellentesque at.
Nam vel massa ac leo aliquam ultricies. Maecenas tempor, diam ac cursus venenatis, metus lacus mollis dui, sit amet suscipit felis erat in urna. Suspendisse ante ex, luctus in dui quis, lobortis sodales lectus. Nullam rutrum accumsan libero, in semper nibh consectetur sit amet. Donec accumsan non turpis eu finibus. Mauris gravida metus at ipsum fringilla molestie. In ante tellus, semper porta lorem non, tincidunt tempus quam. Praesent finibus pellentesque enim, sit amet gravida nulla accumsan a.
Vivamus molestie odio justo, at suscipit ex malesuada ut. Phasellus sit amet tortor porta elit bibendum accumsan a sit amet erat. Nulla varius sodales urna, id tempus mi molestie in. Ut turpis est, varius nec tellus nec, vehicula tempus nunc. Nullam erat justo, pellentesque et ullamcorper ut, rhoncus quis nibh. Sed ut ultrices ipsum. Nulla tellus est, scelerisque a sodales ac, molestie in est. Nullam nec placerat est. Duis vel metus ipsum. Pellentesque placerat sit amet sem et imperdiet. Suspendisse vulputate elit sit amet ex lobortis, vitae egestas tortor auctor. Sed accumsan sapien ut sem ultrices efficitur.
Praesent suscipit risus quis ipsum pretium cursus. Morbi velit nibh, facilisis tincidunt nisl a, aliquet vulputate est. Vestibulum id commodo felis. Curabitur sit amet interdum ante. Maecenas metus sem, imperdiet vel ligula vehicula, mollis egestas velit. Fusce luctus nibh mollis, suscipit mi et, hendrerit ipsum. Etiam ut blandit felis, ac eleifend turpis. Sed nibh ipsum, convallis sit amet elementum eget, laoreet fringilla ex. Curabitur semper nec metus eget venenatis. Praesent efficitur vitae nulla quis placerat. Nullam porta nulla in dignissim tempus. Aliquam erat volutpat.
In a massa dignissim, luctus dolor at, commodo ligula. Proin odio nisl, auctor ut tempus non, ultrices non purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam eleifend diam nec sem pretium, molestie facilisis urna pellentesque. Vestibulum feugiat metus quis lorem aliquam, ac varius lorem tincidunt. In consectetur tempus massa facilisis placerat. Cras tincidunt justo nulla, ut tristique urna dignissim nec. Maecenas orci nunc, faucibus sed sem vel, vestibulum cursus urna. In hac habitasse platea dictumst. Ut facilisis scelerisque nunc ut feugiat. Donec viverra orci in nisi finibus congue. Etiam consectetur vel neque eu posuere. Aliquam erat volutpat.
+1
View File
@@ -0,0 +1 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor cursus **** non interdum. Phasellus lacus diam, cursus a **** **** molestie tincidunt nisl. Suspendisse congue finibus lectus, in imperdiet **** imperdiet sit amet. Curabitur hendrerit a magna ultrices aliquet. Pellentesque tortor felis, varius **** aliquam ultrices, dictum nec lorem. **** **** mauris, semper et **** **** lobortis porta tellus. Sed nec venenatis urna, in pharetra justo. Vestibulum ac fringilla mi, **** vulputate nisi. Fusce **** vehicula velit. Nullam vel mauris lectus. **** eleifend condimentum pulvinar. Nulla congue, **** id iaculis aliquet, **** mauris volutpat magna, ut semper **** lectus vitae neque. In ornare vehicula metus, ac placerat **** pellentesque at. Nam vel massa ac leo aliquam ultricies. Maecenas tempor, **** ac cursus venenatis, metus lacus mollis **** sit **** suscipit felis **** in urna. Suspendisse **** ex, luctus in dui quis, lobortis sodales lectus. Nullam rutrum accumsan libero, in semper **** consectetur sit amet. Donec accumsan non turpis eu finibus. Mauris gravida metus at ipsum fringilla molestie. In **** tellus, semper porta lorem **** tincidunt tempus quam. Praesent finibus pellentesque enim, sit **** gravida nulla accumsan a. Vivamus molestie **** justo, at suscipit ex malesuada ut. Phasellus sit **** tortor porta **** bibendum accumsan a sit **** erat. Nulla varius sodales urna, id tempus mi molestie in. Ut turpis **** varius nec tellus **** vehicula tempus nunc. Nullam **** justo, pellentesque et ullamcorper ut, rhoncus **** nibh. Sed ut ultrices ipsum. Nulla tellus **** scelerisque a sodales ac, molestie in **** Nullam nec placerat **** **** vel metus ipsum. Pellentesque placerat sit **** sem et imperdiet. Suspendisse vulputate **** sit **** ex lobortis, vitae egestas tortor auctor. Sed accumsan sapien ut sem ultrices efficitur. Praesent suscipit risus **** ipsum pretium cursus. Morbi velit nibh, facilisis tincidunt **** a, aliquet vulputate **** Vestibulum id commodo felis. Curabitur sit **** interdum ante. Maecenas metus **** imperdiet vel ligula vehicula, mollis egestas velit. Fusce luctus **** mollis, suscipit mi et, hendrerit ipsum. Etiam ut blandit felis, ac eleifend turpis. Sed **** ipsum, convallis sit **** elementum eget, laoreet fringilla ex. Curabitur semper nec metus **** venenatis. Praesent efficitur vitae nulla **** placerat. Nullam porta nulla in dignissim tempus. Aliquam **** volutpat. In a massa dignissim, luctus dolor at, commodo ligula. Proin **** nisl, auctor ut tempus **** ultrices non purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam eleifend **** nec sem pretium, molestie facilisis **** pellentesque. Vestibulum feugiat metus **** lorem aliquam, ac varius lorem tincidunt. In consectetur tempus massa facilisis placerat. **** tincidunt justo nulla, ut tristique **** dignissim **** Maecenas **** nunc, faucibus sed sem **** vestibulum cursus urna. In hac habitasse platea dictumst. Ut facilisis scelerisque **** ut feugiat. Donec viverra **** in **** finibus congue. Etiam consectetur vel neque eu posuere. Aliquam **** volutpat.
Binary file not shown.
@@ -0,0 +1,25 @@
def windchill_table(formula):
#print header columns
print("\t", end="")
for temp in range(-20, 61, 10):
print(f"{temp}\t", end="")
print("\n-----------------------------------------------------------------------------") # Print the dang header and Add a newline after the temperature header
for v in range(0, 51, 5):
print(f"{v}\t", end="") # Print wind speed
for temp in range(-20, 61, 10): # loop through the temp range to add a value to each cell
# Calculate windchill using the provided formula
windchill = 35.74 + 0.6215 * temp - 35.75 * (v ** 0.16) + 0.4275 * temp * (v ** 0.16)
if v == 0:
print ("N/A\t", end="") # Print N/A for wind speed 0
else:
print(f"{windchill:.2f}\t", end="") # Print windchill with one decimal place
print() # Add a newline after each row of windchill values
def main():
print("This program computes the windchill index.")
print("print a table to show the windchill index for a range of temperatures and wind speeds.")
windchill_table(0)
if __name__ == '__main__':
main()
+11
View File
@@ -0,0 +1,11 @@
my_string = "Hello"
for i in range(3):
print(my_string, end=" ") # Prints "Hello " three times on the same line
print("World!")
@@ -1,220 +0,0 @@
import os
import requests
import whois
from docx import Document
from fpdf import FPDF
import datetime
def investigate_website(url):
"""Investigate the website to find the country of operation and past security breaches."""
try:
# Perform WHOIS lookup to determine country
domain = url.replace("https://", "").replace("http://", "").split("/")[0]
whois_data = whois.whois(domain)
country = whois_data.get("country", "Unknown")
# Check for breaches using Have I Been Pwned API (requires API key)
hibp_api_url = f"https://haveibeenpwned.com/api/v3/breachedaccount/{domain}"
headers = {"hibp-api-key": "YOUR_API_KEY_HERE"} # Replace with your HIBP API key
breaches = []
try:
breach_response = requests.get(hibp_api_url, headers=headers)
if breach_response.status_code == 200:
breaches = breach_response.json()
elif breach_response.status_code == 404:
breaches = "No breaches found."
else:
breaches = f"Error: {breach_response.status_code}"
except Exception as e:
breaches = f"Error fetching breaches: {e}"
return {
"country": country,
"breaches": breaches,
"whois_data": str(whois_data)
}
except Exception as e:
return {
"country": "Error determining country",
"breaches": f"Error fetching breaches: {e}",
"whois_data": f"Error: {e}"
}
def analyze_headers(url):
"""Perform a header analysis to identify security weaknesses."""
try:
response = requests.get(url)
headers = response.headers
# Security headers to check
security_headers = {
"Content-Security-Policy": "Missing or insufficient Content-Security-Policy",
"Strict-Transport-Security": "Missing Strict-Transport-Security",
"X-Content-Type-Options": "Missing X-Content-Type-Options",
"X-Frame-Options": "Missing X-Frame-Options",
"X-XSS-Protection": "Missing or insufficient X-XSS-Protection",
"Referrer-Policy": "Missing Referrer-Policy",
"Permissions-Policy": "Missing Permissions-Policy"
}
weaknesses = []
for header, issue in security_headers.items():
if header not in headers:
weaknesses.append(issue)
grade = "A" if not weaknesses else "C" if len(weaknesses) < 3 else "F"
return {
"grade": grade,
"weaknesses": weaknesses,
"headers": dict(headers)
}
except Exception as e:
return {
"grade": "Error",
"weaknesses": [f"Error analyzing headers: {e}"],
"headers": f"Error: {e}"
}
def save_results_to_files(data, output_dir, domain):
"""Save investigation results to docx, pdf, and markdown files."""
os.makedirs(output_dir, exist_ok=True)
# Generate unique filenames using timestamp and domain
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Ensure the domain is a valid filename
domain_safe = "".join(c if c.isalnum() else "_" for c in domain)
base_filename = f"{domain_safe}_{timestamp}"
docx_path = os.path.join(output_dir, f"{base_filename}.docx")
pdf_path = os.path.join(output_dir, f"{base_filename}.pdf")
md_path = os.path.join(output_dir, f"{base_filename}.md")
# Create a Word document
doc = Document()
doc.add_heading("Website Security Analysis", level=1)
doc.add_heading("1. Website Investigation", level=2)
doc.add_paragraph(f"Country of Operation: {data['investigation'].get('country', 'N/A')}")
doc.add_paragraph(f"Security Breaches: {data['investigation'].get('breaches', 'N/A')}")
doc.add_heading("2. Header Analysis", level=2)
doc.add_paragraph(f"Security Grade: {data['headers'].get('grade', 'N/A')}")
if data['headers'].get('weaknesses'):
doc.add_paragraph("Weaknesses:")
for weakness in data['headers']['weaknesses']:
doc.add_paragraph(f"- {weakness}", style="List Bullet")
# Add Appendix
doc.add_heading("Appendix", level=1)
doc.add_heading("Full WHOIS Data", level=2)
doc.add_paragraph(data['investigation'].get('whois_data', 'N/A'))
doc.add_heading("Full Header Analysis", level=2)
doc.add_paragraph(str(data['headers'].get('headers', 'N/A')))
doc.add_heading("Full Breach Data", level=2)
doc.add_paragraph(str(data['investigation'].get('breaches', 'N/A')))
doc.save(docx_path)
# Create a Markdown file
with open(md_path, "w") as md_file:
md_file.write("# Website Security Analysis\n\n")
md_file.write("## 1. Website Investigation\n")
md_file.write(f"- Country of Operation: {data['investigation'].get('country', 'N/A')}\n")
md_file.write(f"- Security Breaches: {data['investigation'].get('breaches', 'N/A')}\n\n")
md_file.write("## 2. Header Analysis\n")
md_file.write(f"- Security Grade: {data['headers'].get('grade', 'N/A')}\n")
if data['headers'].get('weaknesses'):
md_file.write("- Weaknesses:\n")
for weakness in data['headers']['weaknesses']:
md_file.write(f" - {weakness}\n")
md_file.write("\n# Appendix\n\n")
md_file.write("## Full WHOIS Data\n")
md_file.write(f"```\n{data['investigation'].get('whois_data', 'N/A')}\n```\n")
md_file.write("## Full Header Analysis\n")
md_file.write(f"```\n{data['headers'].get('headers', 'N/A')}\n```\n")
md_file.write("## Full Breach Data\n")
md_file.write(f"```\n{data['investigation'].get('breaches', 'N/A')}\n```\n")
# Create a PDF file using FPDF
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Website Security Analysis", ln=True, align='C')
pdf.ln(10)
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "1. Website Investigation", ln=True)
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, f"Country of Operation: {data['investigation'].get('country', 'N/A')}")
pdf.multi_cell(0, 10, f"Security Breaches: {data['investigation'].get('breaches', 'N/A')}")
pdf.ln(5)
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "2. Header Analysis", ln=True)
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, f"Security Grade: {data['headers'].get('grade', 'N/A')}")
if data['headers'].get('weaknesses'):
pdf.cell(0, 10, "Weaknesses:", ln=True)
for weakness in data['headers']['weaknesses']:
pdf.cell(0, 10, f"- {weakness}", ln=True)
pdf.add_page()
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Appendix", ln=True)
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Full WHOIS Data", ln=True)
pdf.set_font("Arial", size=10)
pdf.multi_cell(0, 10, data['investigation'].get('whois_data', 'N/A'))
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Full Header Analysis", ln=True)
pdf.set_font("Arial", size=10)
pdf.multi_cell(0, 10, str(data['headers'].get('headers', 'N/A')))
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Full Breach Data", ln=True)
pdf.set_font("Arial", size=10)
pdf.multi_cell(0, 10, str(data['investigation'].get('breaches', 'N/A')))
pdf.output(pdf_path)
print(f"Results saved to: {docx_path}, {md_path}, {pdf_path}")
if __name__ == "__main__":
# User inputs
website_url = input("Enter the website URL (including https://): ").strip()
default_directory = os.getcwd()
print(f"Default save directory: {default_directory}")
use_default = input("Do you want to use the default directory? (y/n): ").strip().lower()
if use_default == 'y':
output_directory = default_directory
else:
output_directory = input("Enter the directory to save results: ").strip()
# Extract domain name for unique file naming
domain = website_url.replace("https://", "").replace("http://", "").split("/")[0]
# Perform analysis
investigation_results = investigate_website(website_url)
header_analysis_results = analyze_headers(website_url)
# Combine results
results = {
"investigation": investigation_results,
"headers": header_analysis_results
}
# Save to files
save_results_to_files(results, output_directory, domain)
@@ -1,220 +0,0 @@
import os
import requests
import whois
from docx import Document
from fpdf import FPDF
import datetime
def investigate_website(url):
"""Investigate the website to find the country of operation and past security breaches."""
try:
# Perform WHOIS lookup to determine country
domain = url.replace("https://", "").replace("http://", "").split("/")[0]
whois_data = whois.whois(domain)
country = whois_data.get("country", "Unknown")
# Check for breaches using Have I Been Pwned API (requires API key)
hibp_api_url = f"https://haveibeenpwned.com/api/v3/breachedaccount/{domain}"
headers = {"hibp-api-key": "YOUR_API_KEY_HERE"} # Replace with your HIBP API key
breaches = []
try:
breach_response = requests.get(hibp_api_url, headers=headers)
if breach_response.status_code == 200:
breaches = breach_response.json()
elif breach_response.status_code == 404:
breaches = "No breaches found."
else:
breaches = f"Error: {breach_response.status_code}"
except Exception as e:
breaches = f"Error fetching breaches: {e}"
return {
"country": country,
"breaches": breaches,
"whois_data": str(whois_data)
}
except Exception as e:
return {
"country": "Error determining country",
"breaches": f"Error fetching breaches: {e}",
"whois_data": f"Error: {e}"
}
def analyze_headers(url):
"""Perform a header analysis to identify security weaknesses."""
try:
response = requests.get(url)
headers = response.headers
# Security headers to check
security_headers = {
"Content-Security-Policy": "Missing or insufficient Content-Security-Policy",
"Strict-Transport-Security": "Missing Strict-Transport-Security",
"X-Content-Type-Options": "Missing X-Content-Type-Options",
"X-Frame-Options": "Missing X-Frame-Options",
"X-XSS-Protection": "Missing or insufficient X-XSS-Protection",
"Referrer-Policy": "Missing Referrer-Policy",
"Permissions-Policy": "Missing Permissions-Policy"
}
weaknesses = []
for header, issue in security_headers.items():
if header not in headers:
weaknesses.append(issue)
grade = "A" if not weaknesses else "C" if len(weaknesses) < 3 else "F"
return {
"grade": grade,
"weaknesses": weaknesses,
"headers": dict(headers)
}
except Exception as e:
return {
"grade": "Error",
"weaknesses": [f"Error analyzing headers: {e}"],
"headers": f"Error: {e}"
}
def save_results_to_files(data, output_dir, domain):
"""Save investigation results to docx, pdf, and markdown files."""
os.makedirs(output_dir, exist_ok=True)
# Generate unique filenames using timestamp and domain
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Ensure the domain is a valid filename
domain_safe = "".join(c if c.isalnum() else "_" for c in domain)
base_filename = f"{domain_safe}_{timestamp}"
docx_path = os.path.join(output_dir, f"{base_filename}.docx")
pdf_path = os.path.join(output_dir, f"{base_filename}.pdf")
md_path = os.path.join(output_dir, f"{base_filename}.md")
# Create a Word document
doc = Document()
doc.add_heading("Website Security Analysis", level=1)
doc.add_heading("1. Website Investigation", level=2)
doc.add_paragraph(f"Country of Operation: {data['investigation'].get('country', 'N/A')}")
doc.add_paragraph(f"Security Breaches: {data['investigation'].get('breaches', 'N/A')}")
doc.add_heading("2. Header Analysis", level=2)
doc.add_paragraph(f"Security Grade: {data['headers'].get('grade', 'N/A')}")
if data['headers'].get('weaknesses'):
doc.add_paragraph("Weaknesses:")
for weakness in data['headers']['weaknesses']:
doc.add_paragraph(f"- {weakness}", style="List Bullet")
# Add Appendix
doc.add_heading("Appendix", level=1)
doc.add_heading("Full WHOIS Data", level=2)
doc.add_paragraph(data['investigation'].get('whois_data', 'N/A'))
doc.add_heading("Full Header Analysis", level=2)
doc.add_paragraph(str(data['headers'].get('headers', 'N/A')))
doc.add_heading("Full Breach Data", level=2)
doc.add_paragraph(str(data['investigation'].get('breaches', 'N/A')))
doc.save(docx_path)
# Create a Markdown file
with open(md_path, "w") as md_file:
md_file.write("# Website Security Analysis\n\n")
md_file.write("## 1. Website Investigation\n")
md_file.write(f"- Country of Operation: {data['investigation'].get('country', 'N/A')}\n")
md_file.write(f"- Security Breaches: {data['investigation'].get('breaches', 'N/A')}\n\n")
md_file.write("## 2. Header Analysis\n")
md_file.write(f"- Security Grade: {data['headers'].get('grade', 'N/A')}\n")
if data['headers'].get('weaknesses'):
md_file.write("- Weaknesses:\n")
for weakness in data['headers']['weaknesses']:
md_file.write(f" - {weakness}\n")
md_file.write("\n# Appendix\n\n")
md_file.write("## Full WHOIS Data\n")
md_file.write(f"```\n{data['investigation'].get('whois_data', 'N/A')}\n```\n")
md_file.write("## Full Header Analysis\n")
md_file.write(f"```\n{data['headers'].get('headers', 'N/A')}\n```\n")
md_file.write("## Full Breach Data\n")
md_file.write(f"```\n{data['investigation'].get('breaches', 'N/A')}\n```\n")
# Create a PDF file using FPDF
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Website Security Analysis", ln=True, align='C')
pdf.ln(10)
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "1. Website Investigation", ln=True)
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, f"Country of Operation: {data['investigation'].get('country', 'N/A')}")
pdf.multi_cell(0, 10, f"Security Breaches: {data['investigation'].get('breaches', 'N/A')}")
pdf.ln(5)
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "2. Header Analysis", ln=True)
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, f"Security Grade: {data['headers'].get('grade', 'N/A')}")
if data['headers'].get('weaknesses'):
pdf.cell(0, 10, "Weaknesses:", ln=True)
for weakness in data['headers']['weaknesses']:
pdf.cell(0, 10, f"- {weakness}", ln=True)
pdf.add_page()
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Appendix", ln=True)
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Full WHOIS Data", ln=True)
pdf.set_font("Arial", size=10)
pdf.multi_cell(0, 10, data['investigation'].get('whois_data', 'N/A'))
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Full Header Analysis", ln=True)
pdf.set_font("Arial", size=10)
pdf.multi_cell(0, 10, str(data['headers'].get('headers', 'N/A')))
pdf.set_font("Arial", style="B", size=12)
pdf.cell(0, 10, "Full Breach Data", ln=True)
pdf.set_font("Arial", size=10)
pdf.multi_cell(0, 10, str(data['investigation'].get('breaches', 'N/A')))
pdf.output(pdf_path)
print(f"Results saved to: {docx_path}, {md_path}, {pdf_path}")
if __name__ == "__main__":
# User inputs
website_url = input("Enter the website URL (including https://): ").strip()
default_directory = os.getcwd()
print(f"Default save directory: {default_directory}")
use_default = input("Do you want to use the default directory? (y/n): ").strip().lower()
if use_default == 'y':
output_directory = default_directory
else:
output_directory = input("Enter the directory to save results: ").strip()
# Extract domain name for unique file naming
domain = website_url.replace("https://", "").replace("http://", "").split("/")[0]
# Perform analysis
investigation_results = investigate_website(website_url)
header_analysis_results = analyze_headers(website_url)
# Combine results
results = {
"investigation": investigation_results,
"headers": header_analysis_results
}
# Save to files
save_results_to_files(results, output_directory, domain)
@@ -1,79 +0,0 @@
import pandas as pd
import os
import whois
import socket
import requests
from ipwhois import IPWhois
def aggregate_csv_to_excel(folder_path, output_excel):
with pd.ExcelWriter(output_excel, engine='xlsxwriter') as writer:
for filename in os.listdir(folder_path):
if filename.endswith('.csv'):
file_path = os.path.join(folder_path, filename)
df = pd.read_csv(file_path)
# Filter relevant columns
columns = ['timestamp', 'client_ip', 'server_ip', 'server_port', 'direction', 'total_bytes', 'country', 'flow_state']
if 'dns' in df.columns:
columns.append('dns')
df = df[columns]
# Investigate each server IP
df['whois_info'] = df['server_ip'].apply(get_whois_info)
df['geo_info'] = df['server_ip'].apply(get_geo_info)
df['virus_total'] = df['server_ip'].apply(check_virus_total)
df['dns_lookup'] = df['server_ip'].apply(dns_lookup)
# Write to Excel
sheet_name = os.path.splitext(filename)[0]
df.to_excel(writer, sheet_name=sheet_name, index=False)
def get_whois_info(ip):
try:
w = whois.whois(ip)
return f"Registrar: {w.registrar}, Country: {w.country}"
except Exception as e:
return f"WHOIS Error: {str(e)}"
def get_geo_info(ip):
try:
obj = IPWhois(ip)
res = obj.lookup_rdap()
return f"Country: {res['asn_country_code']}, ASN: {res['asn']}"
except Exception as e:
return f"Geo Error: {str(e)}"
def check_virus_total(ip):
try:
url = f"https://www.virustotal.com/api/v3/ip_addresses/{ip}"
headers = {"x-apikey": "your-api-key-here"} # Replace with your VirusTotal API key
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
return f"Reputation: {data.get('data', {}).get('attributes', {}).get('reputation', 'N/A')}"
else:
return f"VT Error: {response.status_code}"
except Exception as e:
return f"VT Error: {str(e)}"
def dns_lookup(ip):
try:
return socket.gethostbyaddr(ip)[0]
except socket.herror:
return "DNS Lookup Error"
def main():
current_dir = os.getcwd()
user_input = input(f"Do you want to use the current directory ({current_dir}) to pull CSV files? (yes/no): ").strip().lower()
if user_input == 'yes':
folder_path = current_dir
else:
folder_path = input("Please enter the directory where the CSV files are located: ").strip()
output_excel = os.path.join(current_dir, 'aggregated_investigation.xlsx')
aggregate_csv_to_excel(folder_path, output_excel)
print(f"Aggregated investigation saved to {output_excel}")
if __name__ == "__main__":
main()
@@ -1,340 +0,0 @@
import datetime
from docx import Document
from docx2pdf import convert
def create_assessment_doc(data):
"""Creates a Word document from the assessment data."""
document = Document()
document.add_heading('Software/Vendor Security Assessment Request', 0)
# 1. Requestor Information
document.add_heading('1. Requestor Information', level=1)
document.add_paragraph(f"Name: {data['requestor_name']}")
document.add_paragraph(f"Department: {data['department']}")
document.add_paragraph(f"Email Address: {data['email']}")
document.add_paragraph(f"Phone Number: {data['phone']}")
# 2. Request Type
document.add_heading('2. Request Type', level=1)
document.add_paragraph(data['request_type'])
# 3. Deployment Model
document.add_heading('3. Deployment Model', level=1)
document.add_paragraph(data['deployment_model'])
# 4. Software/Vendor Information
document.add_heading('4. Software/Vendor Information', level=1)
document.add_paragraph(f"Software/Vendor Name: {data['vendor_name']}")
document.add_paragraph(f"Software Name: {data['software_name']}")
document.add_paragraph(f"Software/Vendor Website: {data['vendor_website']}")
document.add_paragraph(f"Software/Vendor Contact Information: {data['vendor_contact']}")
document.add_paragraph(f"Brief Description of Software/Vendor and its Purpose: {data['vendor_description']}")
# 5. Intended Use
document.add_heading('5. Intended Use', level=1)
document.add_paragraph(f"Describe how the software/vendor will be used within the company: {data['intended_use']}")
document.add_paragraph(f"Specify the departments or teams that will be using the software/vendor: {data['departments_teams']}")
document.add_paragraph(f"Identify any critical business processes or data that will be impacted by the software/vendor: {data['critical_processes_data']}")
# 6. Prerequisites
document.add_heading('6. Prerequisites', level=1)
document.add_paragraph(f"Operating System Requirements: {data['os_requirements']}")
document.add_paragraph(f"Hardware Requirements (e.g., RAM, storage space): {data['hardware_requirements']}")
document.add_paragraph(f"Network Connectivity (e.g., bandwidth, VPN): {data['network_connectivity']}")
document.add_paragraph(f"Software Dependencies (e.g., libraries, frameworks): {data['software_dependencies']}")
document.add_paragraph(f"User Access Requirements (e.g., specific roles, permissions): {data['user_access_requirements']}")
document.add_paragraph(f"Other Prerequisites: {data['other_prerequisites']}")
# 7. Technical Information
document.add_heading('7. Technical Information', level=1)
document.add_paragraph(f"Hosting Environment (e.g., cloud provider, on-premise data center): {data['hosting_environment']}")
document.add_paragraph(f"Network Requirements (e.g., ports, protocols, firewall rules): {data['network_requirements']}")
document.add_paragraph(f"Data Storage Requirements (e.g., location, encryption, data retention policies): {data['data_storage_requirements']}")
document.add_paragraph(f"Integration with Existing Systems (if any): {data['integration_existing_systems']}")
document.add_paragraph(f"API Information (if applicable): {data['api_information']}")
# 8. Security Requirements
document.add_heading('8. Security Requirements', level=1)
document.add_paragraph(f"Data Security - How will data be protected in transit and at rest?: {data['data_protection']}")
document.add_paragraph(f"Data Security - Does the software/vendor comply with relevant data privacy regulations (e.g., GDPR, CCPA)?: {data['data_privacy_compliance']}")
document.add_paragraph(f"Data Security - What data encryption methods are used?: {data['data_encryption_methods']}")
document.add_paragraph(f"Access Control - How will access to the software/vendor be granted and managed?: {data['access_control_management']}")
document.add_paragraph(f"Access Control - Does the software/vendor support multi-factor authentication?: {data['multi_factor_authentication']}")
document.add_paragraph(f"Access Control - What user roles and permissions are available?: {data['user_roles_permissions']}")
document.add_paragraph(f"Vulnerability Management - Does the software/vendor have a vulnerability disclosure program?: {data['vulnerability_disclosure']}")
document.add_paragraph(f"Vulnerability Management - How are security patches and updates managed?: {data['security_patch_management']}")
document.add_paragraph(f"Vulnerability Management - Are regular security assessments and penetration testing conducted?: {data['security_assessments']}")
document.add_paragraph(f"Compliance - Does the software/vendor comply with relevant industry security standards (e.g., ISO 27001, SOC 2)?: {data['industry_security_standards']}")
document.add_paragraph(f"Compliance - Are there any third-party security certifications or audits available?: {data['third_party_certifications']}")
document.add_paragraph(f"Business Continuity and Disaster Recovery - What are the software/vendor's business continuity and disaster recovery plans?: {data['business_continuity_plans']}")
document.add_paragraph(f"Business Continuity and Disaster Recovery - What are the recovery time objectives (RTOs) and recovery point objectives (RPOs)?: {data['rto_rpo']}")
# 9. Privacy Requirements
document.add_heading('9. Privacy Requirements', level=1)
document.add_paragraph(f"Data Collection - What personal data will be collected by the software/vendor?: {data['personal_data_collected']}")
document.add_paragraph(f"Data Collection - What is the purpose of collecting this data?: {data['data_collection_purpose']}")
document.add_paragraph(f"Data Collection - Will data be shared with third parties? If so, with whom and for what purpose?: {data['data_sharing']}")
document.add_paragraph(f"Data Subject Rights - How does the software/vendor ensure data subject rights (e.g., access, rectification, erasure)?: {data['data_subject_rights']}")
document.add_paragraph(f"Data Subject Rights - Does the software/vendor provide a privacy policy that is readily accessible to users?: {data['privacy_policy']}")
# 10. Legal and Contractual Requirements
document.add_heading('10. Legal and Contractual Requirements', level=1)
document.add_paragraph(f"Software License Agreement: {data['license_agreement']}")
document.add_paragraph(f"Service Level Agreement (SLA): {data['sla']}")
document.add_paragraph(f"Data Processing Agreement (DPA): {data['dpa']}")
document.add_paragraph(f"Vendor Security Policies: {data['vendor_security_policies']}")
# 11. Risk Assessment
document.add_heading('11. Risk Assessment', level=1)
document.add_paragraph(f"Identify any potential security or privacy risks associated with the use of the software/vendor: {data['potential_risks']}")
document.add_paragraph(f"Describe the risk mitigation measures that will be implemented: {data['risk_mitigation']}")
# 12. Approval (This section will likely be filled later)
document.add_heading('12. Approval', level=1)
document.add_paragraph("Security Analyst Review:")
document.add_paragraph("Date of Review: ")
document.add_paragraph("Security Analyst Name: ")
document.add_paragraph("Security Assessment Findings: ")
document.add_paragraph("Approval Status (Approved, Conditionally Approved, Rejected): ")
document.add_paragraph("Management Approval (if required):")
document.add_paragraph("Date of Approval: ")
document.add_paragraph("Approving Manager Name: ")
# 13. Supporting Documentation
document.add_heading('13. Supporting Documentation', level=1)
document.add_paragraph("Attach any relevant supporting documentation, such as:")
document.add_paragraph("Vendor security questionnaires")
document.add_paragraph("Penetration testing reports")
document.add_paragraph("Security audit reports")
document.add_paragraph("Privacy impact assessments")
return document
def create_markdown_file(data, md_filename): # Receive filename as argument
"""Creates a Markdown file from the assessment data."""
with open(md_filename, "w") as f: # Use the provided filename
# Add all the headings and data from the form in Markdown format
f.write("# Software/Vendor Security Assessment Request\n\n")
f.write("## 1. Requestor Information\n")
f.write(f"Name: {data['requestor_name']}\n")
f.write(f"Department: {data['department']}\n")
f.write(f"Email Address: {data['email']}\n")
f.write(f"Phone Number: {data['phone']}\n")
f.write("\n## 2. Request Type\n")
f.write(f"{data['request_type']}\n")
f.write("\n## 3. Deployment Model\n")
f.write(f"{data['deployment_model']}\n")
f.write("\n## 4. Software/Vendor Information\n")
f.write(f"Software/Vendor Name: {data['vendor_name']}\n")
f.write(f"Software Name: {data['software_name']}\n")
f.write(f"Software/Vendor Website: {data['vendor_website']}\n")
f.write(f"Software/Vendor Contact Information: {data['vendor_contact']}\n")
f.write(f"Brief Description of Software/Vendor and its Purpose: {data['vendor_description']}\n")
f.write("\n## 5. Intended Use\n")
f.write(f"Describe how the software/vendor will be used within the company: {data['intended_use']}\n")
f.write(f"Specify the departments or teams that will be using the software/vendor: {data['departments_teams']}\n")
f.write(f"Identify any critical business processes or data that will be impacted by the software/vendor: {data['critical_processes_data']}\n")
f.write("\n## 6. Prerequisites\n")
f.write(f"Operating System Requirements: {data['os_requirements']}\n")
f.write(f"Hardware Requirements (e.g., RAM, storage space): {data['hardware_requirements']}\n")
f.write(f"Network Connectivity (e.g., bandwidth, VPN): {data['network_connectivity']}\n")
f.write(f"Software Dependencies (e.g., libraries, frameworks): {data['software_dependencies']}\n")
f.write(f"User Access Requirements (e.g., specific roles, permissions): {data['user_access_requirements']}\n")
f.write(f"Other Prerequisites: {data['other_prerequisites']}\n")
f.write("\n## 7. Technical Information\n")
f.write(f"Hosting Environment (e.g., cloud provider, on-premise data center): {data['hosting_environment']}\n")
f.write(f"Network Requirements (e.g., ports, protocols, firewall rules): {data['network_requirements']}\n")
f.write(f"Data Storage Requirements (e.g., location, encryption, data retention policies): {data['data_storage_requirements']}\n")
f.write(f"Integration with Existing Systems (if any): {data['integration_existing_systems']}\n")
f.write(f"API Information (if applicable): {data['api_information']}\n")
f.write("\n## 8. Security Requirements\n")
f.write(f"Data Security - How will data be protected in transit and at rest?: {data['data_protection']}\n")
f.write(f"Data Security - Does the software/vendor comply with relevant data privacy regulations (e.g., GDPR, CCPA)?: {data['data_privacy_compliance']}\n")
f.write(f"Data Security - What data encryption methods are used?: {data['data_encryption_methods']}\n")
f.write(f"Access Control - How will access to the software/vendor be granted and managed?: {data['access_control_management']}\n")
f.write(f"Access Control - Does the software/vendor support multi-factor authentication?: {data['multi_factor_authentication']}\n")
f.write(f"Access Control - What user roles and permissions are available?: {data['user_roles_permissions']}\n")
f.write(f"Vulnerability Management - Does the software/vendor have a vulnerability disclosure program?: {data['vulnerability_disclosure']}\n")
f.write(f"Vulnerability Management - How are security patches and updates managed?: {data['security_patch_management']}\n")
f.write(f"Vulnerability Management - Are regular security assessments and penetration testing conducted?: {data['security_assessments']}\n")
f.write(f"Compliance - Does the software/vendor comply with relevant industry security standards (e.g., ISO 27001, SOC 2)?: {data['industry_security_standards']}\n")
f.write(f"Compliance - Are there any third-party security certifications or audits available?: {data['third_party_certifications']}\n")
f.write(f"Business Continuity and Disaster Recovery - What are the software/vendor's business continuity and disaster recovery plans?: {data['business_continuity_plans']}\n")
f.write(f"Business Continuity and Disaster Recovery - What are the recovery time objectives (RTOs) and recovery point objectives (RPOs)?: {data['rto_rpo']}\n")
f.write("\n## 9. Privacy Requirements\n")
f.write(f"Data Collection - What personal data will be collected by the software/vendor?: {data['personal_data_collected']}\n")
f.write(f"Data Collection - What is the purpose of collecting this data?: {data['data_collection_purpose']}\n")
f.write(f"Data Collection - Will data be shared with third parties? If so, with whom and for what purpose?: {data['data_sharing']}\n")
f.write(f"Data Subject Rights - How does the software/vendor ensure data subject rights (e.g., access, rectification, erasure)?: {data['data_subject_rights']}\n")
f.write(f"Data Subject Rights - Does the software/vendor provide a privacy policy that is readily accessible to users?: {data['privacy_policy']}\n")
f.write("\n## 10. Legal and Contractual Requirements\n")
f.write(f"Software License Agreement: {data['license_agreement']}\n")
f.write(f"Service Level Agreement (SLA): {data['sla']}\n")
f.write(f"Data Processing Agreement (DPA): {data['dpa']}\n")
f.write(f"Vendor Security Policies: {data['vendor_security_policies']}\n")
f.write("\n## 11. Risk Assessment\n")
f.write(f"Identify any potential security or privacy risks associated with the use of the software/vendor: {data['potential_risks']}\n")
f.write(f"Describe the risk mitigation measures that will be implemented: {data['risk_mitigation']}\n")
f.write("\n## 12. Approval\n")
f.write("Security Analyst Review:\n")
f.write("Date of Review: \n")
f.write("Security Analyst Name: \n")
f.write("Security Assessment Findings: \n")
f.write("Approval Status (Approved, Conditionally Approved, Rejected): \n")
f.write("Management Approval (if required):\n")
f.write("Date of Approval: \n")
f.write("Approving Manager Name: \n")
f.write("\n## 13. Supporting Documentation\n")
f.write("Attach any relevant supporting documentation, such as:\n")
f.write("- Vendor security questionnaires\n")
f.write("- Penetration testing reports\n")
f.write("- Security audit reports\n")
f.write("- Privacy impact assessments\n")
def main():
"""Collects assessment data from user input and generates documents."""
data = {}
# 1. Requestor Information
data['requestor_name'] = input("Enter your name: ")
data['department'] = input("Enter your department: ")
data['email'] = input("Enter your email address: ")
data['phone'] = input("Enter your phone number: ")
# 2. Request Type
print("\nRequest Type:")
print("1. New Software/Vendor")
print("2. Existing Software/Vendor (Renewal/Upgrade)")
print("3. Software/Vendor Decommissioning")
choice = input("Enter your choice (1-3): ")
request_types = {
"1": "New Software/Vendor",
"2": "Existing Software/Vendor (Renewal/Upgrade)",
"3": "Software/Vendor Decommissioning"
}
data['request_type'] = request_types.get(choice)
# 3. Deployment Model
print("\nDeployment Model:")
print("1. SaaS (Software as a Service)")
print("2. IaaS (Infrastructure as a Service)")
print("3. PaaS (Platform as a Service)")
print("4. On-Premises (Internally Hosted)")
print("5. Hybrid")
print("6. Cloud-Hosted")
print("7. Other (Please Specify)")
choice = input("Enter your choice (1-7): ")
if choice == "7":
data['deployment_model'] = input("Specify the deployment model: ")
else:
deployment_models = {
"1": "SaaS (Software as a Service)",
"2": "IaaS (Infrastructure as a Service)",
"3": "PaaS (Platform as a Service)",
"4": "On-Premises (Internally Hosted)",
"5": "Hybrid",
"6": "Cloud-Hosted"
}
data['deployment_model'] = deployment_models.get(choice)
# 4. Software/Vendor Information
data['vendor_name'] = input("Enter the Software/Vendor Name: ")
data['software_name'] = input("Enter the Software Name: ")
data['vendor_website'] = input("Enter the Software/Vendor Website: ")
data['vendor_contact'] = input("Enter the Software/Vendor Contact Information: ")
data['vendor_description'] = input("Enter a Brief Description of Software/Vendor and its Purpose: ")
# 5. Intended Use
data['intended_use'] = input("Describe how the software/vendor will be used within the company: ")
data['departments_teams'] = input("Specify the departments or teams that will be using the software/vendor: ")
data['critical_processes_data'] = input("Identify any critical business processes or data that will be impacted by the software/vendor: ")
# 6. Prerequisites
data['os_requirements'] = input("List any Operating System Requirements: ")
data['hardware_requirements'] = input("List any Hardware Requirements (e.g., RAM, storage space): ")
data['network_connectivity'] = input("List any Network Connectivity Requirements (e.g., bandwidth, VPN): ")
data['software_dependencies'] = input("List any Software Dependencies (e.g., libraries, frameworks): ")
data['user_access_requirements'] = input("List any User Access Requirements (e.g., specific roles, permissions): ")
data['other_prerequisites'] = input("List any Other Prerequisites: ")
# 7. Technical Information
data['hosting_environment'] = input("Provide the Hosting Environment (e.g., cloud provider, on-premise data center): ")
data['network_requirements'] = input("Provide the Network Requirements (e.g., ports, protocols, firewall rules): ")
data['data_storage_requirements'] = input("Provide the Data Storage Requirements (e.g., location, encryption, data retention policies): ")
data['integration_existing_systems'] = input("Describe the Integration with Existing Systems (if any): ")
data['api_information'] = input("Provide API Information (if applicable): ")
# 8. Security Requirements
data['data_protection'] = input("Data Security - How will data be protected in transit and at rest?: ")
data['data_privacy_compliance'] = input("Data Security - Does the software/vendor comply with relevant data privacy regulations (e.g., GDPR, CCPA)?: ")
data['data_encryption_methods'] = input("Data Security - What data encryption methods are used?: ")
data['access_control_management'] = input("Access Control - How will access to the software/vendor be granted and managed?: ")
data['multi_factor_authentication'] = input("Access Control - Does the software/vendor support multi-factor authentication?: ")
data['user_roles_permissions'] = input("Access Control - What user roles and permissions are available?: ")
data['vulnerability_disclosure'] = input("Vulnerability Management - Does the software/vendor have a vulnerability disclosure program?: ")
data['security_patch_management'] = input("Vulnerability Management - How are security patches and updates managed?: ")
data['security_assessments'] = input("Vulnerability Management - Are regular security assessments and penetration testing conducted?: ")
data['industry_security_standards'] = input("Compliance - Does the software/vendor comply with relevant industry security standards (e.g., ISO 27001, SOC 2)?: ")
data['third_party_certifications'] = input("Compliance - Are there any third-party security certifications or audits available?: ")
data['business_continuity_plans'] = input("Business Continuity and Disaster Recovery - What are the software/vendor's business continuity and disaster recovery plans?: ")
data['rto_rpo'] = input("Business Continuity and Disaster Recovery - What are the recovery time objectives (RTOs) and recovery point objectives (RPOs)?: ")
# 9. Privacy Requirements
data['personal_data_collected'] = input("Data Collection - What personal data will be collected by the software/vendor?: ")
data['data_collection_purpose'] = input("Data Collection - What is the purpose of collecting this data?: ")
data['data_sharing'] = input("Data Collection - Will data be shared with third parties? If so, with whom and for what purpose?: ")
data['data_subject_rights'] = input("Data Subject Rights - How does the software/vendor ensure data subject rights (e.g., access, rectification, erasure)?: ")
data['privacy_policy'] = input("Data Subject Rights - Does the software/vendor provide a privacy policy that is readily accessible to users?: ")
# 10. Legal and Contractual Requirements
data['license_agreement'] = input("Provide the Software License Agreement: ")
data['sla'] = input("Provide the Service Level Agreement (SLA): ")
data['dpa'] = input("Provide the Data Processing Agreement (DPA): ")
data['vendor_security_policies'] = input("Provide the Vendor Security Policies: ")
# 11. Risk Assessment
data['potential_risks'] = input("Identify any potential security or privacy risks associated with the use of the software/vendor: ")
data['risk_mitigation'] = input("Describe the risk mitigation measures that will be implemented: ")
# Generate a unique timestamp
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
# Sanitize vendor/software name for filename
vendor_name = data['vendor_name'].replace(" ", "_").replace("/", "-")
software_name = data['software_name'].replace(" ", "_").replace("/", "-")
# Create and save the Word document with unique filename
doc_filename = f"{vendor_name}_{software_name}_assessment_{timestamp}.docx"
doc = create_assessment_doc(data)
doc.save(doc_filename)
print(f"Word document saved as {doc_filename}")
# Convert to PDF with unique filename
pdf_filename = f"{vendor_name}_{software_name}_assessment_{timestamp}.pdf"
convert(doc_filename, pdf_filename)
print(f"PDF document saved as {pdf_filename}")
# Create Markdown file with unique filename
md_filename = f"{vendor_name}_{software_name}_assessment_{timestamp}.md"
create_markdown_file(data, md_filename) # Pass filename to function
print(f"Markdown file saved as {md_filename}")
if __name__ == "__main__":
main()