-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpsexec.py
More file actions
711 lines (559 loc) · 24.7 KB
/
psexec.py
File metadata and controls
711 lines (559 loc) · 24.7 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# psexec.py
"""
Remote command execution manager for HelpIT application.
This module replaces the PsExec binary wrapper with the pypsexec library,
which correctly captures stdout/stderr from remote processes.
PsExec v2.43+ broke output redirection via subprocess pipes; pypsexec
communicates directly over SMB and always returns the output reliably.
Dependencies:
pip install pypsexec smbprotocol
"""
import re
import csv
import sys
import logging
import shutil
import subprocess
from pathlib import Path
from pypsexec.client import Client
from utils import debug_print
from constants import DEFAULT_PSEXEC_TIMEOUT, DEFAULT_SCRIPT_TIMEOUT
class PsExecManager:
"""
Manages remote command execution on Windows machines using pypsexec.
pypsexec communicates over SMB (port 445) and correctly captures
stdout/stderr from all remote processes, unlike the PsExec binary
which lost output redirection in recent versions.
Attributes:
ip_address (str): IP address of the remote machine.
netbios (str): NetBIOS/hostname of the remote machine.
tmp_dir (str): Local temporary directory for CSV files.
psexec_path (str): Path to the bin folder (kept for open_terminal fallback).
"""
def __init__(self, ip_address: str, netbios: str, psexec_path: str, tmp_dir: str) -> None:
"""
Initializes the PsExecManager.
Args:
ip_address (str): IP address of the remote machine.
netbios (str): NetBIOS name of the remote machine.
psexec_path (str): Path to the bin folder (used for open_terminal only).
tmp_dir (str): Local temporary directory path for CSV output files.
"""
self.ip_address = ip_address
self.netbios = netbios
self.psexec_path = psexec_path
self.tmp_dir = tmp_dir
# Path to PsExec64.exe - kept only for open_terminal (interactive use)
self.psexec_bin = str(Path(psexec_path) / "PsExec64.exe")
# Create the local tmp directory if it does not exist
Path(self.tmp_dir).mkdir(parents=True, exist_ok=True)
logging.debug(f"[PSEXEC] PsExecManager initialized for {ip_address} ({netbios})")
def _run(self, executable: str, arguments: str = "",
use_system: bool = True, timeout: int = DEFAULT_PSEXEC_TIMEOUT) -> tuple[str, str, int] | tuple[None, None, None]:
"""
Executes a command on the remote machine via pypsexec.
Connects to the remote machine over SMB, runs the command as the
SYSTEM account (or current user), captures stdout and stderr, then
cleans up the remote service.
Args:
executable (str): Remote executable to run (e.g. "cmd.exe", "reg").
arguments (str): Command-line arguments string.
use_system (bool): Run as SYSTEM account if True (default True).
timeout (int): Timeout in seconds.
Returns:
tuple[str, str, int]: (stdout, stderr, return_code) decoded as UTF-8.
tuple[None, None, None]: If the connection or execution failed.
"""
logging.debug(f"[PSEXEC] Run: {executable} {arguments} on {self.ip_address}")
# Connect without explicit credentials - uses current Windows session (admin)
client = Client(self.ip_address, encrypt=False)
try:
client.connect()
client.create_service()
stdout_bytes, stderr_bytes, rc = client.run_executable(
executable,
arguments=arguments,
use_system_account=use_system,
timeout_seconds=timeout,
)
# Decode output - try UTF-8 first, fall back to cp850 (Windows console)
stdout = ""
stderr = ""
if stdout_bytes:
try:
stdout = stdout_bytes.decode("utf-8", errors="replace")
except Exception:
stdout = stdout_bytes.decode("cp850", errors="replace")
if stderr_bytes:
try:
stderr = stderr_bytes.decode("utf-8", errors="replace")
except Exception:
stderr = stderr_bytes.decode("cp850", errors="replace")
logging.debug(f"[PSEXEC] RC={rc} | stdout={stdout.strip()[:200]} | stderr={stderr.strip()[:200]}")
return stdout, stderr, rc
except Exception as e:
logging.error(f"[PSEXEC] Connection/execution error on {self.ip_address}: {e}")
return None, None, None
finally:
# Always clean up the remote service
try:
client.remove_service()
except Exception:
pass
try:
client.disconnect()
except Exception:
pass
def open_terminal(self) -> None:
"""
Opens an interactive CMD prompt on the remote machine.
Uses the PsExec64.exe binary directly because pypsexec does not
support interactive sessions. The console window is shown so the
user can type commands.
"""
if not Path(self.psexec_bin).exists():
logging.error(f"[PSEXEC] PsExec64.exe not found at {self.psexec_bin}")
return
command = [
self.psexec_bin, "-accepteula",
f"\\\\{self.ip_address}",
"cmd.exe"
]
# Use CREATE_NEW_CONSOLE so the window is visible and interactive
creationflags = subprocess.CREATE_NEW_CONSOLE if sys.platform == "win32" else 0
subprocess.Popen(
["start", "cmd", "/k"] + command,
shell=True,
creationflags=creationflags
)
logging.info(f"[PSEXEC] Interactive terminal opened for {self.ip_address}")
def get_product_name(self) -> str | None:
"""
Retrieves the Windows product name from the remote registry.
Queries HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion /v ProductName.
Returns:
str: Product name (e.g. "Windows 10 Pro") or None if not found.
"""
os_base = "Windows ancien"
stdout, stderr, rc = self._run(
"cmd.exe",
arguments=(
r'/c reg query '
r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" '
r'/v CurrentBuild'
)
)
if stdout:
match = re.search(r'CurrentBuild\s+REG_SZ\s+(.+)', stdout)
if match:
pn = match.group(1).strip()
if pn:
# Détection par build
if int(pn) >= 22000:
os_base = "Windows 11"
elif int(pn) >= 10000:
os_base = "Windows 10"
elif int(pn) >= 9600:
os_base = "Windows 8.1"
elif int(pn) >= 9200:
os_base = "Windows 8"
elif int(pn) >= 7600:
os_base = "Windows 7"
else:
os_base = "Windows"
debug_print(f"Product Name retrieved: {os_base}")
logging.info(f"[PSEXEC] ProductName={os_base}")
return os_base
logging.warning(f"[PSEXEC] Could not retrieve ProductName (rc={rc})")
return None
def get_pc_infos(self) -> str | None:
"""
Retrieves BIOS information from the remote machine via PowerShell CIM.
Runs Get-CimInstance Win32_BIOS to collect manufacturer, BIOS name,
SMBIOS version, version string, and serial number.
Returns:
str: Formatted multi-line string with each BIOS field on its own line,
or None if the command failed or returned no output.
Example output:
Manufacturer : American Megatrends International, LLC.
Name : F36
SMBIOSBIOSVersion : F36
Version : ALASKA - 1072009
SerialNumber : Default string
"""
ps_command = (
"Get-CimInstance -ClassName Win32_BIOS | "
"Select-Object Manufacturer, Name, SMBIOSBIOSVersion, Version, SerialNumber | "
"Format-List"
)
stdout, stderr, rc = self._run(
"powershell.exe",
arguments=f"-NoProfile -ExecutionPolicy Bypass -Command \"{ps_command}\"",
timeout=DEFAULT_PSEXEC_TIMEOUT
)
# Prefer stdout, fall back to stderr (some PS output lands in stderr)
output = (stdout or "").strip() or (stderr or "").strip()
if not output:
logging.warning("[PSEXEC] get_pc_infos: empty output")
return None
# Fields to extract, in display order
fields = [
"Manufacturer",
"Name",
"SMBIOSBIOSVersion",
"Version",
"SerialNumber",
]
# Parse "Key : Value" lines from the PowerShell Format-List output
parsed: dict[str, str] = {}
for line in output.splitlines():
line = line.strip()
if " : " in line:
key, _, value = line.partition(" : ")
key = key.strip()
value = value.strip()
if key in fields:
parsed[key] = value
if not parsed:
logging.warning("[PSEXEC] get_pc_infos: no fields parsed from output")
return None
# Build the formatted result string, one field per line
# Align values by padding keys to the length of the longest field name
max_key_len = max(len(k) for k in fields)
lines = []
for field in fields:
value = parsed.get(field, "N/A")
# Left-justify key with consistent padding for readability
lines.append(f"{field:<{max_key_len}} : {value}")
result = "\n".join(lines)
debug_print(f"PC infos retrieved:\n{result}")
logging.info(f"[PSEXEC] get_pc_infos OK for {self.ip_address}")
return result
def get_display_version(self) -> str | None:
"""
Retrieves the Windows display version from the remote registry.
Queries HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion /v DisplayVersion.
Returns:
str: Display version (e.g. "23H2") or None if not found.
"""
stdout, stderr, rc = self._run(
"cmd.exe",
arguments=(
r'/c reg query '
r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" '
r'/v DisplayVersion'
)
)
if stdout:
match = re.search(r'DisplayVersion\s+REG_SZ\s+(.+)
E865
9;, stdout, re.IGNORECASE)
if match:
dv = match.group(1).strip()
if dv:
debug_print(f"Display Version retrieved: {dv}")
logging.info(f"[PSEXEC] DisplayVersion={dv}")
return dv
logging.warning(f"[PSEXEC] Could not retrieve DisplayVersion (rc={rc})")
return None
def get_distinguished_name(self) -> str | None:
"""
Retrieves the Active Directory Distinguished Name of the remote machine.
Queries the Group Policy state registry key which is populated after
the machine has received GPOs from the domain controller.
Returns:
str: Distinguished Name (e.g. "CN=PC2,OU=Workstations,DC=...") or None.
"""
stdout, stderr, rc = self._run(
"cmd.exe",
arguments=(
r'/c reg query '
r'"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine" '
r'/v Distinguished-Name'
)
)
if stdout:
match = re.search(r'Distinguished-Name\s+REG_SZ\s+(.+)', stdout)
if match:
dn = match.group(1).strip()
if dn:
debug_print(f"Distinguished Name retrieved: {dn}")
logging.info(f"[PSEXEC] DN={dn}")
return dn
logging.warning(f"[PSEXEC] Could not retrieve Distinguished Name (rc={rc})")
return None
def get_active_user(self) -> str | None:
"""
Retrieves the currently active (logged-in) user on the remote machine.
Runs 'quser' and looks for the Active/Actif session line.
Returns:
str: Username of the active session, or None if no active session found.
"""
stdout, stderr, rc = self._run("quser", arguments="", use_system=False)
# quser output may be in stdout or stderr depending on the environment
output = (stdout or "") + (stderr or "")
for line in output.split("\n"):
if "Active" in line or "Actif" in line:
parts = line.split()
if parts:
username = parts[0].strip().lstrip(">")
debug_print(f"Active user retrieved: {username}")
logging.info(f"[PSEXEC] Active user={username}")
return username
logging.warning(f"[PSEXEC] Could not retrieve active user (rc={rc})")
return None
def get_processes_to_csv(self) -> Path | None:
"""
Retrieves the list of running processes and saves them to a CSV file.
Runs PowerShell Get-Process on the remote machine and filters out
common system processes. The result is saved locally as a CSV.
Returns:
Path: Path to the created CSV file, or None on failure.
"""
ps_command = (
"Get-Process | "
"Where-Object { $_.Name -notin @('System','svchost','wininit','lsass','services','csrss','smss','winlogon') } | "
"Select-Object Name,Id | Format-Table -AutoSize"
)
stdout, stderr, rc = self._run(
"powershell.exe",
arguments=f"-NoProfile -ExecutionPolicy Bypass -Command \"{ps_command}\"",
timeout=60
)
output = (stdout or "") + (stderr or "")
if not output.strip():
logging.warning("[PSEXEC] get_processes_to_csv: empty output")
return None
# Parse lines - skip header and separator lines
processes = set()
start_parsing = False
for line in output.split("\n"):
if "----" in line:
start_parsing = True
continue
if start_parsing and line.strip():
parts = line.split()
if parts:
process_name = parts[0].strip()
# Filter out pypsexec artifacts and non-process lines
if (process_name
and not process_name.isdigit()
and process_name not in ("Name", "exited", "on")):
processes.add(process_name)
# Write CSV file locally
csv_filename = Path(self.tmp_dir) / f"{self.netbios}_processus.csv"
if csv_filename.exists():
csv_filename.unlink()
with open(csv_filename, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["name"])
for process in sorted(processes):
writer.writerow([process])
debug_print(f"CSV created: {csv_filename} ({len(processes)} processes)")
logging.info(f"[PSEXEC] Processes CSV: {csv_filename} ({len(processes)} entries)")
return csv_filename
def kill_process(self, process_name: str) -> int:
"""
Kills a process by name on the remote machine.
Args:
process_name (str): Process name with or without the .exe extension.
Returns:
int: 1 if the process was killed successfully, 0 otherwise.
"""
# Ensure .exe extension is present
if not process_name.lower().endswith(".exe"):
process_name += ".exe"
stdout, stderr, rc = self._run(
"taskkill",
arguments=f"/IM {process_name} /F"
)
output = (stdout or "") + (stderr or "")
if rc == 0 or "SUCCESS" in output or "Opération réussie" in output:
logging.info(f"[PSEXEC] Process killed: {process_name}")
return 1
logging.warning(f"[PSEXEC] Failed to kill {process_name} (rc={rc})")
return 0
def get_services_to_csv(self) -> Path | None:
"""
Retrieves all Windows services and saves them to a CSV file.
Runs 'sc query state= all' on the remote machine and parses the
SERVICE_NAME, DISPLAY_NAME and STATE fields.
Returns:
Path: Path to the created CSV file, or None on failure.
"""
stdout, stderr, rc = self._run(
"sc",
arguments="query state= all",
timeout=60
)
output = (stdout or "") + (stderr or "")
if not output.strip():
logging.warning("[PSEXEC] get_services_to_csv: empty output")
return None
services = []
current_service: dict = {}
for line in output.split("\n"):
line = line.strip()
if line.startswith("SERVICE_NAME:"):
# Save the previous service before starting a new one
if current_service:
services.append(current_service)
service_id = line.split(":", 1)[1].strip()
current_service = {"id": service_id, "name": "", "etat": ""}
elif line.startswith("DISPLAY_NAME:") and current_service:
current_service["name"] = line.split(":", 1)[1].strip()
elif line.startswith("STATE") and current_service:
match = re.search(r"STATE\s*:\s*\d+\s+(\w+)", line)
if match:
current_service["etat"] = match.group(1)
# Don't forget the last service
if current_service:
services.append(current_service)
# Write CSV file locally
csv_filename = Path(self.tmp_dir) / f"{self.netbios}_services.csv"
if csv_filename.exists():
csv_filename.unlink()
with open(csv_filename, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile, delimiter=";")
writer.writerow(["id", "name", "etat"])
for svc in services:
writer.writerow([svc["id"], svc["name"], svc["etat"]])
debug_print(f"CSV created: {csv_filename} ({len(services)} services)")
logging.info(f"[PSEXEC] Services CSV: {csv_filename} ({len(services)} entries)")
return csv_filename
def get_service_status(self, service_name: str) -> int:
"""
Checks whether a specific service is running on the remote machine.
Args:
service_name (str): The service name (short name, not display name).
Returns:
int: 1 if the service is RUNNING, 0 otherwise.
"""
stdout, stderr, rc = self._run("sc", arguments=f"query {service_name}")
output = (stdout or "") + (stderr or "")
match = re.search(r"STATE\s*:\s*\d+\s+(\w+)", output)
if match and match.group(1).strip() == "RUNNING":
logging.info(f"[PSEXEC] Service {service_name} is RUNNING")
return 1
logging.info(f"[PSEXEC] Service {service_name} is NOT running")
return 0
def start_service(self, service_name: str) -> bool:
"""
Starts a service on the remote machine.
Args:
service_name (str): The service name (short name).
Returns:
bool: True if the command succeeded (rc=0), False otherwise.
"""
stdout, stderr, rc = self._run("sc", arguments=f"start {service_name}")
if rc == 0:
logging.info(f"[PSEXEC] Service started: {service_name}")
return True
logging.warning(f"[PSEXEC] Failed to start {service_name} (rc={rc})")
return False
def stop_service(self, service_name: str) -> bool:
"""
Stops a service on the remote machine.
Args:
service_name (str): The service name (short name).
Returns:
bool: True if the command succeeded (rc=0), False otherwise.
"""
stdout, stderr, rc = self._run("sc", arguments=f"stop {service_name}")
if rc == 0:
logging.info(f"[PSEXEC] Service stopped: {service_name}")
return True
logging.warning(f"[PSEXEC] Failed to stop {service_name} (rc={rc})")
return False
def restart_service(self, service_name: str) -> bool:
"""
Restarts a service on the remote machine by stopping then starting it.
Args:
service_name (str): The service name (short name).
Returns:
bool: True if both stop and start succeeded, False otherwise.
"""
stdout, stderr, rc = self._run(
"cmd.exe",
arguments=f"/c sc stop {service_name} && sc start {service_name}",
timeout=60
)
if rc == 0:
logging.info(f"[PSEXEC] Service restarted: {service_name}")
return True
logging.warning(f"[PSEXEC] Failed to restart {service_name} (rc={rc})")
return False
def run_script(self, script_file: Path, timeout: int = DEFAULT_SCRIPT_TIMEOUT) -> bool:
"""
Copies a script to the remote machine and executes it.
The script is copied via the administrative share (\\IP\\c$\\windows\\temp)
then executed remotely via pypsexec. Supported formats: .ps1, .bat, .cmd.
The temporary file is removed from the remote machine after execution.
Args:
script_file (Path): Path to the local script file.
timeout (int): Execution timeout in seconds. Defaults to DEFAULT_SCRIPT_TIMEOUT.
Returns:
bool: True if the script was copied and executed successfully.
Raises:
FileNotFoundError: If the local script file does not exist.
ValueError: If the file extension is not supported.
"""
script_file = Path(script_file)
if not script_file.exists():
raise FileNotFoundError(f"Script file not found: {script_file}")
extension = script_file.suffix.lower()
supported = [".ps1", ".bat", ".cmd"]
if extension not in supported:
raise ValueError(
f"Unsupported extension: {extension}. "
f"Supported: {', '.join(supported)}"
)
# Copy script to remote machine via network share
remote_share = f"\\\\{self.ip_address}\\c$\\windows\\temp\\"
remote_exec_path = f"C:\\windows\\temp\\{script_file.name}"
try:
shutil.copy2(script_file, remote_share)
logging.info(f"[PSEXEC] Script copied to {remote_share}{script_file.name}")
except Exception as e:
logging.error(f"[PSEXEC] Failed to copy script: {e}")
return False
# Build executable and arguments based on script type
if extension == ".ps1":
executable = "powershell.exe"
arguments = (
f"-NoProfile -ExecutionPolicy Bypass "
f"-File \"{remote_exec_path}\""
)
else:
# .bat or .cmd
executable = "cmd.exe"
arguments = f"/c \"{remote_exec_path}\""
logging.debug(f"[PSEXEC] Executing: {executable} {arguments}")
try:
stdout, stderr, rc = self._run(executable, arguments=arguments, timeout=timeout)
if rc == 0:
logging.info(f"[PSEXEC] Script executed successfully: {script_file.name}")
return True
logging.warning(f"[PSEXEC] Script failed (rc={rc}): {script_file.name}")
return False
finally:
# Clean up the remote script file
try:
remote_file = Path(f"\\\\{self.ip_address}\\c$\\windows\\temp\\{script_file.name}")
if remote_file.exists():
remote_file.unlink()
logging.info(f"[PSEXEC] Remote script cleaned up: {remote_file}")
except Exception as e:
logging.warning(f"[PSEXEC] Could not clean up remote script: {e}")
if __name__ == "__main__":
# Quick test - replace with a real IP and hostname
ip = "192.168.12.17"
hostname = "PC1"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s")
try:
mgr = PsExecManager(ip, hostname, r"bin", "tmp")
print(f"Product Name : {mgr.get_product_name()}")
print(f"Display Version: {mgr.get_display_version()}")
print(f"Active User : {mgr.get_active_user()}")
print(f"DN : {mgr.get_distinguished_name()}")
except Exception as e:
print(f"Error: {e}")