machineconfig 5.85__py3-none-any.whl → 5.87__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of machineconfig might be problematic. Click here for more details.

Files changed (32) hide show
  1. machineconfig/jobs/installer/installer_data.json +6 -6
  2. machineconfig/profile/create_links_export.py +9 -9
  3. machineconfig/scripts/python/agents.py +17 -17
  4. machineconfig/scripts/python/croshell.py +1 -1
  5. machineconfig/scripts/python/devops.py +8 -6
  6. machineconfig/scripts/python/devops_helpers/cli_config.py +10 -10
  7. machineconfig/scripts/python/devops_helpers/cli_nw.py +7 -6
  8. machineconfig/scripts/python/devops_helpers/cli_repos.py +20 -20
  9. machineconfig/scripts/python/devops_helpers/cli_self.py +6 -6
  10. machineconfig/scripts/python/devops_helpers/cli_share_server.py +2 -9
  11. machineconfig/scripts/python/helpers_repos/cloud_repo_sync.py +8 -8
  12. machineconfig/scripts/python/helpers_repos/grource.py +1 -1
  13. machineconfig/scripts/python/helpers_repos/secure_repo.py +6 -6
  14. machineconfig/scripts/python/interactive.py +2 -2
  15. machineconfig/scripts/python/nw/add_ssh_key.py +5 -5
  16. machineconfig/scripts/python/nw/devops_add_ssh_key.py +5 -5
  17. machineconfig/scripts/python/nw/mount_nfs +1 -1
  18. machineconfig/scripts/python/nw/ssh_debug_windows.py +338 -0
  19. machineconfig/scripts/python/repos_helpers/count_lines.py +4 -4
  20. machineconfig/scripts/python/repos_helpers/count_lines_frontend.py +3 -2
  21. machineconfig/scripts/python/sessions.py +15 -15
  22. machineconfig/scripts/python/sessions_helpers/sessions_multiprocess.py +4 -4
  23. machineconfig/scripts/windows/mounts/mount_ssh.ps1 +1 -1
  24. machineconfig/setup_linux/web_shortcuts/interactive.sh +1 -1
  25. machineconfig/setup_windows/web_shortcuts/interactive.ps1 +1 -1
  26. machineconfig/utils/installer_utils/installer.py +5 -5
  27. machineconfig/utils/ssh.py +1 -1
  28. {machineconfig-5.85.dist-info → machineconfig-5.87.dist-info}/METADATA +2 -2
  29. {machineconfig-5.85.dist-info → machineconfig-5.87.dist-info}/RECORD +32 -31
  30. {machineconfig-5.85.dist-info → machineconfig-5.87.dist-info}/WHEEL +0 -0
  31. {machineconfig-5.85.dist-info → machineconfig-5.87.dist-info}/entry_points.txt +0 -0
  32. {machineconfig-5.85.dist-info → machineconfig-5.87.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,338 @@
1
+
2
+
3
+ from platform import system
4
+ from machineconfig.utils.path_extended import PathExtended
5
+ from rich.console import Console
6
+ from rich.panel import Panel
7
+ from rich import box
8
+ import subprocess
9
+ import os
10
+
11
+ console = Console()
12
+
13
+
14
+ def ssh_debug_windows() -> dict[str, dict[str, str | bool]]:
15
+ """
16
+ Comprehensive SSH debugging function that checks for common pitfalls on Windows systems.
17
+
18
+ Returns a dictionary with diagnostic results for each check performed.
19
+ """
20
+ if system() != "Windows":
21
+ console.print(Panel("❌ This function is only supported on Windows systems", title="[bold red]Error[/bold red]", border_style="red"))
22
+ raise NotImplementedError("ssh_debug_windows is only supported on Windows")
23
+
24
+ console.print(Panel("🔍 SSH DEBUG - COMPREHENSIVE DIAGNOSTICS (WINDOWS)", box=box.DOUBLE_EDGE, title_align="left"))
25
+
26
+ results: dict[str, dict[str, str | bool]] = {}
27
+ issues_found: list[str] = []
28
+
29
+ ssh_dir = PathExtended.home().joinpath(".ssh")
30
+ authorized_keys = ssh_dir.joinpath("authorized_keys")
31
+
32
+ console.print(Panel("🔐 Checking SSH directory and authorized_keys...", title="[bold blue]File Permissions[/bold blue]", border_style="blue"))
33
+
34
+ if not ssh_dir.exists():
35
+ results["ssh_directory"] = {"status": "error", "message": "~/.ssh directory does not exist", "action": "Create with: mkdir %USERPROFILE%\\.ssh"}
36
+ issues_found.append("SSH directory missing")
37
+ console.print(Panel("❌ ~/.ssh directory does not exist\n💡 Run: mkdir %USERPROFILE%\\.ssh", title="[bold red]Critical Issue[/bold red]", border_style="red"))
38
+ else:
39
+ results["ssh_directory"] = {"status": "ok", "message": "~/.ssh directory exists", "action": ""}
40
+ console.print(Panel("✅ ~/.ssh directory exists", title="[bold green]OK[/bold green]", border_style="green"))
41
+
42
+ try:
43
+ icacls_check = subprocess.run(["icacls", str(ssh_dir)], capture_output=True, text=True, check=False)
44
+ if icacls_check.returncode == 0:
45
+ icacls_output = icacls_check.stdout
46
+ if "BUILTIN\\Administrators:(OI)(CI)(F)" in icacls_output or "NT AUTHORITY\\SYSTEM:(OI)(CI)(F)" in icacls_output:
47
+ console.print(Panel(f"ℹ️ ~/.ssh permissions:\n{icacls_output[:300]}", title="[bold blue]Info[/bold blue]", border_style="blue"))
48
+ except Exception:
49
+ pass
50
+
51
+ if not authorized_keys.exists():
52
+ results["authorized_keys"] = {"status": "warning", "message": "authorized_keys file does not exist", "action": "Create authorized_keys file and add public keys"}
53
+ issues_found.append("authorized_keys missing")
54
+ console.print(Panel("⚠️ authorized_keys file does not exist\n💡 Add your public key to %USERPROFILE%\\.ssh\\authorized_keys", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
55
+ else:
56
+ try:
57
+ key_count = len([line for line in authorized_keys.read_text(encoding="utf-8").split("\n") if line.strip()])
58
+ results["authorized_keys"] = {"status": "ok", "message": f"authorized_keys exists, contains {key_count} key(s)", "action": ""}
59
+ console.print(Panel(f"✅ authorized_keys file exists\n🔑 Contains {key_count} authorized key(s)", title="[bold green]OK[/bold green]", border_style="green"))
60
+
61
+ try:
62
+ icacls_check = subprocess.run(["icacls", str(authorized_keys)], capture_output=True, text=True, check=False)
63
+ if icacls_check.returncode == 0:
64
+ icacls_output = icacls_check.stdout
65
+ current_user = os.environ.get("USERNAME", "")
66
+ if f"{current_user}:(F)" in icacls_output or f"{current_user}:(M)" in icacls_output:
67
+ console.print(Panel(f"✅ authorized_keys permissions appear correct for user {current_user}", title="[bold green]OK[/bold green]", border_style="green"))
68
+ else:
69
+ console.print(Panel(f"⚠️ authorized_keys permissions may need adjustment\n💡 Run: icacls %USERPROFILE%\\.ssh\\authorized_keys /inheritance:r /grant \"{current_user}:F\"", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
70
+ except Exception:
71
+ pass
72
+ except Exception as read_error:
73
+ results["authorized_keys"] = {"status": "warning", "message": f"Could not read authorized_keys: {str(read_error)}", "action": "Check file encoding and permissions"}
74
+ console.print(Panel(f"⚠️ Could not read authorized_keys: {str(read_error)}", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
75
+
76
+ console.print(Panel("🔧 Checking SSH service status...", title="[bold blue]Service Status[/bold blue]", border_style="blue"))
77
+
78
+ try:
79
+ ssh_service_check = subprocess.run(["powershell", "-Command", "Get-Service -Name sshd -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Status"], capture_output=True, text=True, check=False)
80
+
81
+ if ssh_service_check.returncode == 0 and ssh_service_check.stdout.strip():
82
+ service_status = ssh_service_check.stdout.strip()
83
+ if service_status == "Running":
84
+ results["ssh_service"] = {"status": "ok", "message": "SSH service (sshd) is running", "action": ""}
85
+ console.print(Panel("✅ SSH service (sshd) is running", title="[bold green]OK[/bold green]", border_style="green"))
86
+
87
+ startup_type_check = subprocess.run(["powershell", "-Command", "Get-Service -Name sshd | Select-Object -ExpandProperty StartType"], capture_output=True, text=True, check=False)
88
+ if startup_type_check.returncode == 0:
89
+ startup_type = startup_type_check.stdout.strip()
90
+ if startup_type != "Automatic":
91
+ console.print(Panel(f"ℹ️ SSH service startup type: {startup_type}\n💡 To start automatically: Set-Service -Name sshd -StartupType Automatic", title="[bold blue]Info[/bold blue]", border_style="blue"))
92
+ else:
93
+ results["ssh_service"] = {"status": "error", "message": f"SSH service is {service_status}", "action": "Start with: Start-Service sshd"}
94
+ issues_found.append(f"SSH service {service_status}")
95
+ console.print(Panel(f"❌ SSH service is {service_status}\n💡 Start: Start-Service sshd\n💡 Enable on boot: Set-Service -Name sshd -StartupType Automatic", title="[bold red]Critical Issue[/bold red]", border_style="red"))
96
+ else:
97
+ results["ssh_service"] = {"status": "error", "message": "SSH service (sshd) not found", "action": "Install OpenSSH Server: Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0"}
98
+ issues_found.append("SSH service not installed")
99
+ console.print(Panel("❌ SSH service (sshd) not found\n💡 Install: Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0\n💡 Then start: Start-Service sshd", title="[bold red]Critical Issue[/bold red]", border_style="red"))
100
+ except Exception as service_error:
101
+ results["ssh_service"] = {"status": "warning", "message": f"Could not check service status: {str(service_error)}", "action": "Check SSH service manually"}
102
+ console.print(Panel(f"⚠️ Could not check SSH service status: {str(service_error)}\n💡 Check manually: Get-Service sshd", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
103
+
104
+ console.print(Panel("🌐 Checking network interfaces and IP addresses...", title="[bold blue]Network Interfaces[/bold blue]", border_style="blue"))
105
+
106
+ try:
107
+ ip_addr_check = subprocess.run(["powershell", "-Command", "Get-NetIPAddress -AddressFamily IPv4 -PrefixOrigin Dhcp,Manual | Where-Object {$_.IPAddress -notlike '127.*' -and $_.IPAddress -notlike '169.254.*'} | Select-Object -ExpandProperty IPAddress"], capture_output=True, text=True, check=False)
108
+ if ip_addr_check.returncode == 0 and ip_addr_check.stdout.strip():
109
+ ip_addresses = [ip.strip() for ip in ip_addr_check.stdout.strip().split("\n") if ip.strip()]
110
+
111
+ if ip_addresses:
112
+ results["network_interfaces"] = {"status": "ok", "message": f"Found {len(ip_addresses)} network interface(s)", "action": ""}
113
+ console.print(Panel("✅ Network interfaces found:\n" + "\n".join([f" • {ip}" for ip in ip_addresses]), title="[bold green]IP Addresses[/bold green]", border_style="green"))
114
+ else:
115
+ results["network_interfaces"] = {"status": "warning", "message": "No global IP addresses found", "action": "Check network configuration"}
116
+ issues_found.append("No network IP addresses")
117
+ console.print(Panel("⚠️ No global IP addresses found\n💡 This machine may not be reachable on the network\n💡 Check: Get-NetIPAddress", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
118
+ else:
119
+ results["network_interfaces"] = {"status": "warning", "message": "Could not retrieve IP addresses", "action": "Check network manually"}
120
+ console.print(Panel("⚠️ Could not retrieve IP addresses\n💡 Check: ipconfig", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
121
+ except Exception:
122
+ results["network_interfaces"] = {"status": "warning", "message": "Could not check network interfaces", "action": "Check network manually"}
123
+ console.print(Panel("⚠️ Could not check network interfaces\n💡 Try: ipconfig", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
124
+
125
+ console.print(Panel("🔌 Checking SSH port and listening status...", title="[bold blue]Network Status[/bold blue]", border_style="blue"))
126
+
127
+ sshd_config_paths = [PathExtended("C:\\ProgramData\\ssh\\sshd_config"), PathExtended(os.environ.get("PROGRAMDATA", "C:\\ProgramData")).joinpath("ssh", "sshd_config")]
128
+ sshd_config = None
129
+ for config_path in sshd_config_paths:
130
+ if config_path.exists():
131
+ sshd_config = config_path
132
+ break
133
+
134
+ ssh_port = "22"
135
+ if sshd_config:
136
+ try:
137
+ config_text = sshd_config.read_text(encoding="utf-8")
138
+ port_lines = [line for line in config_text.split("\n") if line.strip().startswith("Port") and not line.strip().startswith("#")]
139
+ if port_lines:
140
+ ssh_port = port_lines[0].split()[1]
141
+
142
+ results["sshd_config"] = {"status": "ok", "message": f"SSH configured to listen on port {ssh_port}", "action": ""}
143
+ console.print(Panel(f"✅ SSH configured to listen on port {ssh_port}", title="[bold green]Config[/bold green]", border_style="green"))
144
+
145
+ password_auth_lines = [line for line in config_text.split("\n") if "PasswordAuthentication" in line and not line.strip().startswith("#")]
146
+ if password_auth_lines:
147
+ password_auth_enabled = "yes" in password_auth_lines[-1].lower()
148
+ if not password_auth_enabled:
149
+ console.print(Panel("ℹ️ Password authentication is disabled\n💡 Only SSH keys will work", title="[bold blue]Info[/bold blue]", border_style="blue"))
150
+
151
+ pubkey_auth_lines = [line for line in config_text.split("\n") if "PubkeyAuthentication" in line and not line.strip().startswith("#")]
152
+ if pubkey_auth_lines:
153
+ pubkey_auth_enabled = "yes" in pubkey_auth_lines[-1].lower()
154
+ if not pubkey_auth_enabled:
155
+ results["pubkey_auth"] = {"status": "error", "message": "PubkeyAuthentication is disabled in sshd_config", "action": "Enable with: PubkeyAuthentication yes in sshd_config"}
156
+ issues_found.append("PubkeyAuthentication disabled")
157
+ console.print(Panel(f"❌ PubkeyAuthentication is DISABLED\n💡 Edit {sshd_config} and set: PubkeyAuthentication yes\n💡 Then restart: Restart-Service sshd", title="[bold red]Critical Issue[/bold red]", border_style="red"))
158
+ else:
159
+ results["pubkey_auth"] = {"status": "ok", "message": "PubkeyAuthentication is enabled", "action": ""}
160
+ console.print(Panel("✅ PubkeyAuthentication is enabled", title="[bold green]OK[/bold green]", border_style="green"))
161
+
162
+ authorized_keys_file_lines = [line for line in config_text.split("\n") if "AuthorizedKeysFile" in line and not line.strip().startswith("#")]
163
+ if authorized_keys_file_lines:
164
+ auth_keys_path = authorized_keys_file_lines[-1].split(None, 1)[1] if len(authorized_keys_file_lines[-1].split(None, 1)) > 1 else ".ssh/authorized_keys"
165
+ console.print(Panel(f"ℹ️ AuthorizedKeysFile: {auth_keys_path}", title="[bold blue]Info[/bold blue]", border_style="blue"))
166
+
167
+ admin_authorized_keys_lines = [line for line in config_text.split("\n") if "Match Group administrators" in line or "AuthorizedKeysFile __PROGRAMDATA__" in line]
168
+ if admin_authorized_keys_lines:
169
+ console.print(Panel("⚠️ IMPORTANT: Administrators group uses different authorized_keys location\n💡 For admin users, keys should be in: C:\\ProgramData\\ssh\\administrators_authorized_keys\n💡 Not in user's .ssh/authorized_keys!", title="[bold yellow]Admin Users[/bold yellow]", border_style="yellow"))
170
+
171
+ programdata_auth_keys = PathExtended(os.environ.get("PROGRAMDATA", "C:\\ProgramData")).joinpath("ssh", "administrators_authorized_keys")
172
+ if programdata_auth_keys.exists():
173
+ console.print(Panel("✅ administrators_authorized_keys file exists", title="[bold green]OK[/bold green]", border_style="green"))
174
+ else:
175
+ results["admin_authorized_keys"] = {"status": "warning", "message": "administrators_authorized_keys not found for admin users", "action": "Create C:\\ProgramData\\ssh\\administrators_authorized_keys"}
176
+ console.print(Panel("⚠️ administrators_authorized_keys not found\n💡 Create: C:\\ProgramData\\ssh\\administrators_authorized_keys\n💡 Set permissions: icacls C:\\ProgramData\\ssh\\administrators_authorized_keys /inheritance:r /grant SYSTEM:F /grant Administrators:F", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
177
+ except Exception as config_error:
178
+ results["sshd_config"] = {"status": "warning", "message": f"Could not read sshd_config: {str(config_error)}", "action": "Check SSH configuration manually"}
179
+ console.print(Panel(f"⚠️ Could not read sshd_config: {str(config_error)}", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
180
+ else:
181
+ results["sshd_config"] = {"status": "warning", "message": "sshd_config not found", "action": "Check SSH configuration manually"}
182
+ console.print(Panel("⚠️ sshd_config not found\n💡 Check if OpenSSH Server is installed\n💡 Expected location: C:\\ProgramData\\ssh\\sshd_config", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
183
+
184
+ try:
185
+ netstat_check = subprocess.run(["netstat", "-an"], capture_output=True, text=True, check=False)
186
+ if netstat_check.returncode == 0:
187
+ netstat_output = netstat_check.stdout
188
+ if f":{ssh_port}" in netstat_output and "LISTENING" in netstat_output:
189
+ ssh_lines = [line for line in netstat_output.split("\n") if f":{ssh_port}" in line and "LISTENING" in line]
190
+ listening_on_all = any("0.0.0.0" in line or "[::]" in line for line in ssh_lines)
191
+ listening_on_localhost_only = all("127.0.0.1" in line or "[::1]" in line for line in ssh_lines)
192
+
193
+ if listening_on_localhost_only:
194
+ results["ssh_listening"] = {"status": "error", "message": f"SSH is listening ONLY on localhost (127.0.0.1:{ssh_port}), not accessible from network", "action": f"Edit {sshd_config}, check ListenAddress, restart SSH"}
195
+ issues_found.append("SSH listening only on localhost")
196
+ console.print(Panel(f"❌ SSH is listening ONLY on localhost (127.0.0.1:{ssh_port})\n💡 This prevents external connections!\n💡 Check sshd_config for 'ListenAddress'\n💡 Remove or comment out 'ListenAddress 127.0.0.1'\n💡 Or change to 'ListenAddress 0.0.0.0'\n💡 Then: Restart-Service sshd", title="[bold red]Critical Issue[/bold red]", border_style="red"))
197
+ elif listening_on_all:
198
+ results["ssh_listening"] = {"status": "ok", "message": f"SSH is listening on all interfaces (0.0.0.0:{ssh_port})", "action": ""}
199
+ console.print(Panel(f"✅ SSH is listening on all interfaces (0.0.0.0:{ssh_port})\n✅ Should be accessible from network", title="[bold green]OK[/bold green]", border_style="green"))
200
+ else:
201
+ results["ssh_listening"] = {"status": "ok", "message": f"SSH is listening on port {ssh_port}", "action": ""}
202
+ console.print(Panel(f"✅ SSH is listening on port {ssh_port}\n\nListening on:\n" + "\n".join([f" {line.strip()}" for line in ssh_lines[:3]]), title="[bold green]OK[/bold green]", border_style="green"))
203
+ else:
204
+ results["ssh_listening"] = {"status": "error", "message": f"SSH is NOT listening on port {ssh_port}", "action": "Check if SSH service is running and configured correctly"}
205
+ issues_found.append(f"SSH not listening on port {ssh_port}")
206
+ console.print(Panel(f"❌ SSH is NOT listening on port {ssh_port}\n💡 Check: netstat -an | findstr :{ssh_port}\n💡 Restart: Restart-Service sshd", title="[bold red]Critical Issue[/bold red]", border_style="red"))
207
+ else:
208
+ results["ssh_listening"] = {"status": "warning", "message": "Could not check listening status", "action": "Check manually with: netstat -an"}
209
+ console.print(Panel("⚠️ Could not check listening status\n💡 Check manually: netstat -an | findstr :22", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
210
+ except Exception:
211
+ results["ssh_listening"] = {"status": "warning", "message": "Could not check listening status", "action": "Check manually"}
212
+ console.print(Panel("⚠️ Could not check listening status\n💡 Try: netstat -an | findstr :22", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
213
+
214
+ console.print(Panel("🧱 Checking Windows Firewall status...", title="[bold blue]Firewall[/bold blue]", border_style="blue"))
215
+
216
+ try:
217
+ firewall_check = subprocess.run(["powershell", "-Command", "Get-NetFirewallRule -DisplayName '*SSH*' | Select-Object DisplayName, Enabled, Direction, Action"], capture_output=True, text=True, check=False)
218
+ if firewall_check.returncode == 0 and firewall_check.stdout.strip():
219
+ firewall_output = firewall_check.stdout
220
+ ssh_rules_enabled = "True" in firewall_output and "Allow" in firewall_output
221
+
222
+ if ssh_rules_enabled:
223
+ results["firewall"] = {"status": "ok", "message": "Windows Firewall has SSH rules enabled", "action": ""}
224
+ console.print(Panel("✅ Windows Firewall has SSH rules enabled\n\n" + firewall_output[:300], title="[bold green]OK[/bold green]", border_style="green"))
225
+ else:
226
+ results["firewall"] = {"status": "error", "message": "Windows Firewall may be blocking SSH", "action": "Add firewall rule: New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22"}
227
+ issues_found.append("Firewall blocking SSH")
228
+ console.print(Panel("❌ Windows Firewall may be blocking SSH\n💡 Add rule: New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22", title="[bold red]Critical Issue[/bold red]", border_style="red"))
229
+ else:
230
+ firewall_status_check = subprocess.run(["powershell", "-Command", "Get-NetFirewallProfile | Select-Object Name, Enabled"], capture_output=True, text=True, check=False)
231
+ if firewall_status_check.returncode == 0:
232
+ console.print(Panel("⚠️ No SSH-specific firewall rules found\n💡 Add rule: New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
233
+ except Exception:
234
+ results["firewall"] = {"status": "warning", "message": "Could not check firewall status", "action": "Check manually"}
235
+ console.print(Panel("⚠️ Could not check Windows Firewall\n💡 Check manually: Get-NetFirewallRule -DisplayName '*SSH*'", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
236
+
237
+ console.print(Panel("👥 Checking user account and admin status...", title="[bold blue]User Account[/bold blue]", border_style="blue"))
238
+
239
+ try:
240
+ current_user = os.environ.get("USERNAME", "unknown")
241
+ admin_check = subprocess.run(["powershell", "-Command", "([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)"], capture_output=True, text=True, check=False)
242
+
243
+ is_admin = "True" in admin_check.stdout if admin_check.returncode == 0 else False
244
+
245
+ if is_admin:
246
+ results["user_account"] = {"status": "warning", "message": f"Current user ({current_user}) is an Administrator", "action": "Check administrators_authorized_keys location"}
247
+ console.print(Panel(f"⚠️ Current user ({current_user}) is an Administrator\n💡 Admin users may need keys in: C:\\ProgramData\\ssh\\administrators_authorized_keys\n💡 Not in %USERPROFILE%\\.ssh\\authorized_keys", title="[bold yellow]Important[/bold yellow]", border_style="yellow"))
248
+ else:
249
+ results["user_account"] = {"status": "ok", "message": f"Current user ({current_user}) is a standard user", "action": ""}
250
+ console.print(Panel(f"✅ Current user ({current_user}) is a standard user\n💡 Keys should be in: %USERPROFILE%\\.ssh\\authorized_keys", title="[bold green]OK[/bold green]", border_style="green"))
251
+ except Exception:
252
+ results["user_account"] = {"status": "warning", "message": "Could not check user account status", "action": ""}
253
+ console.print(Panel("⚠️ Could not check user account status", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
254
+
255
+ console.print(Panel("📋 Checking SSH logs for errors...", title="[bold blue]Logs[/bold blue]", border_style="blue"))
256
+
257
+ try:
258
+ log_check = subprocess.run(["powershell", "-Command", "Get-WinEvent -LogName 'OpenSSH/Admin' -MaxEvents 20 -ErrorAction SilentlyContinue | Where-Object {$_.LevelDisplayName -eq 'Error' -or $_.LevelDisplayName -eq 'Warning'} | Select-Object TimeCreated, LevelDisplayName, Message | Format-List"], capture_output=True, text=True, check=False)
259
+
260
+ if log_check.returncode == 0 and log_check.stdout.strip():
261
+ log_output = log_check.stdout
262
+ results["ssh_logs"] = {"status": "warning", "message": "Found SSH errors/warnings in event log", "action": "Review event log"}
263
+ console.print(Panel(f"⚠️ Found SSH errors/warnings:\n\n{log_output[:500]}", title="[bold yellow]Log Errors[/bold yellow]", border_style="yellow"))
264
+ else:
265
+ results["ssh_logs"] = {"status": "ok", "message": "No recent SSH errors in event log", "action": ""}
266
+ console.print(Panel("✅ No recent SSH errors in event log", title="[bold green]OK[/bold green]", border_style="green"))
267
+ except Exception:
268
+ results["ssh_logs"] = {"status": "warning", "message": "Could not check SSH logs", "action": "Check manually: Get-WinEvent -LogName 'OpenSSH/Admin'"}
269
+ console.print(Panel("⚠️ Could not check SSH logs\n💡 Check: Get-WinEvent -LogName 'OpenSSH/Admin' -MaxEvents 20", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
270
+
271
+ console.print(Panel("🧪 Testing local SSH connection...", title="[bold blue]Connection Test[/bold blue]", border_style="blue"))
272
+
273
+ try:
274
+ local_user = os.environ.get("USERNAME", "unknown")
275
+ ssh_test = subprocess.run(["ssh", "-o", "ConnectTimeout=5", "-o", "StrictHostKeyChecking=no", "-o", "BatchMode=yes", f"{local_user}@localhost", "echo", "test"], capture_output=True, text=True, check=False, timeout=10)
276
+
277
+ if ssh_test.returncode == 0:
278
+ results["local_ssh_test"] = {"status": "ok", "message": "Local SSH connection successful", "action": ""}
279
+ console.print(Panel("✅ Local SSH connection works\n✅ SSH server is functional", title="[bold green]OK[/bold green]", border_style="green"))
280
+ else:
281
+ error_output = ssh_test.stderr
282
+ results["local_ssh_test"] = {"status": "warning", "message": f"Local SSH test failed: {error_output[:100]}", "action": "Check SSH keys and configuration"}
283
+ console.print(Panel(f"⚠️ Local SSH test failed\n💡 Error: {error_output[:200]}\n💡 This may be normal if key authentication is not set up for localhost", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
284
+ except subprocess.TimeoutExpired:
285
+ results["local_ssh_test"] = {"status": "error", "message": "Local SSH connection timed out", "action": "SSH may be hanging or not responding"}
286
+ issues_found.append("SSH connection timeout")
287
+ console.print(Panel("❌ Local SSH connection timed out\n💡 SSH server may not be responding\n💡 Check: Get-Service sshd", title="[bold red]Critical Issue[/bold red]", border_style="red"))
288
+ except FileNotFoundError:
289
+ results["local_ssh_test"] = {"status": "warning", "message": "ssh client not found", "action": "Install SSH client: Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0"}
290
+ console.print(Panel("⚠️ SSH client not installed\n💡 Install: Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
291
+ except Exception as test_error:
292
+ results["local_ssh_test"] = {"status": "warning", "message": f"Could not test SSH: {str(test_error)}", "action": ""}
293
+ console.print(Panel(f"⚠️ Could not test SSH connection: {str(test_error)}", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
294
+
295
+ console.print(Panel("📊 DIAGNOSTIC SUMMARY", box=box.DOUBLE_EDGE, title_align="left"))
296
+
297
+ if issues_found:
298
+ console.print(Panel(f"⚠️ Found {len(issues_found)} issue(s):\n\n" + "\n".join([f"• {issue}" for issue in issues_found]), title="[bold yellow]Issues Found[/bold yellow]", border_style="yellow"))
299
+ else:
300
+ console.print(Panel("✅ No critical issues detected\n\nIf you still cannot connect:\n• Check client-side configuration\n• Verify network connectivity\n• Ensure correct username and hostname\n• Check if public key is correctly added to authorized_keys\n• For admin users, check C:\\ProgramData\\ssh\\administrators_authorized_keys", title="[bold green]All Checks Passed[/bold green]", border_style="green"))
301
+
302
+ console.print(Panel("🔗 CONNECTION INFORMATION", box=box.DOUBLE_EDGE, title_align="left"))
303
+
304
+ try:
305
+ current_user = os.environ.get("USERNAME", "unknown")
306
+ hostname_result = subprocess.run(["hostname"], capture_output=True, text=True, check=False)
307
+ hostname = hostname_result.stdout.strip() if hostname_result.returncode == 0 else "unknown"
308
+
309
+ ip_addr_result = subprocess.run(["powershell", "-Command", "Get-NetIPAddress -AddressFamily IPv4 -PrefixOrigin Dhcp,Manual | Where-Object {$_.IPAddress -notlike '127.*' -and $_.IPAddress -notlike '169.254.*'} | Select-Object -ExpandProperty IPAddress"], capture_output=True, text=True, check=False)
310
+ connection_ips: list[str] = []
311
+ if ip_addr_result.returncode == 0 and ip_addr_result.stdout.strip():
312
+ connection_ips = [ip.strip() for ip in ip_addr_result.stdout.strip().split("\n") if ip.strip()]
313
+
314
+ connection_info = f"👤 Username: {current_user}\n🖥️ Hostname: {hostname}\n🔌 SSH Port: {ssh_port}\n"
315
+
316
+ if connection_ips:
317
+ connection_info += "\n🌐 This machine can be accessed via SSH from other machines on the same network using:\n\n"
318
+ for ip in connection_ips:
319
+ connection_info += f" ssh {current_user}@{ip}\n"
320
+ if ssh_port != "22":
321
+ connection_info += f"\n (Port {ssh_port} should be used: ssh -p {ssh_port} {current_user}@<IP>)\n"
322
+ else:
323
+ connection_info += "\n⚠️ No network IP addresses found - this machine may not be reachable from the network"
324
+
325
+ connection_info += "\n\n💡 From another machine on the same network, use one of the commands above"
326
+ connection_info += "\n💡 Ensure your public key is in the correct authorized_keys location"
327
+ connection_info += "\n💡 For admin users: C:\\ProgramData\\ssh\\administrators_authorized_keys"
328
+ connection_info += "\n💡 For standard users: %USERPROFILE%\\.ssh\\authorized_keys"
329
+
330
+ console.print(Panel(connection_info, title="[bold cyan]SSH Connection Details[/bold cyan]", border_style="cyan"))
331
+ except Exception as conn_error:
332
+ console.print(Panel(f"⚠️ Could not gather connection information: {str(conn_error)}", title="[bold yellow]Connection Info[/bold yellow]", border_style="yellow"))
333
+
334
+ return results
335
+
336
+
337
+ if __name__ == "__main__":
338
+ ssh_debug_windows()
@@ -1,5 +1,5 @@
1
1
 
2
- from typing import TYPE_CHECKING
2
+ from typing import TYPE_CHECKING, Annotated
3
3
  from git import Repo
4
4
  from collections import defaultdict
5
5
  from datetime import datetime
@@ -82,7 +82,7 @@ def get_default_branch(repo: Repo) -> str:
82
82
 
83
83
 
84
84
  @app.command()
85
- def count_historical(repo_path: str = typer.Argument(..., help="Path to the git repository")):
85
+ def count_historical(repo_path: Annotated[str, typer.Argument(..., help="Path to the git repository")]):
86
86
  """Count total historical lines of Python code in the repository."""
87
87
  print(f"Analyzing repository: {repo_path}")
88
88
  total_loc: int = count_historical_loc(repo_path)
@@ -90,7 +90,7 @@ def count_historical(repo_path: str = typer.Argument(..., help="Path to the git
90
90
 
91
91
 
92
92
  @app.command()
93
- def analyze_over_time(repo_path: str = typer.Argument(..., help="Path to the git repository")):
93
+ def analyze_over_time(repo_path: Annotated[str, typer.Argument(..., help="Path to the git repository")]):
94
94
  """Analyze a git repository to track Python code size over time with visualization."""
95
95
  repo: Repo = Repo(repo_path)
96
96
  branch_name: str = get_default_branch(repo)
@@ -336,7 +336,7 @@ def _print_python_files_by_size_impl(repo_path: str) -> "Union[pl.DataFrame, Exc
336
336
 
337
337
 
338
338
  @app.command()
339
- def print_python_files_by_size(repo_path: str = typer.Argument(..., help="Path to the git repository")):
339
+ def print_python_files_by_size(repo_path: Annotated[str, typer.Argument(..., help="Path to the git repository")]):
340
340
  """Print Python files sorted by size with visualizations."""
341
341
  result = _print_python_files_by_size_impl(repo_path)
342
342
  if isinstance(result, Exception):
@@ -1,13 +1,14 @@
1
1
 
2
2
  import typer
3
+ from typing import Annotated
3
4
 
4
5
 
5
- def analyze_repo_development(repo_path: str = typer.Argument(..., help="Path to the git repository")):
6
+ def analyze_repo_development(repo_path: Annotated[str, typer.Argument(..., help="Path to the git repository")]):
6
7
  from machineconfig.scripts.python.repos_helpers import count_lines
7
8
  from pathlib import Path
8
9
  count_lines_path = Path(count_lines.__file__)
9
10
  # --project $HOME/code/ machineconfig --group plot
10
- cmd = f"""uv run --python 3.14 --with "machineconfig[plot]>=5.84" {count_lines_path} analyze-over-time {repo_path}"""
11
+ cmd = f"""uv run --python 3.14 --with "machineconfig[plot]>=5.87" {count_lines_path} analyze-over-time {repo_path}"""
11
12
  from machineconfig.utils.code import run_shell_script
12
13
  run_shell_script(cmd)
13
14
 
@@ -1,13 +1,13 @@
1
1
 
2
2
  from pathlib import Path
3
- from typing import Optional, Literal
3
+ from typing import Optional, Literal, Annotated
4
4
  import typer
5
5
 
6
- def balance_load(layout_path: Path = typer.Argument(..., help="Path to the layout.json file"),
7
- max_thresh: int = typer.Option(..., help="Maximum tabs per layout"),
8
- thresh_type: Literal['number', 'weight'] = typer.Option(..., help="Threshold type"),
9
- breaking_method: Literal['moreLayouts', 'combineTabs'] = typer.Option(..., help="Breaking method"),
10
- output_path: Optional[Path] = typer.Option(None, help="Path to write the adjusted layout.json file")):
6
+ def balance_load(layout_path: Annotated[Path, typer.Argument(..., help="Path to the layout.json file")],
7
+ max_thresh: Annotated[int, typer.Option(..., help="Maximum tabs per layout")],
8
+ thresh_type: Annotated[Literal['number', 'weight'], typer.Option(..., help="Threshold type")],
9
+ breaking_method: Annotated[Literal['moreLayouts', 'combineTabs'], typer.Option(..., help="Breaking method")],
10
+ output_path: Annotated[Optional[Path], typer.Option(..., help="Path to write the adjusted layout.json file")] = None):
11
11
  """Adjust layout file to limit max tabs per layout, etc."""
12
12
  from machineconfig.utils.schemas.layouts.layout_types import LayoutsFile
13
13
  import json
@@ -69,15 +69,15 @@ def find_layout_file(layout_path: str, ) -> Path:
69
69
 
70
70
 
71
71
  def run(ctx: typer.Context,
72
- layout_path: Optional[str] = typer.Argument(None, help="Path to the layout.json file"),
73
- max_tabs: int = typer.Option(10, help="A Sanity checker that throws an error if any layout exceeds the maximum number of tabs to launch."),
74
- max_layouts: int = typer.Option(10, help="A Sanity checker that throws an error if the total number of layouts exceeds this number."),
75
- sleep_inbetween: float = typer.Option(1.0, help="Sleep time in seconds between launching layouts"),
76
- monitor: bool = typer.Option(False, "--monitor", "-m", help="Monitor the layout sessions for completion"),
77
- parallel: bool = typer.Option(False, "--parallel", "-p", help="Launch multiple layouts in parallel"),
78
- kill_upon_completion: bool = typer.Option(False, "--kill-upon-completion", "-k", help="Kill session(s) upon completion (only relevant if monitor flag is set)"),
79
- choose: Optional[str] = typer.Option(None, "--choose", "-c", help="Comma separated names of layouts to be selected from the layout file passed"),
80
- choose_interactively: bool = typer.Option(False, "--choose-interactively", "-ia", help="Select layouts interactively")
72
+ layout_path: Annotated[Optional[str], typer.Argument(..., help="Path to the layout.json file")] = None,
73
+ max_tabs: Annotated[int, typer.Option(..., help="A Sanity checker that throws an error if any layout exceeds the maximum number of tabs to launch.")] = 10,
74
+ max_layouts: Annotated[int, typer.Option(..., help="A Sanity checker that throws an error if the total number of layouts exceeds this number.")] = 10,
75
+ sleep_inbetween: Annotated[float, typer.Option(..., help="Sleep time in seconds between launching layouts")] = 1.0,
76
+ monitor: Annotated[bool, typer.Option(..., "--monitor", "-m", help="Monitor the layout sessions for completion")] = False,
77
+ parallel: Annotated[bool, typer.Option(..., "--parallel", "-p", help="Launch multiple layouts in parallel")] = False,
78
+ kill_upon_completion: Annotated[bool, typer.Option(..., "--kill-upon-completion", "-k", help="Kill session(s) upon completion (only relevant if monitor flag is set)")] = False,
79
+ choose: Annotated[Optional[str], typer.Option(..., "--choose", "-c", help="Comma separated names of layouts to be selected from the layout file passed")] = None,
80
+ choose_interactively: Annotated[bool, typer.Option(..., "--choose-interactively", "-ia", help="Select layouts interactively")] = False
81
81
  ):
82
82
  """
83
83
  Launch terminal sessions based on a layout configuration file.
@@ -1,14 +1,14 @@
1
1
 
2
2
 
3
- from typing import Optional
3
+ from typing import Optional, Annotated
4
4
  from pathlib import Path
5
5
  import typer
6
6
 
7
7
 
8
8
  def create_from_function(
9
- num_process: int = typer.Option(..., "--num-process", "-n", help="Number of parallel processes to run"),
10
- path: str = typer.Option(".", "--path", "-p", help="Path to a Python or Shell script file or a directory containing such files"),
11
- function: Optional[str] = typer.Option(None, "--function", "-f", help="Function to run from the Python file. If not provided, you will be prompted to choose."),
9
+ num_process: Annotated[int, typer.Option(..., "--num-process", "-n", help="Number of parallel processes to run")],
10
+ path: Annotated[str, typer.Option(..., "--path", "-p", help="Path to a Python or Shell script file or a directory containing such files")] = ".",
11
+ function: Annotated[Optional[str], typer.Option(..., "--function", "-f", help="Function to run from the Python file. If not provided, you will be prompted to choose.")] = None,
12
12
  ):
13
13
  from machineconfig.utils.ve import get_ve_activate_line, get_ve_path_and_ipython_profile
14
14
  from machineconfig.utils.options import choose_from_options
@@ -7,7 +7,7 @@ $user = ''
7
7
  $sharePath = ''
8
8
  $driveLetter = ''
9
9
 
10
- uv run --python 3.14 --with "machineconfig>=5.84" python -m machineconfig.scripts.python.mount_ssh
10
+ uv run --python 3.14 --with "machineconfig>=5.87" python -m machineconfig.scripts.python.mount_ssh
11
11
 
12
12
  net use T: \\sshfs.kr\$user@$host.local
13
13
  # this worked: net use T: \\sshfs\alex@alex-p51s-5.local
@@ -1,7 +1,7 @@
1
1
  #!/bin/bash
2
2
  . <( curl -sSL "https://raw.githubusercontent.com/thisismygitrepo/machineconfig/main/src/machineconfig/setup_linux/uv.sh")
3
3
  mcfg() {
4
- "$HOME/.local/bin/uv" run --python 3.14 --with "machineconfig>="mcfg 5.84" mcfg "$@"
4
+ "$HOME/.local/bin/uv" run --python 3.14 --with "machineconfig>=5.87" mcfg "$@"
5
5
  }
6
6
  alias d="mcfg devops"
7
7
  alias c="mcfg cloud"
@@ -2,7 +2,7 @@
2
2
 
3
3
  iex (iwr "https://raw.githubusercontent.com/thisismygitrepo/machineconfig/main/src/machineconfig/setup_windows/uv.ps1").Content
4
4
  function mcfg {
5
- & "$HOME\.local\bin\uv.exe" run --python 3.14 --with "machineconfig>=5.84" mcfg $args
5
+ & "$HOME\.local\bin\uv.exe" run --python 3.14 --with "machineconfig>=5.87" mcfg $args
6
6
  }
7
7
  function d { mcfg devops @args }
8
8
  function c { mcfg cloud @args }
@@ -5,7 +5,7 @@ import typer
5
5
  from rich.console import Console
6
6
  from rich.panel import Panel
7
7
  from rich.table import Table
8
- from typing import Optional, cast, get_args
8
+ from typing import Optional, cast, get_args, Annotated
9
9
  from machineconfig.jobs.installer.package_groups import PACKAGE_GROUPS, PACKAGE_GROUP2NAMES
10
10
 
11
11
  console = Console()
@@ -56,9 +56,9 @@ def main_with_parser():
56
56
 
57
57
 
58
58
  def main(
59
- which: Optional[str] = typer.Argument(None, help="Comma-separated list of program/groups names to install (if --group flag is set)."),
60
- group: bool = typer.Option(False, "--group", "-g", help="Treat 'which' as a group name. A group is bundle of apps."),
61
- interactive: bool = typer.Option(False, "--interactive", "-ia", help="Interactive selection of programs to install."),
59
+ which: Annotated[Optional[str], typer.Argument(..., help="Comma-separated list of program/groups names to install (if --group flag is set).")] = None,
60
+ group: Annotated[bool, typer.Option(..., "--group", "-g", help="Treat 'which' as a group name. A group is bundle of apps.")] = False,
61
+ interactive: Annotated[bool, typer.Option(..., "--interactive", "-ia", help="Interactive selection of programs to install.")] = False,
62
62
  ) -> None:
63
63
  if interactive:
64
64
  return install_interactively()
@@ -189,7 +189,7 @@ def install_if_missing(which: str):
189
189
  return
190
190
  print(f"⏳ {which} not found. Installing...")
191
191
  from machineconfig.utils.installer_utils.installer import main
192
- main(which=which)
192
+ main(which=which, interactive=False)
193
193
 
194
194
 
195
195
  if __name__ == "__main__":
@@ -6,7 +6,7 @@ from machineconfig.utils.terminal import Response, MACHINE
6
6
  from machineconfig.utils.accessories import pprint
7
7
 
8
8
  UV_RUN_CMD = "$HOME/.local/bin/uv run"
9
- MACHINECONFIG_VERSION = "machineconfig>=5.84"
9
+ MACHINECONFIG_VERSION = "machineconfig>=5.87"
10
10
  DEFAULT_PICKLE_SUBDIR = "tmp_results/tmp_scripts/ssh"
11
11
 
12
12
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: machineconfig
3
- Version: 5.85
3
+ Version: 5.87
4
4
  Summary: Dotfiles management package
5
5
  Author-email: Alex Al-Saffar <programmer@usa.com>
6
6
  License: Apache 2.0
@@ -69,7 +69,7 @@ iex (iwr bit.ly/cfgwindows).Content
69
69
 
70
70
  ```bash
71
71
 
72
- . <(curl -sL bit.ly/cfglinux)
72
+ . <(curl -L bit.ly/cfglinux)
73
73
  ```
74
74
 
75
75