Skip to content

Commit ce6649d

Browse files
Major improvements across debugger, vulnscan, and logging (#225)
2 parents 7895e7b + 8a93c7a commit ce6649d

25 files changed

+460
-839
lines changed

.idea/csv-editor.xml

Lines changed: 0 additions & 16 deletions
This file was deleted.

.idea/misc.xml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

CODE/Logicytics.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import psutil
1313
from prettytable import PrettyTable
1414

15-
from logicytics import Log, Execute, Check, Get, FileManagement, Flag, DEBUG, DELETE_LOGS, config
15+
from logicytics import Log, execute, check, get, file_management, flag, DEBUG, DELETE_LOGS, config
1616

1717
# Initialization
1818
log = Log({"log_level": DEBUG, "delete_log": DELETE_LOGS})
@@ -66,7 +66,7 @@ def __generate_execution_list(self) -> list[str]:
6666
- Logs the final execution list for debugging purposes
6767
- Warns users about potential long execution times for certain actions
6868
"""
69-
execution_list = Get.list_of_files(".", only_extensions=(".py", ".exe", ".ps1", ".bat"),
69+
execution_list = get.list_of_files(".", only_extensions=(".py", ".exe", ".ps1", ".bat"),
7070
exclude_files=["Logicytics.py"],
7171
exclude_dirs=["logicytics", "SysInternal_Suite"])
7272
files_to_remove = {
@@ -101,7 +101,7 @@ def __generate_execution_list(self) -> list[str]:
101101

102102
elif ACTION == "modded":
103103
# Add all files in MODS to execution list
104-
execution_list = Get.list_of_files("../MODS", only_extensions=(".py", ".exe", ".ps1", ".bat"),
104+
execution_list = get.list_of_files("../MODS", only_extensions=(".py", ".exe", ".ps1", ".bat"),
105105
append_file_list=execution_list, exclude_files=["Logicytics.py"],
106106
exclude_dirs=["logicytics", "SysInternal_Suite"])
107107

@@ -144,7 +144,7 @@ def __script_handler(script: str) -> tuple[str, Exception | None]:
144144
"""
145145
log.debug(f"Executing {script}")
146146
try:
147-
log.execution(Execute.script(script))
147+
log.execution(execute.script(script))
148148
log.info(f"{script} executed successfully")
149149
return script, None
150150
except Exception as err:
@@ -207,7 +207,7 @@ def __performance(self):
207207
gc.collect()
208208
start_time = datetime.now()
209209
start_memory = process.memory_full_info().uss / 1024 / 1024 # MB
210-
log.execution(Execute.script(self.execution_list[file]))
210+
log.execution(execute.script(self.execution_list[file]))
211211
end_time = datetime.now()
212212
end_memory = process.memory_full_info().uss / 1024 / 1024 # MB
213213
elapsed_time = end_time - start_time
@@ -352,7 +352,7 @@ def get_flags():
352352
"""
353353
global ACTION, SUB_ACTION
354354
# Get flags_list
355-
ACTION, SUB_ACTION = Flag.data()
355+
ACTION, SUB_ACTION = flag.data()
356356
log.debug(f"Action: {ACTION}")
357357
log.debug(f"Sub-Action: {SUB_ACTION}")
358358

@@ -382,7 +382,7 @@ def handle_special_actions():
382382
log.info("Opening debug menu...")
383383
SpecialAction.execute_new_window("_debug.py")
384384

385-
messages = Check.sys_internal_zip()
385+
messages = check.sys_internal_zip()
386386
if messages:
387387
# If there are messages, log them with debug
388388
log.debug(messages)
@@ -407,7 +407,7 @@ def handle_special_actions():
407407
"Sorry, this feature is yet to be implemented. You can manually Restore your backups, We will open "
408408
"the location for you"
409409
)
410-
FileManagement.open_file("../ACCESS/BACKUP/")
410+
file_management.open_file("../ACCESS/BACKUP/")
411411
input("Press Enter to exit...")
412412
exit(1)
413413

@@ -438,7 +438,7 @@ def check_privileges():
438438
- Depends on global `DEBUG` configuration variable
439439
- Logs warnings or critical messages based on privilege and UAC status
440440
"""
441-
if not Check.admin():
441+
if not check.admin():
442442
if DEBUG == "DEBUG":
443443
log.warning("Running in debug mode, continuing without admin privileges - This may cause issues")
444444
else:
@@ -447,7 +447,7 @@ def check_privileges():
447447
input("Press Enter to exit...")
448448
exit(1)
449449

450-
if Check.uac():
450+
if check.uac():
451451
log.warning("UAC is enabled, this may cause issues - Please disable UAC if possible")
452452

453453

@@ -462,7 +462,7 @@ def files(cls):
462462
@staticmethod
463463
def __and_log(directory: str, name: str):
464464
log.debug(f"Zipping directory '{directory}' with name '{name}' under action '{ACTION}'")
465-
zip_values = FileManagement.Zip.and_hash(
465+
zip_values = file_management.Zip.and_hash(
466466
directory,
467467
name,
468468
ACTION if ACTION is not None else f"ERROR_NO_ACTION_SPECIFIED_{datetime.now().isoformat()}"
@@ -530,9 +530,10 @@ def Logicytics():
530530
try:
531531
Logicytics()
532532
except KeyboardInterrupt:
533-
log.warning("⚠️ Force shutdown detected! Some temporary files might be left behind.")
534-
log.warning("💡 Pro tip: Next time, let the program finish naturally.")
535-
# TODO v3.4.2 -> Cleanup function
533+
log.warning("Force shutdown detected! Some temporary files might be left behind.")
534+
log.warning("Next time, let the program finish naturally for complete cleanup.")
535+
# Emergency cleanup - zip generated files
536+
ZIP.files()
536537
exit(0)
537538
else:
538539
log.error("This script cannot be imported!")

CODE/_debug.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@
99
import psutil
1010
import requests
1111

12-
from logicytics import Log, DEBUG, VERSION, Check
12+
from logicytics import Log, DEBUG, VERSION, check, config
1313

1414
log_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "ACCESS\\LOGS\\DEBUG\\DEBUG.log")
1515
log = Log({"log_level": DEBUG, "filename": log_path, "truncate_message": False, "delete_log": True})
16+
url = config.get("System Settings", "config_url")
1617

1718

1819
class VersionManager:
@@ -149,10 +150,9 @@ def get_online_config() -> dict | None:
149150
Retrieves configuration data from a remote repository.
150151
"""
151152
try:
152-
url = "https://raw.githubusercontent.com/DefinetlyNotAI/Logicytics/main/CODE/config.ini"
153-
config = configparser.ConfigParser()
154-
config.read_string(requests.get(url, timeout=15).text)
155-
return config
153+
_config = configparser.ConfigParser()
154+
_config.read_string(requests.get(url, timeout=15).text)
155+
return _config
156156
except requests.exceptions.RequestException as e:
157157
log.error(f"Connection error: {e}")
158158
return None
@@ -194,27 +194,27 @@ def debug():
194194
Executes a comprehensive system debug routine, performing various checks and logging system information.
195195
"""
196196
# Online Configuration Check
197-
config = ConfigManager.get_online_config()
198-
if config:
199-
HealthCheck.check_versions(VERSION, config["System Settings"]["version"])
197+
_config = ConfigManager.get_online_config()
198+
if _config:
199+
HealthCheck.check_versions(VERSION, _config["System Settings"]["version"])
200200

201201
# File Integrity Check
202-
required_files = config["System Settings"].get("files", "").split(",")
202+
required_files = _config["System Settings"].get("files", "").split(",")
203203
FileManager.check_required_files(".", required_files)
204204

205205
# SysInternal Binaries Check
206206
SysInternalManager.check_binaries("SysInternal_Suite")
207207

208208
# System Checks
209-
log.info("Admin privileges found" if Check.admin() else "Admin privileges not found")
210-
log.info("UAC enabled" if Check.uac() else "UAC disabled")
209+
log.info("Admin privileges found" if check.admin() else "Admin privileges not found")
210+
log.info("UAC enabled" if check.uac() else "UAC disabled")
211211
log.info(f"Execution path: {psutil.__file__}")
212212
log.info(f"Global execution path: {sys.executable}")
213213
log.info(f"Local execution path: {sys.prefix}")
214214
log.info(
215215
"Running in a virtual environment" if sys.prefix != sys.base_prefix else "Not running in a virtual environment")
216216
log.info(
217-
"Execution policy is unrestricted" if Check.execution_policy() else "Execution policy is restricted")
217+
"Execution policy is unrestricted" if check.execution_policy() else "Execution policy is restricted")
218218

219219
# Python Version Check
220220
SystemInfoManager.python_version()

CODE/_dev.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import configobj
88

9-
from logicytics import log, Get, FileManagement, CURRENT_FILES, VERSION
9+
from logicytics import log, get, file_management, CURRENT_FILES, VERSION
1010

1111

1212
def color_print(text, color="reset", is_input=False) -> None | str:
@@ -21,8 +21,8 @@ def color_print(text, color="reset", is_input=False) -> None | str:
2121
color_code = colors.get(color.lower(), colors["reset"])
2222
if is_input:
2323
return input(f"{color_code}{text}{colors['reset']}")
24-
else:
25-
print(f"{color_code}{text}{colors['reset']}")
24+
print(f"{color_code}{text}{colors['reset']}")
25+
return None
2626

2727

2828
def _update_ini_file(filename: str, new_data: list | str, key: str) -> None:
@@ -88,6 +88,7 @@ def _prompt_user(question: str, file_to_open: str = None, special: bool = False)
8888
return True
8989
except Exception as e:
9090
color_print(f"[x] {e}", "red")
91+
return None
9192

9293

9394
def _perform_checks() -> bool:
@@ -116,7 +117,8 @@ def _handle_file_operations() -> None:
116117
Handles file operations and logging for added, removed, and normal files.
117118
"""
118119
EXCLUDE_FILES = ["logicytics\\User_History.json.gz", "logicytics\\User_History.json"]
119-
files = Get.list_of_files(".", exclude_files=EXCLUDE_FILES, exclude_dirs=["SysInternal_Suite"])
120+
files = get.list_of_files(".", exclude_files=EXCLUDE_FILES, exclude_dirs=["SysInternal_Suite"],
121+
exclude_extensions=[".pyc"])
120122
added_files, removed_files, normal_files = [], [], []
121123
clean_files_list = [file.replace('"', '') for file in CURRENT_FILES]
122124

@@ -187,7 +189,7 @@ def dev_checks() -> None:
187189
- Updates configuration file with current files and version
188190
- Logs warnings or errors during the process
189191
"""
190-
FileManagement.mkdir()
192+
file_management.mkdir()
191193
if not _perform_checks():
192194
return
193195
_handle_file_operations()

CODE/bluetooth_details.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import json
44
import subprocess
5+
from typing import TextIO
56

67
from logicytics import log
78

@@ -84,7 +85,7 @@ def _query_bluetooth_devices() -> bool | list[dict[str, str]]:
8485
return device_info_list
8586

8687

87-
def _write_device_info_to_file(devices, filename):
88+
def _write_device_info_to_file(devices: list[dict[str, str]], filename: str):
8889
"""
8990
Writes the details of Bluetooth devices to a specified file.
9091
@@ -105,11 +106,12 @@ def _write_device_info_to_file(devices, filename):
105106
with open(filename, "w", encoding="UTF-8") as file:
106107
for device_info in devices:
107108
_write_single_device_info(file, device_info)
109+
log.info(f"Successfully wrote device details to '{filename}'")
108110
except Exception as e:
109111
log.error(f"Failed to write device information to file: {e}")
110112

111113

112-
def _write_single_device_info(file, device_info):
114+
def _write_single_device_info(file: TextIO, device_info: dict[str, str]):
113115
"""
114116
Writes detailed information for a single Bluetooth device to the specified file.
115117

CODE/bluetooth_logger.py

Lines changed: 5 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import datetime
22
import re
33
import subprocess
4+
from typing import LiteralString
45

56
from logicytics import log
67

78

89
# Utility function to log data to a file
9-
def save_to_file(filename, section_title, data):
10+
def save_to_file(filename: str, section_title: str, data: str):
1011
"""
1112
Appends data to a file with a section title.
1213
@@ -35,7 +36,7 @@ def save_to_file(filename, section_title, data):
3536

3637

3738
# Utility function to run PowerShell commands
38-
def run_powershell_command(command):
39+
def run_powershell_command(command: str) -> None | list[LiteralString]:
3940
"""
4041
Runs a PowerShell command and returns the output as a list of lines.
4142
@@ -67,7 +68,7 @@ def run_powershell_command(command):
6768

6869

6970
# Unified parsing function for PowerShell output
70-
def parse_output(lines, regex, group_names):
71+
def parse_output(lines: list[LiteralString], regex: str, group_names: list[str]):
7172
"""
7273
Parses the output lines using the provided regex and group names.
7374
@@ -101,7 +102,7 @@ def parse_output(lines, regex, group_names):
101102

102103

103104
# Function to get paired Bluetooth devices
104-
def get_paired_bluetooth_devices():
105+
def get_paired_bluetooth_devices() -> list[str]:
105106
"""
106107
Retrieves a list of paired Bluetooth devices with their names and MAC addresses.
107108
@@ -168,41 +169,6 @@ def log_bluetooth():
168169
save_to_file(filename, section_title, paired_devices or ["No paired Bluetooth devices found."])
169170
log.debug(f"{section_title}: {paired_devices}")
170171

171-
# Collect and log event logs
172-
def collect_logs(title: str, command: str):
173-
"""
174-
Collects and logs event logs by executing a PowerShell command and saving the results.
175-
176-
Args:
177-
title (str): The title or description of the log section being collected.
178-
command (str): The PowerShell command to execute for retrieving event logs.
179-
180-
Behavior:
181-
- Runs the specified PowerShell command using `run_powershell_command()`
182-
- Saves the log results to a file using `save_to_file()`
183-
- Logs an informational message about the log collection
184-
- If no logs are found, saves a default "No logs found." message
185-
- Uses the global `filename` variable for log file destination
186-
187-
Raises:
188-
Potential exceptions from `run_powershell_command()` and `save_to_file()` which are handled internally
189-
"""
190-
logs = run_powershell_command(command)
191-
save_to_file(filename, title, logs or ["No logs found."])
192-
log.info(f"Getting {title}...")
193-
194-
collect_logs(
195-
"Bluetooth Connection/Disconnection Logs",
196-
'Get-WinEvent -LogName "Microsoft-Windows-Bluetooth-BthLEServices/Operational" '
197-
'| Select-Object TimeCreated, Id, Message | Format-Table -AutoSize'
198-
)
199-
200-
collect_logs(
201-
"Bluetooth File Transfer Logs",
202-
'Get-WinEvent -LogName "Microsoft-Windows-Bluetooth-BthLEServices/Operational" '
203-
'| Select-String -Pattern "file.*transferred" | Format-Table -AutoSize'
204-
)
205-
206172
log.info("Finished Bluetooth data logging.")
207173

208174

CODE/cmd_commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from logicytics import log, Execute
1+
from logicytics import log, execute
22

33

44
@log.function
@@ -17,7 +17,7 @@ def command(file: str, commands: str, message: str, encoding: str = "UTF-8") ->
1717
"""
1818
log.info(f"Executing {message}")
1919
try:
20-
output = Execute.command(commands)
20+
output = execute.command(commands)
2121
with open(file, "w", encoding=encoding) as f:
2222
f.write(output)
2323
log.info(f"{message} Successful - {file}")

0 commit comments

Comments
 (0)