import os import subprocess defanalyze_code(directory): # List Python files in the directory python_files = [file for file in os.listdir(directory) if file.endswith('.py')] ifnot python_files: print("No Python files found in the specified directory.") return # Analyze each Python file using pylint and flake8 for file in python_files: print(f"Analyzing file: {file}") file_path = os.path.join(directory, file) # Run pylint print("\nRunning pylint...") pylint_command = f"pylint {file_path}" subprocess.run(pylint_command, shell=True) # Run flake8 print("\nRunning flake8...") flake8_command = f"flake8 {file_path}" subprocess.run(flake8_command, shell=True) if __name__ == "__main__": directory = r"C:\Users\abhay\OneDrive\Desktop\Part7" analyze_code(directory) 对一个旧 Python 脚本进行代码质量审查时的输出结果,该脚本通过网络应用程序将文件转换为不同格式
import hashlib import os defcalculate_sha256(file_path): sha256 = hashlib.sha256() with open(file_path, 'rb') as file: for chunk in iter(lambda: file.read(4096), b''): sha256.update(chunk) return sha256.hexdigest() defcheck_integrity(file_path, expected_checksum): actual_checksum = calculate_sha256(file_path) return actual_checksum == expected_checksum if __name__ == "__main__": file_path = input("Enter the path to the file: ") expected_checksum = input("Enter the expected SHA-256 checksum: ") if os.path.isfile(file_path): if check_integrity(file_path, expected_checksum): print("File integrity verified: The file has not been tampered with.") else: print("File integrity check failed: The file may have been tampered with.") else: print("Error: File not found.") 使用样本 ZIP 文件(未篡改)进行脚本测试使用样本 ZIP 文件(篡改)进行脚本测试
import socket from prettytable import PrettyTable # Dictionary mapping common ports to vulnerabilities (Top 15) vulnerabilities = { 80: "HTTP (Hypertext Transfer Protocol) - Used for unencrypted web traffic", 443: "HTTPS (HTTP Secure) - Used for encrypted web traffic", 22: "SSH (Secure Shell) - Used for secure remote access", 21: "FTP (File Transfer Protocol) - Used for file transfers", 25: "SMTP (Simple Mail Transfer Protocol) - Used for email transmission", 23: "Telnet - Used for remote terminal access", 53: "DNS (Domain Name System) - Used for domain name resolution", 110: "POP3 (Post Office Protocol version 3) - Used for email retrieval", 143: "IMAP (Internet Message Access Protocol) - Used for email retrieval", 3306: "MySQL - Used for MySQL database access", 3389: "RDP (Remote Desktop Protocol) - Used for remote desktop connections (Windows)", 8080: "HTTP Alternate - Commonly used as a secondary HTTP port", 8000: "HTTP Alternate - Commonly used as a secondary HTTP port", 8443: "HTTPS Alternate - Commonly used as a secondary HTTPS port", 5900: "VNC (Virtual Network Computing) - Used for remote desktop access", # Add more ports and vulnerabilities as needed } defdisplay_table(open_ports): table = PrettyTable(["Open Port", "Vulnerability"]) for port in open_ports: vulnerability = vulnerabilities.get(port, "No known vulnerabilities associated with common services") table.add_row([port, vulnerability]) print(table) defscan_top_ports(target): open_ports = [] top_ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 3306, 3389, 5900, 8000, 8080, 8443] # Top 15 ports for port in top_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) # Adjust timeout as needed result = sock.connect_ex((target, port)) if result == 0: open_ports.append(port) sock.close() except KeyboardInterrupt: sys.exit() except socket.error: pass return open_ports defmain(): target = input("Enter the website URL or IP address to scan for open ports: ") open_ports = scan_top_ports(target) ifnot open_ports: print("No open ports found on the target.") else: print("Open ports and associated vulnerabilities:") display_table(open_ports) if __name__ == "__main__": main() 使用脚本识别的 OpenPorts 列表
import streamlit as st import csv from cryptography.fernet import Fernet from cryptography.fernet import InvalidToken # Custom encryption key (hardcoded) CUSTOM_ENCRYPTION_KEY = b'u7wGgNdDFefqpr_kGxb8wJf6XRVsRwvb3QgITsD5Ft4='## 如果您打算在共享平台上使用此脚本,请确保将此密钥保存在一个单独的安全文件中。 # Function to encrypt password defencrypt_password(password): cipher_suite = Fernet(CUSTOM_ENCRYPTION_KEY) encrypted_password = cipher_suite.encrypt(password.encode()) return encrypted_password # Function to decrypt password defdecrypt_password(encrypted_password): if isinstance(encrypted_password, bytes): try: cipher_suite = Fernet(CUSTOM_ENCRYPTION_KEY) decrypted_password = cipher_suite.decrypt(encrypted_password) return decrypted_password.decode() except InvalidToken: return"Invalid Token" else: returnNone # Function to save website name and password to CSV file defsave_credentials(website_name, password): encrypted_password = encrypt_password(password) with open('credentials.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow([website_name, encrypted_password.decode()]) # Ensure storing string representation # Function to retrieve password from CSV file defretrieve_password(website_name): with open('credentials.csv', 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: if row[0] == website_name: encrypted_password = row[1].encode() return encrypted_password returnNone # Streamlit UI st.title("Password Manager") # Input fields for website name and password website_name = st.text_input("Enter website name:") password = st.text_input("Enter password:", type="password") # Save button to save website name and password if st.button("Save"): if website_name and password: save_credentials(website_name, password) st.success("Website name and password saved successfully.") else: st.error("Please fill in all fields.") # Retrieve button to retrieve password if st.checkbox("Retrieve Password"): website_name = st.selectbox("Select website name:", options=[""] + [row[0] for row in csv.reader(open('credentials.csv', 'r'))]) key = st.text_input("Enter Your Encryption Key:", type="password") if st.button("Retrieve Password"): if key == str(CUSTOM_ENCRYPTION_KEY.decode()): if website_name: encrypted_password = retrieve_password(website_name) if encrypted_password: decrypted_password = decrypt_password(encrypted_password) st.success(f"Password for **{website_name}** -> **{decrypted_password}**") else: st.error("Password not found in database.") elif key == "": pass else: st.error("Invalid Encryption Key!!!")
defgenerate_markdown_file(): # Prompting user for inputs repository_name = input("\n Enter the name of your GitHub repository: ") project_description = input("Enter a short description of your project: ") installation_instructions = input("Enter installation instructions for your project: ") usage_instructions = input("Enter usage instructions for your project: ") contributors = input("Enter the contributors to your project (separated by commas): ") license = select_license() # Generating badges stars_badge = "[](https://github.com/{}/stargazers)".format(repository_name, repository_name) forks_badge = "[](https://github.com/{}/network/members)".format(repository_name, repository_name)
issues_badge = "[](https://github.com/{}/issues)".format(repository_name, repository_name) license_badge = "[](https://github.com/{}/blob/master/LICENSE)".format(repository_name, repository_name) # Generating Markdown content markdown_content = f""" # {repository_name} {project_description} ## Table of Contents - [Installation](#installation) - [Usage](#usage) - [Contributors](#contributors) - [License](#license) - [Badges](#badges) - [GitHub Repository](#github-repository) ## Installation ``` {installation_instructions} ``` ## Usage ``` {usage_instructions} ``` ## Contributors {contributors} ## License This project is licensed under the {license} License - see the [LICENSE](LICENSE) file for details. ## Badges {stars_badge}{forks_badge}{issues_badge}{license_badge} ## GitHub Repository [Link to GitHub repository](https://github.com/{repository_name}) """ # Writing content to Markdown file markdown_file_name = f"{repository_name}_README.md" with open(markdown_file_name, "w") as markdown_file: markdown_file.write(markdown_content) print(f"Markdown file '{markdown_file_name}' generated successfully!") defselect_license(): licenses = { "MIT": "MIT License", "Apache": "Apache License 2.0", "GPL": "GNU General Public License v3.0", # Add more licenses as needed } print("Select a license for your project:") for key, value in licenses.items(): print(f"{key}: {value}") whileTrue: selected_license = input("Enter the number corresponding to your selected license: ") if selected_license in licenses: return licenses[selected_license] else: print("Invalid input. Please enter a valid license number.") if __name__ == "__main__": generate_markdown_file()
import os import hashlib import shutil defget_file_hash(file_path): with open(file_path, 'rb') as f: return hashlib.sha256(f.read()).hexdigest() deforganize_and_move_duplicates(folder_path): # Create a dictionary to store destination folders based on file extensions extension_folders = {} # Create the "Duplicates" folder if it doesn't exist duplicates_folder = os.path.join(folder_path, 'Duplicates') os.makedirs(duplicates_folder, exist_ok=True) # Create a dictionary to store file hashes file_hashes = {} # Iterate through files in the folder for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) if os.path.isfile(file_path): # Get the file extension _, extension = os.path.splitext(filename) extension = extension.lower() # Convert extension to lowercase # Determine the destination folder if extension in extension_folders: destination_folder = extension_folders[extension] else: destination_folder = os.path.join(folder_path, extension[1:]) # Remove the leading dot from the extension os.makedirs(destination_folder, exist_ok=True) extension_folders[extension] = destination_folder # Calculate the file hash file_hash = get_file_hash(file_path) # Check for duplicates if file_hash in file_hashes: # File is a duplicate, move it to the "Duplicates" folder shutil.move(file_path, os.path.join(duplicates_folder, filename)) print(f"Moved duplicate file {filename} to Duplicates folder.") else: # Store the file hash file_hashes[file_hash] = filename # Move the file to the destination folder shutil.move(file_path, destination_folder) print(f"Moved {filename} to {destination_folder}") if __name__ == "__main__": folder_path = input("Enter the path to the folder to organize: ") organize_and_move_duplicates(folder_path)