-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_script.py
More file actions
266 lines (215 loc) Β· 8.54 KB
/
Copy pathtest_script.py
File metadata and controls
266 lines (215 loc) Β· 8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
#!/usr/bin/env python3
"""
Installation Test Script for Behavioral Monitor
This script tests if all dependencies are properly installed
"""
import sys
import time
import subprocess
def check_python_version():
"""Check if Python version is compatible"""
version = sys.version_info
print(f"π Python version: {version.major}.{version.minor}.{version.micro}")
if version.major < 3 or (version.major == 3 and version.minor < 7):
print("β Python 3.7+ required")
return False
else:
print("β
Python version compatible")
return True
def install_dependencies():
"""Install required packages"""
packages = ['pynput', 'psutil']
print("\nπ¦ Installing dependencies...")
for package in packages:
try:
print(f"Installing {package}...")
subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
print(f"β
{package} installed successfully")
except subprocess.CalledProcessError:
print(f"β Failed to install {package}")
print(f"π‘ Try manually: pip install {package}")
return False
return True
def test_imports():
"""Test if all required modules can be imported"""
print("\nπ Testing imports...")
try:
import pynput
from pynput import keyboard, mouse
print("β
pynput imported successfully")
except ImportError as e:
print(f"β pynput import failed: {e}")
return False
try:
import psutil
print("β
psutil imported successfully")
except ImportError as e:
print(f"β psutil import failed: {e}")
return False
try:
import threading, queue, json, statistics, time
from collections import deque, defaultdict
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict
print("β
Standard library imports successful")
except ImportError as e:
print(f"β Standard library import failed: {e}")
return False
return True
def test_permissions():
"""Test if we have required permissions"""
print("\nπ Testing permissions...")
try:
from pynput import keyboard, mouse
# Test keyboard listener creation
def dummy_key_handler(key):
pass
def dummy_mouse_handler(*args):
pass
# Create listeners without starting them
kb_listener = keyboard.Listener(on_press=dummy_key_handler)
mouse_listener = mouse.Listener(on_move=dummy_mouse_handler)
print("β
Listeners created successfully")
print("π‘ Actual permissions will be tested during monitoring")
return True
except Exception as e:
print(f"β Permission test failed: {e}")
print("π‘ You may need to grant accessibility permissions")
return False
def run_quick_test():
"""Run a quick 10-second monitoring test"""
print("\nπ§ͺ Running monitoring test...")
print("π Please type something and move your mouse in the next 10 seconds...")
try:
# Import the behavioral monitor
sys.path.append('.') # Add current directory to path
# Create a minimal test version
from pynput import keyboard, mouse
import threading
import queue
events_recorded = {'keystrokes': 0, 'mouse_moves': 0, 'mouse_clicks': 0}
event_queue = queue.Queue()
def on_key_press(key):
event_queue.put(('keystroke', time.time()))
def on_mouse_move(x, y):
event_queue.put(('mouse_move', time.time()))
def on_mouse_click(x, y, button, pressed):
if pressed:
event_queue.put(('mouse_click', time.time()))
# Start listeners
kb_listener = keyboard.Listener(on_press=on_key_press)
mouse_listener = mouse.Listener(
on_move=on_mouse_move,
on_click=on_mouse_click
)
kb_listener.start()
mouse_listener.start()
# Monitor for 10 seconds
start_time = time.time()
while time.time() - start_time < 10:
try:
event_type, timestamp = event_queue.get_nowait()
events_recorded[event_type] = events_recorded.get(event_type, 0) + 1
except queue.Empty:
pass
time.sleep(0.1)
# Stop listeners
kb_listener.stop()
mouse_listener.stop()
# Show results
print(f"\nπ Test Results:")
print(f" Keystrokes: {events_recorded.get('keystroke', 0)}")
print(f" Mouse moves: {events_recorded.get('mouse_move', 0)}")
print(f" Mouse clicks: {events_recorded.get('mouse_click', 0)}")
total_events = sum(events_recorded.values())
if total_events > 0:
print("β
Monitoring test successful!")
return True
else:
print("β οΈ No events recorded - check permissions")
return False
except Exception as e:
print(f"β Monitoring test failed: {e}")
return False
def show_platform_specific_help():
"""Show platform-specific setup instructions"""
import platform
os_name = platform.system().lower()
print(f"\nπ₯οΈ Platform-specific setup ({os_name}):")
if os_name == "darwin": # macOS
print("""
macOS Setup:
1. System Preferences β Security & Privacy β Privacy β Accessibility
2. Add Terminal (or your Python IDE) to allowed applications
3. You may need to add Python itself to the list
4. For macOS Catalina+: Also add to "Full Disk Access" if needed
If still having issues:
- Run: sudo python test_installation.py
- Temporarily disable SIP (not recommended for production)
""")
elif os_name == "linux":
print("""
Linux Setup:
1. Install X11 development libraries:
sudo apt-get install python3-xlib # Ubuntu/Debian
sudo yum install python3-xlib # CentOS/RHEL
2. If running in virtual environment, ensure packages are installed there
3. For Wayland users: May need X11 compatibility layer
4. Run with sudo if permission issues persist
""")
elif os_name == "windows":
print("""
Windows Setup:
1. Run Command Prompt as Administrator
2. Add script to Windows Defender exclusions if needed
3. Some antivirus software may block keyboard monitoring
PowerShell alternative:
Start-Process python -ArgumentList "test_installation.py" -Verb RunAs
""")
def main():
"""Main installation test function"""
print("π§ Behavioral Monitor - Installation Test")
print("=" * 50)
# Check Python version
if not check_python_version():
return False
# Install dependencies
install_choice = input("\nπ¦ Install dependencies automatically? (y/n): ").lower().strip()
if install_choice == 'y':
if not install_dependencies():
return False
else:
print("π‘ Please install manually: pip install pynput psutil")
# Test imports
if not test_imports():
print("\nβ Import test failed. Try reinstalling dependencies.")
return False
# Test permissions
if not test_permissions():
show_platform_specific_help()
return False
# Run monitoring test
test_choice = input("\nπ§ͺ Run 10-second monitoring test? (y/n): ").lower().strip()
if test_choice == 'y':
if not run_quick_test():
print("\nβ οΈ Monitoring test had issues. Check permissions.")
show_platform_specific_help()
return False
print("\n" + "=" * 50)
print("π Installation test completed successfully!")
print("\nNext steps:")
print("1. Save the main behavioral_monitor.py script")
print("2. Run: python behavioral_monitor.py")
print("3. Check the setup guide for advanced configuration")
return True
if __name__ == "__main__":
try:
success = main()
if not success:
print("\nβ Installation test failed. Check error messages above.")
sys.exit(1)
except KeyboardInterrupt:
print("\n\nβΉοΈ Installation test interrupted by user.")
except Exception as e:
print(f"\nβ Unexpected error: {e}")
sys.exit(1)