Skip to content

Commit 115245c

Browse files
Made the todo's linking config to many files
Added configuration settings to be changed to network_psutil.py, packet_sniffer.py and dump_memory.py Renamed global CONFIG var to config Signed-off-by: Shahm Najeeb <Nirt_12023@outlook.com>
1 parent e2bc66b commit 115245c

11 files changed

Lines changed: 103 additions & 58 deletions

File tree

.idea/csv-editor.xml

Lines changed: 16 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: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@
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, FileManagement, Flag, DEBUG, DELETE_LOGS, config
1616

1717
# Initialization
1818
log = Log({"log_level": DEBUG, "delete_log": DELETE_LOGS})
1919
ACTION, SUB_ACTION = None, None
20-
MAX_WORKERS = CONFIG.getint("Settings", "max_workers", fallback=min(32, (os.cpu_count() or 1) + 4))
20+
MAX_WORKERS = config.getint("Settings", "max_workers", fallback=min(32, (os.cpu_count() or 1) + 4))
2121
log.debug(f"MAX_WORKERS: {MAX_WORKERS}")
2222

2323

CODE/config.ini

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,14 +56,45 @@ model_debug = false
5656

5757
###################################################
5858

59+
[DumpMemory Settings]
60+
# If the file size generated exceeds this limit,
61+
# the file will be truncated with a message
62+
# Put 0 to disable the limit - Limit is in MiB - int
63+
file_size_limit = 0
64+
# Safety margin to check, it multiplies with the size limit
65+
# This makes sure that after the file is created, there is still
66+
# disk space left for other tasks,
67+
# Make sure its above 1 or else it will fail
68+
# Put 1 to disable the limit - Limit is in MiB - float
69+
file_size_safety = 1.5
70+
71+
###################################################
72+
73+
[NetWorkPsutil Settings]
74+
# Total time this will take will be `sample_count * interval`
75+
76+
# Number of samples to take for feature `measure network bandwidth usage`
77+
# This is an integer, and should be 1 and above
78+
sample_count = 5
79+
# Time between samples in seconds for feature `measure network bandwidth usage`
80+
# This is a float, and should be above 0
81+
interval = 1.5
82+
83+
###################################################
84+
5985
[PacketSniffer Settings]
6086
# The interface to sniff packets on, keep it as WiFi for most cases
6187
# Autocorrects between WiFi and Wi-Fi
6288
interface = WiFi
6389
# The number of packets to sniff,
64-
packet_count = 10000
65-
# The time to timeout the sniffing process
90+
# Must be greater than or equal to 1 - int
91+
packet_count = 5000
92+
# The time to timeout the sniffing process only,
93+
# Must be greater than or equal to 5 - int
6694
timeout = 10
95+
# The maximum retry time for the whole process,
96+
# Must be greater than or equal to 10 and timeout - int
97+
max_retry_time = 30
6798

6899
###################################################
69100

CODE/dump_memory.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55

66
import psutil
77

8-
from logicytics import log
8+
from logicytics import log, config
99

1010
# TODO v3.4.1
1111
# psutil.virtual_memory(): used, free, percent, total
1212
# psutil.swap_memory(): used, free, percent, total
1313

14-
# If the file size exceeds this limit, the file will be truncated with a message
15-
# Put 0 to disable the limit
16-
# TODO v3.4.1: Make this take from config.ini
17-
LIMIT_FILE_SIZE = 20 # Always in MiB
14+
LIMIT_FILE_SIZE = config.getint("DumpMemory Settings", "file_size_limit") # Always in MiB
15+
SAFETY_MARGIN = config.getfloat("DumpMemory Settings", "file_size_safety") # Always in MiB
16+
if SAFETY_MARGIN < 1:
17+
log.critical("Invalid Safety Margin Inputted - Cannot proceed with dump memory")
18+
exit(1)
1819

1920

2021
# Capture RAM Snapshot
@@ -41,7 +42,7 @@ def capture_ram_snapshot():
4142
log.info("Capturing RAM Snapshot...")
4243
memory = psutil.virtual_memory()
4344
swap = psutil.swap_memory()
44-
with open("Ram_Snapshot.txt", "w") as file:
45+
with open("memory_dumps/Ram_Snapshot.txt", "w") as file:
4546
try:
4647
file.write(f"Total RAM: {memory.total / (1024 ** 3):.2f} GB\n")
4748
file.write(f"Used RAM: {memory.used / (1024 ** 3):.2f} GB\n")
@@ -91,13 +92,13 @@ def gather_system_info():
9192
except Exception as e:
9293
log.error(f"Error gathering system information: {e}")
9394
sys_info = {'Error': 'Failed to gather system information'}
94-
with open("SystemRam_Info.txt", "w") as file:
95+
with open("memory_dumps/SystemRam_Info.txt", "w") as file:
9596
for key, value in sys_info.items():
9697
file.write(f"{key}: {value}\n")
9798
log.info("System Information saved to SystemRam_Info.txt")
9899

99100

100-
# Memory Dump (Windows-specific, using psutil)
101+
# Memory Dump
101102
def memory_dump():
102103
"""
103104
Perform a memory dump of the current process, capturing detailed metadata for each readable memory region.
@@ -127,12 +128,12 @@ def memory_dump():
127128

128129
try:
129130
process = psutil.Process(pid)
130-
with open("Ram_Dump.txt", "wb") as dump_file:
131+
with open("memory_dumps/Ram_Dump.txt", "wb") as dump_file:
131132
total_size = 0
132133
for mem_region in process.memory_maps(grouped=False):
133134
# Check available disk space
134135
if os.path.exists("Ram_Dump.txt"):
135-
required_space = LIMIT_FILE_SIZE * 1024 * 1024 * 1.5 # 2x safety margin
136+
required_space = LIMIT_FILE_SIZE * 1024 * 1024 * SAFETY_MARGIN # 2x safety margin
136137
free_space = psutil.disk_usage(".").free
137138
if free_space < required_space:
138139
log.error(f"Not enough disk space. Need {required_space / 1024 / 1024:.2f}MB")
@@ -206,6 +207,7 @@ def main():
206207
No parameters.
207208
No return value.
208209
"""
210+
os.makedirs("memory_dumps", exist_ok=True)
209211
log.info("Starting system memory collection tasks...")
210212
capture_ram_snapshot()
211213
gather_system_info()

CODE/logicytics/Config.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __config_data() -> tuple[str, str, list[str], bool, str]:
1515
- Version (str): System version from configuration
1616
- Files (list[str]): List of files specified in configuration
1717
- Delete old logs (bool): Flag indicating whether to delete old log files
18-
- CONFIG itself
18+
- config itself
1919
2020
Raises:
2121
SystemExit: If the 'config.ini' file cannot be found in any of the attempted locations
@@ -30,21 +30,21 @@ def _config_path() -> str:
3030
print("The config.ini file is not found in the expected location.")
3131
exit(1)
3232

33-
config = configparser.ConfigParser()
33+
config_local = configparser.ConfigParser()
3434
path = _config_path()
35-
config.read(path)
35+
config_local.read(path)
3636

37-
log_using_debug = config.getboolean("Settings", "log_using_debug")
38-
delete_old_logs = config.getboolean("Settings", "delete_old_logs")
39-
version = config.get("System Settings", "version")
40-
files = config.get("System Settings", "files").split(", ")
37+
log_using_debug = config_local.getboolean("Settings", "log_using_debug")
38+
delete_old_logs = config_local.getboolean("Settings", "delete_old_logs")
39+
version = config_local.get("System Settings", "version")
40+
files = config_local.get("System Settings", "files").split(", ")
4141

4242
log_using_debug = "DEBUG" if log_using_debug else "INFO"
4343

44-
return log_using_debug, version, files, delete_old_logs, config
44+
return log_using_debug, version, files, delete_old_logs, config_local
4545

4646

4747
# Check if the script is being run directly, if not, set up the library
4848
if __name__ == '__main__':
4949
exit("This is a library, Please import rather than directly run.")
50-
DEBUG, VERSION, CURRENT_FILES, DELETE_LOGS, CONFIG = __config_data()
50+
DEBUG, VERSION, CURRENT_FILES, DELETE_LOGS, config = __config_data()

CODE/logicytics/Flag.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,23 @@
88
from collections import Counter
99
from datetime import datetime
1010

11-
from logicytics.Config import CONFIG
11+
from logicytics.Config import config
1212

1313
# Check if the script is being run directly, if not, set up the library
1414
if __name__ == '__main__':
1515
exit("This is a library, Please import rather than directly run.")
1616
else:
1717
# Save user preferences?
18-
SAVE_PREFERENCES = CONFIG.getboolean("Settings", "save_preferences")
18+
SAVE_PREFERENCES = config.getboolean("Settings", "save_preferences")
1919
# Debug mode for Sentence Transformer
20-
DEBUG_MODE = CONFIG.getboolean("Flag Settings", "model_debug") # Debug mode for Sentence Transformer
20+
DEBUG_MODE = config.getboolean("Flag Settings", "model_debug") # Debug mode for Sentence Transformer
2121
# File for storing user history data
2222
HISTORY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'User_History.json.gz') # User history file
2323
# Minimum accuracy threshold for flag suggestions
2424
MIN_ACCURACY_THRESHOLD = float(
25-
CONFIG.get("Flag Settings", "accuracy_min")) # Minimum accuracy threshold for flag suggestions
26-
if not 0 <= MIN_ACCURACY_THRESHOLD <= 100:
27-
raise ValueError("accuracy_min must be between 0 and 100")
25+
config.get("Flag Settings", "accuracy_min")) # Minimum accuracy threshold for flag suggestions
26+
if not 1 <= MIN_ACCURACY_THRESHOLD <= 99:
27+
raise ValueError("accuracy_min must be between 1 and 99")
2828

2929

3030
class _Match:
@@ -61,11 +61,11 @@ def __get_sim(user_input: str, all_descriptions: list[str]) -> list[float]:
6161
logging.getLogger("sentence_transformers").setLevel(logging.ERROR)
6262

6363
try:
64-
MODEL = SentenceTransformer(CONFIG.get("Flag Settings", "model_to_use"))
64+
MODEL = SentenceTransformer(config.get("Flag Settings", "model_to_use"))
6565
except Exception as e:
6666
print(f"Error: {e}")
6767
print("Please check the model name in the config file.")
68-
print(f"Model name {CONFIG.get('Flag Settings', 'model_to_use')} may not be valid.")
68+
print(f"Model name {config.get('Flag Settings', 'model_to_use')} may not be valid.")
6969
exit(1)
7070

7171
user_embedding = MODEL.encode(user_input, convert_to_tensor=True, show_progress_bar=DEBUG_MODE)

CODE/logicytics/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import traceback
33

44
from logicytics.Checks import Check
5-
from logicytics.Config import DEBUG, VERSION, CURRENT_FILES, DELETE_LOGS, CONFIG
5+
from logicytics.Config import DEBUG, VERSION, CURRENT_FILES, DELETE_LOGS, config
66
from logicytics.Execute import Execute
77
from logicytics.FileManagement import FileManagement
88
from logicytics.Flag import Flag

CODE/network_psutil.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,18 @@
44

55
import psutil
66

7-
from logicytics import log, Execute
7+
from logicytics import log, Execute, config
88

99

1010
class NetworkInfo:
1111
"""
1212
A class to gather and save various network-related information.
1313
"""
1414

15+
def __init__(self):
16+
self.SAMPLE_COUNT = config.getint("NetWorkPsutil Settings", "sample_count")
17+
self.INTERVAL = config.getfloat("NetWorkPsutil Settings", "interval")
18+
1519
@log.function
1620
async def get(self):
1721
"""
@@ -24,7 +28,7 @@ async def get(self):
2428
self.__fetch_network_interface_stats()
2529
self.__execute_external_network_command()
2630
self.__fetch_network_connections_with_process_info()
27-
await self.__measure_network_bandwidth_usage()
31+
await self.__measure_network_bandwidth_usage(sample_count=self.SAMPLE_COUNT, interval=self.INTERVAL)
2832
self.__fetch_hostname_and_ip()
2933
except Exception as e:
3034
log.error(f"Error getting network info: {e}, Type: {type(e).__name__}")
@@ -133,7 +137,9 @@ async def __measure_network_bandwidth_usage(self, sample_count: int = 5, interva
133137
sample_count: Number of samples to take (default: 5)
134138
interval: Time between samples in seconds (default: 1.0)
135139
"""
136-
# TODO v3.4.1: Allow config.ini to set values
140+
if sample_count < 1 or interval <= 0:
141+
log.critical(
142+
"Invalid values passed down from configuration for `NetworkInfo.__measure_network_bandwidth_usage()`")
137143
log.debug("Measuring network bandwidth usage...")
138144
samples = []
139145
for _ in range(sample_count):

CODE/packet_sniffer.py

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from __future__ import annotations
22

3-
import os
4-
import warnings
53
from time import time
64

75
import matplotlib.pyplot as plt
@@ -10,13 +8,7 @@
108
from scapy.all import sniff, conf
119
from scapy.layers.inet import IP, TCP, UDP, ICMP
1210

13-
from logicytics import log, CONFIG
14-
15-
# Read configuration from config.ini
16-
CONFIG.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.ini"))
17-
config = CONFIG['PacketSniffer Settings']
18-
# Ignore all warnings (Wireshark issue)
19-
warnings.filterwarnings("ignore")
11+
from logicytics import log, config
2012

2113

2214
class Sniff:
@@ -361,24 +353,24 @@ def correct_interface_name(interface_name: str) -> str:
361353
}
362354
return corrections.get(interface_name, interface_name)
363355

364-
interface = config['interface']
365-
packet_count = int(config['packet_count'])
366-
timeout = int(config['timeout'])
356+
interface = config.get("PacketSniffer Settings", "interface")
357+
packet_count = config.getint("PacketSniffer Settings", "packet_count")
358+
timeout = config.getint("PacketSniffer Settings", "timeout")
359+
max_retry_time = config.getint("PacketSniffer Settings", "max_retry_time")
367360

368-
if packet_count <= 0 or timeout <= 0:
361+
if packet_count < 1 or timeout < 5 or max_retry_time < 10 or max_retry_time < timeout:
369362
try:
370-
log.error(
371-
"Oops! Can't work with these values (Not your fault):\n"
372-
f" - Packet count: {packet_count} {'❌ (must be > 0)' if packet_count <= 0 else '✅'}\n"
373-
f" - Timeout: {timeout} {'❌ (must be > 0)' if timeout <= 0 else '✅'}"
363+
log.critical(
364+
"Oops! Can't work with these values):\n"
365+
f" - Packet count: {packet_count} {'❌ (must be > 0)' if packet_count < 1 else '✅'}\n"
366+
f" - Timeout: {timeout} {'❌ (must be >= 5)' if timeout < 5 else '✅'}\n"
367+
f" - Max Retry Time: {max_retry_time} {'❌ (must be >= 10 and larger than timeout)' if max_retry_time < 10 or max_retry_time < timeout else '✅'}"
374368
)
375369
except Exception:
376-
log.error("Error reading configuration: Improper values for packet count or timeout")
370+
log.critical("Error reading configuration: Improper values for packet count or timeout")
377371
exit(1)
378372

379373
start_time = time()
380-
# TODO v3.4.1 -> Config.ini controlled value
381-
max_retry_time = 30 # seconds
382374
for attempt in range(2): # Try original and corrected name
383375
try:
384376
if time() - start_time > max_retry_time:

CODE/vulnscan.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@
2323
# Use Asynchronous File Scanning,
2424
# Optimize Model Loading and Caching,
2525
# Improve Feature Extraction
26-
27-
# TODO: v3.4.1
2826
# also add a global variable called MAX_FILE_SIZE, if its none ignore it, else only scan files under that file size (default at 50MB)
2927
# add this to config.ini -> max_workers = min(32, os.cpu_count() * 2)
3028
# add UNREADABLE_EXTENSIONS as well to config.ini

0 commit comments

Comments
 (0)