machineconfig 5.78__py3-none-any.whl → 5.81__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.
- machineconfig/scripts/python/devops_helpers/cli_nw.py +15 -2
- machineconfig/scripts/python/{devops_helpers → nw}/devops_add_ssh_key.py +1 -13
- machineconfig/scripts/python/nw/ssh_debug_linux.py +299 -0
- {machineconfig-5.78.dist-info → machineconfig-5.81.dist-info}/METADATA +1 -1
- {machineconfig-5.78.dist-info → machineconfig-5.81.dist-info}/RECORD +8 -8
- machineconfig/scripts/python/devops_helpers/devops_add_identity.py +0 -84
- {machineconfig-5.78.dist-info → machineconfig-5.81.dist-info}/WHEEL +0 -0
- {machineconfig-5.78.dist-info → machineconfig-5.81.dist-info}/entry_points.txt +0 -0
- {machineconfig-5.78.dist-info → machineconfig-5.81.dist-info}/top_level.txt +0 -0
|
@@ -18,17 +18,18 @@ def install_ssh_server():
|
|
|
18
18
|
from machineconfig.utils.code import run_shell_script
|
|
19
19
|
run_shell_script(script=SSH_SERVER.read_text(encoding="utf-8"))
|
|
20
20
|
|
|
21
|
+
|
|
21
22
|
def add_ssh_key(path: Optional[str] = typer.Option(None, help="Path to the public key file"),
|
|
22
23
|
choose: bool = typer.Option(False, "--choose", "-c", help="Choose from available public keys in ~/.ssh/*.pub"),
|
|
23
24
|
value: bool = typer.Option(False, "--value", "-v", help="Paste the public key content manually"),
|
|
24
25
|
github: Optional[str] = typer.Option(None, "--github", "-g", help="Fetch public keys from a GitHub username")
|
|
25
26
|
):
|
|
26
27
|
"""🔑 SSH add pub key to this machine so its accessible by owner of corresponding private key."""
|
|
27
|
-
import machineconfig.scripts.python.
|
|
28
|
+
import machineconfig.scripts.python.nw.devops_add_ssh_key as helper
|
|
28
29
|
helper.main(pub_path=path, pub_choose=choose, pub_val=value, from_github=github)
|
|
29
30
|
def add_ssh_identity():
|
|
30
31
|
"""🗝️ SSH add identity (private key) to this machine"""
|
|
31
|
-
import machineconfig.scripts.python.
|
|
32
|
+
import machineconfig.scripts.python.nw.devops_add_identity as helper
|
|
32
33
|
helper.main()
|
|
33
34
|
|
|
34
35
|
|
|
@@ -41,6 +42,16 @@ def show_address():
|
|
|
41
42
|
print(f"This computer is @ {local_ip_v4}")
|
|
42
43
|
|
|
43
44
|
|
|
45
|
+
def debug_ssh():
|
|
46
|
+
"""🐛 SSH debug"""
|
|
47
|
+
from platform import system
|
|
48
|
+
if system() == "Linux" or system() == "Darwin":
|
|
49
|
+
import machineconfig.scripts.python.nw.ssh_debug_linux as helper
|
|
50
|
+
helper.ssh_debug_linux()
|
|
51
|
+
elif system() == "Windows":
|
|
52
|
+
raise NotImplementedError("SSH debug for Windows is not implemented yet.")
|
|
53
|
+
else:
|
|
54
|
+
raise NotImplementedError(f"Platform {system()} is not supported.")
|
|
44
55
|
|
|
45
56
|
def get_app():
|
|
46
57
|
nw_apps = typer.Typer(help="🔐 [n] Network subcommands", no_args_is_help=True)
|
|
@@ -56,4 +67,6 @@ def get_app():
|
|
|
56
67
|
nw_apps.command(name="a", help="Add SSH identity (private key) to this machine", hidden=True)(add_ssh_identity)
|
|
57
68
|
nw_apps.command(name="show-address", help="[A] Show this computer addresses on network")(show_address)
|
|
58
69
|
nw_apps.command(name="a", help="Show this computer addresses on network", hidden=True)(show_address)
|
|
70
|
+
nw_apps.command(name="debug-ssh", help="🐛 [d] Debug SSH connection")(debug_ssh)
|
|
71
|
+
nw_apps.command(name="d", help="Debug SSH connection", hidden=True)(debug_ssh)
|
|
59
72
|
return nw_apps
|
|
@@ -5,25 +5,13 @@ from machineconfig.utils.source_of_truth import LIBRARY_ROOT
|
|
|
5
5
|
from machineconfig.utils.path_extended import PathExtended
|
|
6
6
|
from rich.console import Console
|
|
7
7
|
from rich.panel import Panel
|
|
8
|
-
from rich import box
|
|
8
|
+
from rich import box
|
|
9
9
|
from typing import Optional
|
|
10
10
|
import typer
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
console = Console()
|
|
14
14
|
|
|
15
|
-
"""
|
|
16
|
-
if (!$pubkey_string) {
|
|
17
|
-
$pubkey_url = 'https://github.com/thisismygitrepo.keys' # (CHANGE APPROPRIATELY)
|
|
18
|
-
$pubkey_string = (Invoke-WebRequest $pubkey_url).Content
|
|
19
|
-
} else {
|
|
20
|
-
Write-Output "pubkey_string is already defined."
|
|
21
|
-
}
|
|
22
|
-
echo $null >> $HOME/.ssh/authorized_keys # powershell way of touching a file if it doesn't exist
|
|
23
|
-
echo $pubkey_string >> $HOME/.ssh/authorized_keys
|
|
24
|
-
echo $pubkey_string > $HOME/.ssh/pubkey.pub
|
|
25
|
-
"""
|
|
26
|
-
|
|
27
15
|
|
|
28
16
|
def get_add_ssh_key_script(path_to_key: PathExtended):
|
|
29
17
|
console.print(Panel("🔑 SSH KEY CONFIGURATION", title="[bold blue]SSH Setup[/bold blue]"))
|
|
@@ -0,0 +1,299 @@
|
|
|
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_linux() -> dict[str, dict[str, str | bool]]:
|
|
15
|
+
"""
|
|
16
|
+
Comprehensive SSH debugging function that checks for common pitfalls on Linux systems.
|
|
17
|
+
|
|
18
|
+
Returns a dictionary with diagnostic results for each check performed.
|
|
19
|
+
"""
|
|
20
|
+
if system() != "Linux":
|
|
21
|
+
console.print(Panel("❌ This function is only supported on Linux systems", title="[bold red]Error[/bold red]", border_style="red"))
|
|
22
|
+
raise NotImplementedError("ssh_debug_linux is only supported on Linux")
|
|
23
|
+
|
|
24
|
+
console.print(Panel("🔍 SSH DEBUG - COMPREHENSIVE DIAGNOSTICS", 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 -p ~/.ssh && chmod 700 ~/.ssh"}
|
|
36
|
+
issues_found.append("SSH directory missing")
|
|
37
|
+
console.print(Panel("❌ ~/.ssh directory does not exist\n💡 Run: mkdir -p ~/.ssh && chmod 700 ~/.ssh", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
38
|
+
else:
|
|
39
|
+
ssh_dir_stat = os.stat(ssh_dir)
|
|
40
|
+
ssh_dir_perms = oct(ssh_dir_stat.st_mode)[-3:]
|
|
41
|
+
if ssh_dir_perms != "700":
|
|
42
|
+
results["ssh_directory"] = {"status": "warning", "message": f"~/.ssh has incorrect permissions: {ssh_dir_perms} (should be 700)", "action": "Fix with: chmod 700 ~/.ssh"}
|
|
43
|
+
issues_found.append(f"SSH directory permissions incorrect: {ssh_dir_perms}")
|
|
44
|
+
console.print(Panel(f"⚠️ ~/.ssh permissions: {ssh_dir_perms} (should be 700)\n💡 Fix: chmod 700 ~/.ssh", title="[bold yellow]Permission Issue[/bold yellow]", border_style="yellow"))
|
|
45
|
+
else:
|
|
46
|
+
results["ssh_directory"] = {"status": "ok", "message": "~/.ssh directory permissions correct (700)", "action": ""}
|
|
47
|
+
console.print(Panel("✅ ~/.ssh directory permissions correct (700)", title="[bold green]OK[/bold green]", border_style="green"))
|
|
48
|
+
|
|
49
|
+
if not authorized_keys.exists():
|
|
50
|
+
results["authorized_keys"] = {"status": "warning", "message": "authorized_keys file does not exist", "action": "Create authorized_keys file and add public keys"}
|
|
51
|
+
issues_found.append("authorized_keys missing")
|
|
52
|
+
console.print(Panel("⚠️ authorized_keys file does not exist\n💡 Add your public key to ~/.ssh/authorized_keys", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
53
|
+
else:
|
|
54
|
+
ak_stat = os.stat(authorized_keys)
|
|
55
|
+
ak_perms = oct(ak_stat.st_mode)[-3:]
|
|
56
|
+
if ak_perms not in ["600", "644"]:
|
|
57
|
+
results["authorized_keys"] = {"status": "warning", "message": f"authorized_keys has incorrect permissions: {ak_perms} (should be 600 or 644)", "action": "Fix with: chmod 644 ~/.ssh/authorized_keys"}
|
|
58
|
+
issues_found.append(f"authorized_keys permissions incorrect: {ak_perms}")
|
|
59
|
+
console.print(Panel(f"⚠️ authorized_keys permissions: {ak_perms} (should be 600 or 644)\n💡 Fix: chmod 644 ~/.ssh/authorized_keys", title="[bold yellow]Permission Issue[/bold yellow]", border_style="yellow"))
|
|
60
|
+
else:
|
|
61
|
+
key_count = len([line for line in authorized_keys.read_text(encoding="utf-8").split("\n") if line.strip()])
|
|
62
|
+
results["authorized_keys"] = {"status": "ok", "message": f"authorized_keys permissions correct ({ak_perms}), contains {key_count} key(s)", "action": ""}
|
|
63
|
+
console.print(Panel(f"✅ authorized_keys permissions correct ({ak_perms})\n🔑 Contains {key_count} authorized key(s)", title="[bold green]OK[/bold green]", border_style="green"))
|
|
64
|
+
|
|
65
|
+
console.print(Panel("🔧 Checking SSH service status...", title="[bold blue]Service Status[/bold blue]", border_style="blue"))
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
ssh_service_check = subprocess.run(["systemctl", "is-active", "ssh"], capture_output=True, text=True, check=False)
|
|
69
|
+
sshd_service_check = subprocess.run(["systemctl", "is-active", "sshd"], capture_output=True, text=True, check=False)
|
|
70
|
+
|
|
71
|
+
ssh_active = ssh_service_check.returncode == 0
|
|
72
|
+
sshd_active = sshd_service_check.returncode == 0
|
|
73
|
+
|
|
74
|
+
if not ssh_active and not sshd_active:
|
|
75
|
+
results["ssh_service"] = {"status": "error", "message": "SSH service is not running (checked both 'ssh' and 'sshd')", "action": "Start with: sudo systemctl start ssh (or sshd)"}
|
|
76
|
+
issues_found.append("SSH service not running")
|
|
77
|
+
console.print(Panel("❌ SSH service is not running\n💡 Start: sudo systemctl start ssh (or sshd)\n💡 Enable on boot: sudo systemctl enable ssh", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
78
|
+
elif ssh_active or sshd_active:
|
|
79
|
+
service_name = "ssh" if ssh_active else "sshd"
|
|
80
|
+
results["ssh_service"] = {"status": "ok", "message": f"SSH service is running ({service_name})", "action": ""}
|
|
81
|
+
console.print(Panel(f"✅ SSH service is running ({service_name})", title="[bold green]OK[/bold green]", border_style="green"))
|
|
82
|
+
except FileNotFoundError:
|
|
83
|
+
results["ssh_service"] = {"status": "warning", "message": "systemctl not found, cannot check service status", "action": "Check SSH service manually"}
|
|
84
|
+
console.print(Panel("⚠️ systemctl not found\n💡 Check SSH service status manually", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
85
|
+
|
|
86
|
+
console.print(Panel("🔌 Checking SSH port and listening status...", title="[bold blue]Network Status[/bold blue]", border_style="blue"))
|
|
87
|
+
|
|
88
|
+
sshd_config_paths = [PathExtended("/etc/ssh/sshd_config"), PathExtended("/etc/sshd_config")]
|
|
89
|
+
sshd_config = None
|
|
90
|
+
for config_path in sshd_config_paths:
|
|
91
|
+
if config_path.exists():
|
|
92
|
+
sshd_config = config_path
|
|
93
|
+
break
|
|
94
|
+
|
|
95
|
+
if sshd_config:
|
|
96
|
+
config_text = sshd_config.read_text(encoding="utf-8")
|
|
97
|
+
port_lines = [line for line in config_text.split("\n") if line.strip().startswith("Port") and not line.strip().startswith("#")]
|
|
98
|
+
if port_lines:
|
|
99
|
+
ssh_port = port_lines[0].split()[1]
|
|
100
|
+
else:
|
|
101
|
+
ssh_port = "22"
|
|
102
|
+
|
|
103
|
+
results["sshd_config"] = {"status": "ok", "message": f"SSH configured to listen on port {ssh_port}", "action": ""}
|
|
104
|
+
console.print(Panel(f"✅ SSH configured to listen on port {ssh_port}", title="[bold green]Config[/bold green]", border_style="green"))
|
|
105
|
+
|
|
106
|
+
password_auth_lines = [line for line in config_text.split("\n") if "PasswordAuthentication" in line and not line.strip().startswith("#")]
|
|
107
|
+
if password_auth_lines:
|
|
108
|
+
password_auth_enabled = "yes" in password_auth_lines[-1].lower()
|
|
109
|
+
if not password_auth_enabled:
|
|
110
|
+
console.print(Panel("ℹ️ Password authentication is disabled\n💡 Only SSH keys will work", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
111
|
+
|
|
112
|
+
pubkey_auth_lines = [line for line in config_text.split("\n") if "PubkeyAuthentication" in line and not line.strip().startswith("#")]
|
|
113
|
+
if pubkey_auth_lines:
|
|
114
|
+
pubkey_auth_enabled = "yes" in pubkey_auth_lines[-1].lower()
|
|
115
|
+
if not pubkey_auth_enabled:
|
|
116
|
+
results["pubkey_auth"] = {"status": "error", "message": "PubkeyAuthentication is disabled in sshd_config", "action": "Enable with: PubkeyAuthentication yes in sshd_config"}
|
|
117
|
+
issues_found.append("PubkeyAuthentication disabled")
|
|
118
|
+
console.print(Panel("❌ PubkeyAuthentication is DISABLED\n💡 Edit /etc/ssh/sshd_config and set: PubkeyAuthentication yes\n💡 Then restart: sudo systemctl restart ssh", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
119
|
+
else:
|
|
120
|
+
results["pubkey_auth"] = {"status": "ok", "message": "PubkeyAuthentication is enabled", "action": ""}
|
|
121
|
+
console.print(Panel("✅ PubkeyAuthentication is enabled", title="[bold green]OK[/bold green]", border_style="green"))
|
|
122
|
+
else:
|
|
123
|
+
results["sshd_config"] = {"status": "warning", "message": "sshd_config not found", "action": "Check SSH configuration manually"}
|
|
124
|
+
ssh_port = "22"
|
|
125
|
+
console.print(Panel("⚠️ sshd_config not found\n💡 Assuming default port 22", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
listening_check = subprocess.run(["ss", "-tlnp"], capture_output=True, text=True, check=False)
|
|
129
|
+
if listening_check.returncode == 0:
|
|
130
|
+
listening_output = listening_check.stdout
|
|
131
|
+
if f":{ssh_port}" in listening_output:
|
|
132
|
+
results["ssh_listening"] = {"status": "ok", "message": f"SSH is listening on port {ssh_port}", "action": ""}
|
|
133
|
+
console.print(Panel(f"✅ SSH is listening on port {ssh_port}", title="[bold green]OK[/bold green]", border_style="green"))
|
|
134
|
+
else:
|
|
135
|
+
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"}
|
|
136
|
+
issues_found.append(f"SSH not listening on port {ssh_port}")
|
|
137
|
+
console.print(Panel(f"❌ SSH is NOT listening on port {ssh_port}\n💡 Check: sudo ss -tlnp | grep {ssh_port}\n💡 Restart: sudo systemctl restart ssh", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
138
|
+
else:
|
|
139
|
+
results["ssh_listening"] = {"status": "warning", "message": "Could not check listening status", "action": "Check manually with: ss -tlnp"}
|
|
140
|
+
console.print(Panel("⚠️ Could not check listening status\n💡 Check manually: ss -tlnp | grep ssh", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
141
|
+
except FileNotFoundError:
|
|
142
|
+
results["ssh_listening"] = {"status": "warning", "message": "ss command not found", "action": "Install net-tools or check manually"}
|
|
143
|
+
console.print(Panel("⚠️ 'ss' command not found\n💡 Try: netstat -tlnp | grep ssh", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
144
|
+
|
|
145
|
+
console.print(Panel("🧱 Checking firewall status...", title="[bold blue]Firewall[/bold blue]", border_style="blue"))
|
|
146
|
+
|
|
147
|
+
firewall_checked = False
|
|
148
|
+
|
|
149
|
+
try:
|
|
150
|
+
ufw_status = subprocess.run(["ufw", "status"], capture_output=True, text=True, check=False)
|
|
151
|
+
if ufw_status.returncode == 0:
|
|
152
|
+
firewall_checked = True
|
|
153
|
+
ufw_output = ufw_status.stdout
|
|
154
|
+
if "Status: active" in ufw_output:
|
|
155
|
+
if f"{ssh_port}/tcp" in ufw_output.lower() or f"{ssh_port}" in ufw_output.lower() or "ssh" in ufw_output.lower():
|
|
156
|
+
results["firewall_ufw"] = {"status": "ok", "message": f"UFW is active and SSH port {ssh_port} is allowed", "action": ""}
|
|
157
|
+
console.print(Panel(f"✅ UFW is active and SSH port {ssh_port} is allowed", title="[bold green]OK[/bold green]", border_style="green"))
|
|
158
|
+
else:
|
|
159
|
+
results["firewall_ufw"] = {"status": "error", "message": f"UFW is active but SSH port {ssh_port} is NOT allowed", "action": f"Allow with: sudo ufw allow {ssh_port}/tcp"}
|
|
160
|
+
issues_found.append(f"UFW blocking port {ssh_port}")
|
|
161
|
+
console.print(Panel(f"❌ UFW is active but SSH port {ssh_port} is NOT allowed\n💡 Fix: sudo ufw allow {ssh_port}/tcp", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
162
|
+
else:
|
|
163
|
+
results["firewall_ufw"] = {"status": "ok", "message": "UFW is inactive", "action": ""}
|
|
164
|
+
console.print(Panel("ℹ️ UFW is inactive (no firewall blocking)", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
165
|
+
except FileNotFoundError:
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
if not firewall_checked:
|
|
169
|
+
try:
|
|
170
|
+
firewalld_status = subprocess.run(["firewall-cmd", "--state"], capture_output=True, text=True, check=False)
|
|
171
|
+
if firewalld_status.returncode == 0 and "running" in firewalld_status.stdout.lower():
|
|
172
|
+
firewall_checked = True
|
|
173
|
+
firewalld_check = subprocess.run(["firewall-cmd", "--list-services"], capture_output=True, text=True, check=False)
|
|
174
|
+
if firewalld_check.returncode == 0:
|
|
175
|
+
if "ssh" in firewalld_check.stdout.lower():
|
|
176
|
+
results["firewall_firewalld"] = {"status": "ok", "message": "firewalld is active and SSH service is allowed", "action": ""}
|
|
177
|
+
console.print(Panel("✅ firewalld is active and SSH service is allowed", title="[bold green]OK[/bold green]", border_style="green"))
|
|
178
|
+
else:
|
|
179
|
+
results["firewall_firewalld"] = {"status": "error", "message": "firewalld is active but SSH service is NOT allowed", "action": "Allow with: sudo firewall-cmd --permanent --add-service=ssh && sudo firewall-cmd --reload"}
|
|
180
|
+
issues_found.append("firewalld blocking SSH")
|
|
181
|
+
console.print(Panel("❌ firewalld is active but SSH is NOT allowed\n💡 Fix: sudo firewall-cmd --permanent --add-service=ssh\n💡 Then: sudo firewall-cmd --reload", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
182
|
+
except FileNotFoundError:
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
if not firewall_checked:
|
|
186
|
+
try:
|
|
187
|
+
iptables_check = subprocess.run(["iptables", "-L", "-n"], capture_output=True, text=True, check=False)
|
|
188
|
+
if iptables_check.returncode == 0:
|
|
189
|
+
firewall_checked = True
|
|
190
|
+
iptables_output = iptables_check.stdout
|
|
191
|
+
if f"dpt:{ssh_port}" in iptables_output or "ACCEPT" in iptables_output.split("\n")[0]:
|
|
192
|
+
results["firewall_iptables"] = {"status": "ok", "message": f"iptables appears to allow SSH traffic on port {ssh_port}", "action": ""}
|
|
193
|
+
console.print(Panel(f"ℹ️ iptables detected - appears to allow SSH on port {ssh_port}", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
194
|
+
else:
|
|
195
|
+
results["firewall_iptables"] = {"status": "warning", "message": f"iptables may be blocking SSH traffic on port {ssh_port}", "action": "Check rules manually: sudo iptables -L -n"}
|
|
196
|
+
console.print(Panel(f"⚠️ iptables detected - may be blocking SSH\n💡 Check: sudo iptables -L -n\n💡 Allow: sudo iptables -A INPUT -p tcp --dport {ssh_port} -j ACCEPT", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
197
|
+
except FileNotFoundError:
|
|
198
|
+
pass
|
|
199
|
+
|
|
200
|
+
if not firewall_checked:
|
|
201
|
+
results["firewall"] = {"status": "ok", "message": "No firewall detected or firewall commands not available", "action": ""}
|
|
202
|
+
console.print(Panel("ℹ️ No firewall detected", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
203
|
+
|
|
204
|
+
console.print(Panel("🗂️ Checking for problematic files in /etc/...", title="[bold blue]System Files[/bold blue]", border_style="blue"))
|
|
205
|
+
|
|
206
|
+
hosts_deny = PathExtended("/etc/hosts.deny")
|
|
207
|
+
if hosts_deny.exists():
|
|
208
|
+
hosts_deny_content = hosts_deny.read_text(encoding="utf-8")
|
|
209
|
+
if "sshd" in hosts_deny_content.lower() or "all" in hosts_deny_content.lower():
|
|
210
|
+
results["hosts_deny"] = {"status": "error", "message": "/etc/hosts.deny may be blocking SSH connections", "action": "Review /etc/hosts.deny and remove SSH blocks"}
|
|
211
|
+
issues_found.append("/etc/hosts.deny blocking SSH")
|
|
212
|
+
console.print(Panel("❌ /etc/hosts.deny may be blocking SSH\n💡 Check: cat /etc/hosts.deny\n💡 Remove any lines blocking 'sshd' or 'ALL'", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
213
|
+
else:
|
|
214
|
+
results["hosts_deny"] = {"status": "ok", "message": "/etc/hosts.deny exists but doesn't appear to block SSH", "action": ""}
|
|
215
|
+
console.print(Panel("✅ /etc/hosts.deny doesn't block SSH", title="[bold green]OK[/bold green]", border_style="green"))
|
|
216
|
+
else:
|
|
217
|
+
results["hosts_deny"] = {"status": "ok", "message": "/etc/hosts.deny does not exist", "action": ""}
|
|
218
|
+
console.print(Panel("✅ /etc/hosts.deny not present", title="[bold green]OK[/bold green]", border_style="green"))
|
|
219
|
+
|
|
220
|
+
hosts_allow = PathExtended("/etc/hosts.allow")
|
|
221
|
+
if hosts_allow.exists():
|
|
222
|
+
results["hosts_allow"] = {"status": "ok", "message": "/etc/hosts.allow exists (check if needed)", "action": ""}
|
|
223
|
+
console.print(Panel("ℹ️ /etc/hosts.allow exists\n💡 Ensure it allows SSH if using TCP wrappers", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
224
|
+
|
|
225
|
+
console.print(Panel("👤 Checking home directory permissions...", title="[bold blue]User Permissions[/bold blue]", border_style="blue"))
|
|
226
|
+
|
|
227
|
+
home_dir = PathExtended.home()
|
|
228
|
+
home_stat = os.stat(home_dir)
|
|
229
|
+
home_perms = oct(home_stat.st_mode)[-3:]
|
|
230
|
+
|
|
231
|
+
if home_perms[2] in ["7", "6"]:
|
|
232
|
+
results["home_directory"] = {"status": "error", "message": f"Home directory has world-writable permissions: {home_perms} (SSH may refuse to work)", "action": f"Fix with: chmod 755 {home_dir}"}
|
|
233
|
+
issues_found.append(f"Home directory world-writable: {home_perms}")
|
|
234
|
+
console.print(Panel(f"❌ Home directory is world-writable ({home_perms})\n💡 SSH may refuse connections for security\n💡 Fix: chmod 755 {home_dir}", title="[bold red]Critical Issue[/bold red]", border_style="red"))
|
|
235
|
+
else:
|
|
236
|
+
results["home_directory"] = {"status": "ok", "message": f"Home directory permissions OK: {home_perms}", "action": ""}
|
|
237
|
+
console.print(Panel(f"✅ Home directory permissions OK: {home_perms}", title="[bold green]OK[/bold green]", border_style="green"))
|
|
238
|
+
|
|
239
|
+
console.print(Panel("🔍 Checking SELinux status...", title="[bold blue]SELinux[/bold blue]", border_style="blue"))
|
|
240
|
+
|
|
241
|
+
try:
|
|
242
|
+
selinux_check = subprocess.run(["getenforce"], capture_output=True, text=True, check=False)
|
|
243
|
+
if selinux_check.returncode == 0:
|
|
244
|
+
selinux_status = selinux_check.stdout.strip()
|
|
245
|
+
if selinux_status == "Enforcing":
|
|
246
|
+
restorecon_check = subprocess.run(["restorecon", "-Rv", str(ssh_dir)], capture_output=True, text=True, check=False)
|
|
247
|
+
if restorecon_check.returncode == 0:
|
|
248
|
+
results["selinux"] = {"status": "ok", "message": f"SELinux is {selinux_status}, SSH contexts restored", "action": ""}
|
|
249
|
+
console.print(Panel(f"✅ SELinux is {selinux_status}\n✅ SSH contexts restored", title="[bold green]OK[/bold green]", border_style="green"))
|
|
250
|
+
else:
|
|
251
|
+
results["selinux"] = {"status": "warning", "message": f"SELinux is {selinux_status}, may need context restoration", "action": f"Run: sudo restorecon -Rv {ssh_dir}"}
|
|
252
|
+
console.print(Panel(f"⚠️ SELinux is {selinux_status}\n💡 Fix contexts: sudo restorecon -Rv {ssh_dir}", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
253
|
+
else:
|
|
254
|
+
results["selinux"] = {"status": "ok", "message": f"SELinux is {selinux_status}", "action": ""}
|
|
255
|
+
console.print(Panel(f"ℹ️ SELinux is {selinux_status}", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
256
|
+
except FileNotFoundError:
|
|
257
|
+
results["selinux"] = {"status": "ok", "message": "SELinux not installed", "action": ""}
|
|
258
|
+
console.print(Panel("ℹ️ SELinux not installed", title="[bold blue]Info[/bold blue]", border_style="blue"))
|
|
259
|
+
|
|
260
|
+
console.print(Panel("📋 Checking SSH logs for errors...", title="[bold blue]Logs[/bold blue]", border_style="blue"))
|
|
261
|
+
|
|
262
|
+
log_files = [PathExtended("/var/log/auth.log"), PathExtended("/var/log/secure")]
|
|
263
|
+
log_found = False
|
|
264
|
+
for log_file in log_files:
|
|
265
|
+
if log_file.exists():
|
|
266
|
+
log_found = True
|
|
267
|
+
try:
|
|
268
|
+
tail_check = subprocess.run(["tail", "-n", "50", str(log_file)], capture_output=True, text=True, check=False)
|
|
269
|
+
if tail_check.returncode == 0:
|
|
270
|
+
log_content = tail_check.stdout
|
|
271
|
+
error_keywords = ["error", "failed", "refused", "denied", "invalid"]
|
|
272
|
+
ssh_errors = [line for line in log_content.split("\n") if any(keyword in line.lower() for keyword in error_keywords) and "ssh" in line.lower()]
|
|
273
|
+
if ssh_errors:
|
|
274
|
+
results["ssh_logs"] = {"status": "warning", "message": f"Found {len(ssh_errors)} potential SSH errors in {log_file}", "action": f"Review: sudo tail -f {log_file}"}
|
|
275
|
+
console.print(Panel(f"⚠️ Found {len(ssh_errors)} potential SSH errors in {log_file}\n💡 Review: sudo tail -f {log_file}\n\nRecent errors:\n" + "\n".join(ssh_errors[-3:]), title="[bold yellow]Log Errors[/bold yellow]", border_style="yellow"))
|
|
276
|
+
else:
|
|
277
|
+
results["ssh_logs"] = {"status": "ok", "message": f"No recent SSH errors in {log_file}", "action": ""}
|
|
278
|
+
console.print(Panel(f"✅ No recent SSH errors in {log_file}", title="[bold green]OK[/bold green]", border_style="green"))
|
|
279
|
+
except Exception:
|
|
280
|
+
results["ssh_logs"] = {"status": "warning", "message": f"Could not read {log_file}", "action": f"Check manually: sudo tail {log_file}"}
|
|
281
|
+
console.print(Panel(f"⚠️ Could not read {log_file}\n💡 Check: sudo tail {log_file}", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
282
|
+
break
|
|
283
|
+
|
|
284
|
+
if not log_found:
|
|
285
|
+
results["ssh_logs"] = {"status": "warning", "message": "SSH log files not found", "action": "Check journalctl: sudo journalctl -u ssh"}
|
|
286
|
+
console.print(Panel("⚠️ SSH log files not found\n💡 Check: sudo journalctl -u ssh -n 50", title="[bold yellow]Warning[/bold yellow]", border_style="yellow"))
|
|
287
|
+
|
|
288
|
+
console.print(Panel("📊 DIAGNOSTIC SUMMARY", box=box.DOUBLE_EDGE, title_align="left"))
|
|
289
|
+
|
|
290
|
+
if issues_found:
|
|
291
|
+
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"))
|
|
292
|
+
else:
|
|
293
|
+
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", title="[bold green]All Checks Passed[/bold green]", border_style="green"))
|
|
294
|
+
|
|
295
|
+
return results
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
if __name__ == "__main__":
|
|
299
|
+
ssh_debug_linux()
|
|
@@ -177,13 +177,11 @@ machineconfig/scripts/python/devops_helpers/__init__.py,sha256=47DEQpj8HBSa-_TIm
|
|
|
177
177
|
machineconfig/scripts/python/devops_helpers/cli_config.py,sha256=wnQyhN-LbuIpVKvZhOxv8_UR7cwFTlKpZMqL3Ydi3Zo,5332
|
|
178
178
|
machineconfig/scripts/python/devops_helpers/cli_config_dotfile.py,sha256=rjTys4FNf9_feP9flWM7Zvq17dxWmetSiGaHPxp25nk,2737
|
|
179
179
|
machineconfig/scripts/python/devops_helpers/cli_data.py,sha256=kvJ7g2CccjjXIhCwdu_Vlif8JHC0qUoLjuGcTSqT-IU,514
|
|
180
|
-
machineconfig/scripts/python/devops_helpers/cli_nw.py,sha256=
|
|
180
|
+
machineconfig/scripts/python/devops_helpers/cli_nw.py,sha256=3KyzyoEyiLFrKxB5abkUq8UI3PoHWcI9PyczHf0YcSY,4023
|
|
181
181
|
machineconfig/scripts/python/devops_helpers/cli_repos.py,sha256=HJH5ZBob_Uzhc3fDgG9riOeW6YEJt88xTjQYcEUPmUY,12015
|
|
182
182
|
machineconfig/scripts/python/devops_helpers/cli_self.py,sha256=9ie3qtEKcUSDwi7rkwBbWCXZoYsk6wpYXEVIC4wlBIg,4531
|
|
183
183
|
machineconfig/scripts/python/devops_helpers/cli_share_server.py,sha256=285OzxttCx7YsrpOkaapMKP1eVGHmG5TkkaSQnY7i3c,3976
|
|
184
184
|
machineconfig/scripts/python/devops_helpers/cli_terminal.py,sha256=k_PzXaiGyE0vXr0Ii1XcJz2A7UvyPJrR31TRWt4RKRI,6019
|
|
185
|
-
machineconfig/scripts/python/devops_helpers/devops_add_identity.py,sha256=wvjNgqsLmqD2SxbNCW_usqfp0LI-TDvcJJKGOWt2oFw,3775
|
|
186
|
-
machineconfig/scripts/python/devops_helpers/devops_add_ssh_key.py,sha256=4Vn93ecTy62rIc8uLM90YsR3l0-0AiiqumMlI9Axk9A,9296
|
|
187
185
|
machineconfig/scripts/python/devops_helpers/devops_backup_retrieve.py,sha256=nK47Rc7gQuDCnkk6_sW1y82gBnDJ9TdHU8XwMPFBK9c,5591
|
|
188
186
|
machineconfig/scripts/python/devops_helpers/devops_status.py,sha256=PJVPhfhXq8der6Xd-_fjZfnizfM-RGfJApkRGhGBmNo,20525
|
|
189
187
|
machineconfig/scripts/python/devops_helpers/devops_update_repos.py,sha256=qYS3vT-VECxXI4MXgmRMHAqbVX19aj0U_zobhyM_nGI,10130
|
|
@@ -227,6 +225,7 @@ machineconfig/scripts/python/helpers_repos/secure_repo.py,sha256=g0o3SHBwicro1K5
|
|
|
227
225
|
machineconfig/scripts/python/nw/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
228
226
|
machineconfig/scripts/python/nw/add_ssh_key.py,sha256=dYOK9vCB6I9YSeCLO7Hid1IaFjiEs9n_gugDSddtGU8,9298
|
|
229
227
|
machineconfig/scripts/python/nw/devops_add_identity.py,sha256=aPjcHbTLhxYwWYcandyAHdwuO15ZBu3fB82u6bI0tMQ,3773
|
|
228
|
+
machineconfig/scripts/python/nw/devops_add_ssh_key.py,sha256=EyLs2kc1A0Z-JncjDSleiBokgBzEaxlS-C024K4WuZQ,8847
|
|
230
229
|
machineconfig/scripts/python/nw/mount_drive,sha256=zemKofv7hOmRN_V3qK0q580GkfWw3VdikyVVQyiu8j8,3514
|
|
231
230
|
machineconfig/scripts/python/nw/mount_nfs,sha256=DdJqswbKLu8zqlVR3X6Js30D4myJFPVzHHNkWTJqDUQ,1855
|
|
232
231
|
machineconfig/scripts/python/nw/mount_nfs.py,sha256=lOMDY4RS7tx8gsCazVR5tNNwFbaRyO2PJlnwBCDQgCM,3573
|
|
@@ -235,6 +234,7 @@ machineconfig/scripts/python/nw/mount_nw_drive.py,sha256=iru6AtnTyvyuk6WxlK5R4lD
|
|
|
235
234
|
machineconfig/scripts/python/nw/mount_smb,sha256=7UN5EP1kuxYL_-CnyaH4f9Wuu2CgALDZpJ0mPcdvCiY,94
|
|
236
235
|
machineconfig/scripts/python/nw/mount_ssh.py,sha256=qt0P4T4pheszexBxaDeLVrGdLIVRoOc-UdfYv5r0OLY,2587
|
|
237
236
|
machineconfig/scripts/python/nw/onetimeshare.py,sha256=xRd8by6qUm-od2Umty2MYsXyJwzXw-CBTd7VellNaKY,2498
|
|
237
|
+
machineconfig/scripts/python/nw/ssh_debug_linux.py,sha256=LAKWq8rMWauvVk4_ap38SjZCIqPFaREjheJ84424Ss0,23012
|
|
238
238
|
machineconfig/scripts/python/nw/wifi_conn.py,sha256=4GdLhgma9GRmZ6OFg3oxOX-qY3sr45njPckozlpM_A0,15566
|
|
239
239
|
machineconfig/scripts/python/nw/wsl_windows_transfer.py,sha256=1ab9l-8MtAxofW5nGH9G2-BjlszaiLETu6WBECcNNhA,3546
|
|
240
240
|
machineconfig/scripts/python/repos_helpers/action.py,sha256=t6x9K43Uy7r5aRpdODfsN-5UoMrYXEG2cVw-Y8l9prw,14847
|
|
@@ -420,8 +420,8 @@ machineconfig/utils/schemas/installer/installer_types.py,sha256=QClRY61QaduBPJoS
|
|
|
420
420
|
machineconfig/utils/schemas/layouts/layout_types.py,sha256=TcqlZdGVoH8htG5fHn1KWXhRdPueAcoyApppZsPAPto,2020
|
|
421
421
|
machineconfig/utils/schemas/repos/repos_types.py,sha256=ECVr-3IVIo8yjmYmVXX2mnDDN1SLSwvQIhx4KDDQHBQ,405
|
|
422
422
|
machineconfig/utils/ssh_utils/utils.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
423
|
-
machineconfig-5.
|
|
424
|
-
machineconfig-5.
|
|
425
|
-
machineconfig-5.
|
|
426
|
-
machineconfig-5.
|
|
427
|
-
machineconfig-5.
|
|
423
|
+
machineconfig-5.81.dist-info/METADATA,sha256=6QMAVt6LlV-kLzc9UcRMh75QCdIk0DZbIPrYMYYMS20,3013
|
|
424
|
+
machineconfig-5.81.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
425
|
+
machineconfig-5.81.dist-info/entry_points.txt,sha256=M0jwN_brZdXWhmNVeXLvdKxfkv8WhhXFZYcuKBA9qnk,418
|
|
426
|
+
machineconfig-5.81.dist-info/top_level.txt,sha256=porRtB8qms8fOIUJgK-tO83_FeH6Bpe12oUVC670teA,14
|
|
427
|
+
machineconfig-5.81.dist-info/RECORD,,
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
"""ID"""
|
|
2
|
-
|
|
3
|
-
# from platform import system
|
|
4
|
-
from machineconfig.utils.path_extended import PathExtended
|
|
5
|
-
from machineconfig.utils.options import choose_from_options
|
|
6
|
-
from rich.panel import Panel
|
|
7
|
-
from rich.text import Text
|
|
8
|
-
|
|
9
|
-
BOX_WIDTH = 150 # width for box drawing
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def main() -> None:
|
|
13
|
-
title = "🔑 SSH IDENTITY MANAGEMENT"
|
|
14
|
-
print(Panel(Text(title, justify="center"), expand=False))
|
|
15
|
-
|
|
16
|
-
print(Panel("🔍 Searching for existing SSH keys...", expand=False))
|
|
17
|
-
|
|
18
|
-
private_keys = [x.with_name(x.stem) for x in PathExtended.home().joinpath(".ssh").search("*.pub")]
|
|
19
|
-
private_keys = [x for x in private_keys if x.exists()]
|
|
20
|
-
if private_keys:
|
|
21
|
-
print(Panel(f"✅ Found {len(private_keys)} SSH private key(s)", expand=False))
|
|
22
|
-
else:
|
|
23
|
-
print(Panel("⚠️ No SSH private keys found", expand=False))
|
|
24
|
-
|
|
25
|
-
choice = choose_from_options(msg="Path to private key to be used when ssh'ing: ", options=[str(x) for x in private_keys] + ["I have the path to the key file", "I want to paste the key itself"], multi=False)
|
|
26
|
-
|
|
27
|
-
if choice == "I have the path to the key file":
|
|
28
|
-
print(Panel("📄 Please enter the path to your private key file", expand=False))
|
|
29
|
-
path_to_key = PathExtended(input("📋 Input path here: ")).expanduser().absolute()
|
|
30
|
-
print(Panel(f"📂 Using key from custom path: {path_to_key}", expand=False))
|
|
31
|
-
|
|
32
|
-
elif choice == "I want to paste the key itself":
|
|
33
|
-
print(Panel("📋 Please provide a filename and paste the private key content", expand=False))
|
|
34
|
-
key_filename = input("📝 File name (default: my_pasted_key): ") or "my_pasted_key"
|
|
35
|
-
path_to_key = PathExtended.home().joinpath(f".ssh/{key_filename}")
|
|
36
|
-
path_to_key.parent.mkdir(parents=True, exist_ok=True)
|
|
37
|
-
path_to_key.write_text(input("🔑 Paste the private key here: "), encoding="utf-8")
|
|
38
|
-
print(Panel(f"💾 Key saved to: {path_to_key}", expand=False))
|
|
39
|
-
|
|
40
|
-
else:
|
|
41
|
-
path_to_key = PathExtended(choice)
|
|
42
|
-
print(Panel(f"🔑 Using selected key: {path_to_key.name}", expand=False))
|
|
43
|
-
|
|
44
|
-
txt = f"IdentityFile {path_to_key.collapseuser().as_posix()}" # adds this id for all connections, no host specified.
|
|
45
|
-
config_path = PathExtended.home().joinpath(".ssh/config")
|
|
46
|
-
|
|
47
|
-
print(Panel("📝 Updating SSH configuration...", expand=False))
|
|
48
|
-
|
|
49
|
-
# Inline the previous modify_text behavior (now deprecated):
|
|
50
|
-
# - If file doesn't exist, seed content with txt_search
|
|
51
|
-
# - Otherwise, replace a matching line or append if not found
|
|
52
|
-
if config_path.exists():
|
|
53
|
-
current = config_path.read_text(encoding="utf-8")
|
|
54
|
-
print(Panel("✏️ Updated existing SSH config file", expand=False))
|
|
55
|
-
else:
|
|
56
|
-
current = txt
|
|
57
|
-
print(Panel("📄 Created new SSH config file", expand=False))
|
|
58
|
-
lines = current.split("\n")
|
|
59
|
-
found = False
|
|
60
|
-
for i, line in enumerate(lines):
|
|
61
|
-
if txt in line:
|
|
62
|
-
lines[i] = txt
|
|
63
|
-
found = True
|
|
64
|
-
if not found:
|
|
65
|
-
lines.insert(0, txt)
|
|
66
|
-
new_content = "\n".join(lines)
|
|
67
|
-
config_path.write_text(new_content, encoding="utf-8")
|
|
68
|
-
|
|
69
|
-
panel_complete = Panel(Text("✅ SSH IDENTITY CONFIGURATION COMPLETE\nIdentity added to SSH config file\nConsider reloading the SSH config to apply changes", justify="center"), expand=False, border_style="green")
|
|
70
|
-
program = f"echo '{panel_complete}'"
|
|
71
|
-
|
|
72
|
-
success_message = f"🎉 CONFIGURATION SUCCESSFUL\nIdentity added: {path_to_key.name}\nConfig file: {config_path}"
|
|
73
|
-
print(Panel(Text(success_message, justify="center"), expand=False, border_style="green"))
|
|
74
|
-
|
|
75
|
-
import subprocess
|
|
76
|
-
|
|
77
|
-
# run program
|
|
78
|
-
subprocess.run(program, shell=True, check=True, text=True)
|
|
79
|
-
print(Panel("🔐 Identity added to SSH agent", expand=False, border_style="green"))
|
|
80
|
-
return None
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if __name__ == "__main__":
|
|
84
|
-
pass
|
|
File without changes
|
|
File without changes
|
|
File without changes
|