Compare commits

..
5 Commits
15 changed files with 1058 additions and 111 deletions

No files matched your search

+4 -3
View File
@@ -3,7 +3,7 @@
</p> </p>
# Connpy (v6.3.0) # Connpy (v6.4.0b1)
[![](https://img.shields.io/pypi/v/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/v/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/)
[![](https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/)
[![](https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&cacheSeconds=86400)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&cacheSeconds=86400)](https://pypi.org/pypi/connpy/)
@@ -13,7 +13,7 @@
[![](https://img.shields.io/badge/MCP-compatible-orange?style=flat-square)](https://modelcontextprotocol.io) [![](https://img.shields.io/badge/MCP-compatible-orange?style=flat-square)](https://modelcontextprotocol.io)
[![](https://img.shields.io/pypi/l/connpy.svg?style=flat-square)](https://github.com/fluzzi/connpy/blob/main/LICENSE) [![](https://img.shields.io/pypi/l/connpy.svg?style=flat-square)](https://github.com/fluzzi/connpy/blob/main/LICENSE)
**Connpy** is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for **SSH, SFTP, Telnet, kubectl, Docker pods, and AWS SSM**. **Connpy** is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for **SSH, SFTP, Mosh, Telnet, kubectl, Docker pods, and AWS SSM**.
The v6 release introduces a comprehensive **AI Copilot** and **AI Playbook Engine**, transforming your terminal into an interactive network assistant that understands your device outputs, configures parameters safely, and runs simulations. The v6 release introduces a comprehensive **AI Copilot** and **AI Playbook Engine**, transforming your terminal into an interactive network assistant that understands your device outputs, configures parameters safely, and runs simulations.
@@ -134,9 +134,10 @@ tags: { "os": "cisco_ios", "prompt": ".*#", "screen_length_command": "terminal l
## 4. 🔌 Protocols & Connection Features ## 4. 🔌 Protocols & Connection Features
### 4a. SSH / SFTP / Telnet / kubectl / Docker / AWS SSM ### 4a. SSH / SFTP / Mosh / Telnet / kubectl / Docker / AWS SSM
Connect to various architectures using native protocols: Connect to various architectures using native protocols:
* **SSH / Telnet**: Standard CLI protocols. * **SSH / Telnet**: Standard CLI protocols.
* **Mosh**: Mobile Shell with roaming and local echo support.
* **SFTP**: Transfer files securely (`conn --sftp node`). * **SFTP**: Transfer files securely (`conn --sftp node`).
* **Docker**: Connect directly to local container names (host set to container name/ID). * **Docker**: Connect directly to local container names (host set to container name/ID).
* **Kubernetes (kubectl)**: Connect to pods (namespace customizable via options). * **Kubernetes (kubectl)**: Connect to pods (namespace customizable via options).
+4 -3
View File
@@ -5,7 +5,7 @@
</p> </p>
# Connpy (v6.3.0) # Connpy (v6.4.0b1)
[![](https://img.shields.io/pypi/v/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/v/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/)
[![](https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square)](https://pypi.org/pypi/connpy/)
[![](https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&cacheSeconds=86400)](https://pypi.org/pypi/connpy/) [![](https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&cacheSeconds=86400)](https://pypi.org/pypi/connpy/)
@@ -15,7 +15,7 @@
[![](https://img.shields.io/badge/MCP-compatible-orange?style=flat-square)](https://modelcontextprotocol.io) [![](https://img.shields.io/badge/MCP-compatible-orange?style=flat-square)](https://modelcontextprotocol.io)
[![](https://img.shields.io/pypi/l/connpy.svg?style=flat-square)](https://github.com/fluzzi/connpy/blob/main/LICENSE) [![](https://img.shields.io/pypi/l/connpy.svg?style=flat-square)](https://github.com/fluzzi/connpy/blob/main/LICENSE)
**Connpy** is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for **SSH, SFTP, Telnet, kubectl, Docker pods, and AWS SSM**. **Connpy** is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for **SSH, SFTP, Mosh, Telnet, kubectl, Docker pods, and AWS SSM**.
The v6 release introduces a comprehensive **AI Copilot** and **AI Playbook Engine**, transforming your terminal into an interactive network assistant that understands your device outputs, configures parameters safely, and runs simulations. The v6 release introduces a comprehensive **AI Copilot** and **AI Playbook Engine**, transforming your terminal into an interactive network assistant that understands your device outputs, configures parameters safely, and runs simulations.
@@ -136,9 +136,10 @@ tags: { "os": "cisco_ios", "prompt": ".*#", "screen_length_command": "terminal l
## 4. 🔌 Protocols & Connection Features ## 4. 🔌 Protocols & Connection Features
### 4a. SSH / SFTP / Telnet / kubectl / Docker / AWS SSM ### 4a. SSH / SFTP / Mosh / Telnet / kubectl / Docker / AWS SSM
Connect to various architectures using native protocols: Connect to various architectures using native protocols:
* **SSH / Telnet**: Standard CLI protocols. * **SSH / Telnet**: Standard CLI protocols.
* **Mosh**: Mobile Shell with roaming and local echo support.
* **SFTP**: Transfer files securely (`conn --sftp node`). * **SFTP**: Transfer files securely (`conn --sftp node`).
* **Docker**: Connect directly to local container names (host set to container name/ID). * **Docker**: Connect directly to local container names (host set to container name/ID).
* **Kubernetes (kubectl)**: Connect to pods (namespace customizable via options). * **Kubernetes (kubectl)**: Connect to pods (namespace customizable via options).
+1 -1
View File
@@ -1 +1 @@
__version__ = "6.3.0" __version__ = "6.4.0b1"
+4
View File
@@ -29,6 +29,7 @@ Here are some important instructions and tips for configuring your new node:
2. **Available Protocols and Apps**: 2. **Available Protocols and Apps**:
- ssh - ssh
- mosh (requires remote mosh-server and UDP ports 60000-61000 open; --sftp uses SSH TCP)
- telnet - telnet
- kubectl (`kubectl exec`) - kubectl (`kubectl exec`)
- docker (`docker exec`) - docker (`docker exec`)
@@ -59,6 +60,9 @@ Here are some important instructions and tips for configuring your new node:
- `profile`: AWS Profile used for `aws ssm start-session`. - `profile`: AWS Profile used for `aws ssm start-session`.
- `ssh_options`: Additional SSH options injected when an SSM node is used as a jumphost (e.g., `-i ~/.ssh/key.pem`). - `ssh_options`: Additional SSH options injected when an SSM node is used as a jumphost (e.g., `-i ~/.ssh/key.pem`).
- `nc_command`: Replaces the default `nc` command used when bridging connections through Docker or Kubernetes (e.g., `ip netns exec global-vrf nc`). - `nc_command`: Replaces the default `nc` command used when bridging connections through Docker or Kubernetes (e.g., `ip netns exec global-vrf nc`).
- `mosh_udp_port`: Server-side UDP port or range (`PORT` or `PORT1:PORT2`) passed as `-p` to `mosh`.
- `mosh_server`: Path to the `mosh-server` binary on the remote host (`--server`).
- `mosh_ssh_options`: Additional SSH options injected into `mosh --ssh="ssh ..."` and reused when connecting via `--sftp` or running batch commands (`run`/`test`).
""" """
if type == "bashcompletion": if type == "bashcompletion":
return ''' return '''
+4 -4
View File
@@ -17,14 +17,14 @@ class Validators:
_raise_val_err("Profile {} don't exist".format(current)) _raise_val_err("Profile {} don't exist".format(current))
return True return True
def profile_protocol_validation(self, answers, current, regex = "(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)"): def profile_protocol_validation(self, answers, current, regex = "(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)"):
if not re.match(regex, current): if not re.match(regex, current):
_raise_val_err("Pick between ssh, telnet, kubectl, docker, ssm or leave empty") _raise_val_err("Pick between ssh, mosh, telnet, kubectl, docker, ssm or leave empty")
return True return True
def protocol_validation(self, answers, current, regex = "(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)"): def protocol_validation(self, answers, current, regex = "(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)"):
if not re.match(regex, current): if not re.match(regex, current):
_raise_val_err("Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile") _raise_val_err("Pick between ssh, mosh, telnet, kubectl, docker, ssm, leave empty or @profile")
if current.startswith("@"): if current.startswith("@"):
if current[1:] not in self.app.profiles: if current[1:] not in self.app.profiles:
_raise_val_err("Profile {} don't exist".format(current)) _raise_val_err("Profile {} don't exist".format(current))
+231 -39
View File
@@ -83,7 +83,7 @@ class node:
- port (str): Port to connect to node, default 22 for ssh and 23 - port (str): Port to connect to node, default 22 for ssh and 23
for telnet. for telnet.
- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh. - protocol (str): Select ssh, mosh, telnet, kubectl, docker or ssm. Default is ssh.
- user (str): Username to of the node. - user (str): Username to of the node.
@@ -119,6 +119,7 @@ class node:
setattr(self,key,"ssh") setattr(self,key,"ssh")
else: else:
setattr(self,key,attr[key]) setattr(self,key,attr[key])
self._orig_protocol = self.protocol
if isinstance(password,list): if isinstance(password,list):
self.password = [] self.password = []
for i, s in enumerate(password): for i, s in enumerate(password):
@@ -195,6 +196,11 @@ class node:
jh = config.getitem(jumphost_name) jh = config.getitem(jumphost_name)
jh = self._resolve_jumphost_data(jh, config) jh = self._resolve_jumphost_data(jh, config)
if jh["protocol"] == "mosh":
raise ValueError(
f"Jumphost '{jumphost_name}' uses protocol 'mosh' which cannot be used as a jumphost."
)
passwords = [] passwords = []
inner_proxy_opt = "" inner_proxy_opt = ""
@@ -910,12 +916,14 @@ class node:
str: Output of the commands you ran on the node. str: Output of the commands you ran on the node.
''' '''
connect = self._connect(timeout = timeout, logger = logger) force_ssh = (self.protocol == "mosh")
connect = self._connect(timeout=timeout, logger=logger, force_ssh=force_ssh)
now = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S') now = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
if connect == True: if connect == True:
if logger: if logger:
port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else "" effective_protocol = "ssh" if force_ssh else self.protocol
logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}") port_str = f":{self.port}" if self.port and effective_protocol not in ["ssm", "kubectl", "docker"] else ""
logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {effective_protocol}")
if "prompt" in self.tags: if "prompt" in self.tags:
prompt = self.tags["prompt"] prompt = self.tags["prompt"]
@@ -1027,11 +1035,13 @@ class node:
''' '''
now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
connect = self._connect(timeout = timeout, logger = logger) force_ssh = (self.protocol == "mosh")
connect = self._connect(timeout=timeout, logger=logger, force_ssh=force_ssh)
if connect == True: if connect == True:
if logger: if logger:
port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else "" effective_protocol = "ssh" if force_ssh else self.protocol
logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}") port_str = f":{self.port}" if self.port and effective_protocol not in ["ssm", "kubectl", "docker"] else ""
logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {effective_protocol}")
if "prompt" in self.tags: if "prompt" in self.tags:
prompt = self.tags["prompt"] prompt = self.tags["prompt"]
@@ -1123,16 +1133,45 @@ class node:
return connect return connect
@MethodHook @MethodHook
def _generate_ssh_sftp_cmd(self): def _generate_ssh_sftp_cmd(self, force_ssh=False):
cmd = self.protocol is_from_mosh = getattr(self, "_orig_protocol", "") == "mosh"
if self.port: if is_from_mosh:
if self.protocol == "ssh": if str(self.host).startswith("-"):
cmd += " -p " + self.port raise ValueError("Host cannot start with '-'")
elif self.protocol == "sftp": if self.user and str(self.user).startswith("-"):
cmd += " -P " + self.port raise ValueError("User cannot start with '-'")
if self.options:
opts = self.options proto = "ssh" if force_ssh else self.protocol
if self.protocol == "sftp": cmd = proto
if self.port != "" and self.port is not None:
if is_from_mosh:
port_s = str(self.port).strip()
if port_s:
if not re.fullmatch(r"^\d+$", port_s) or not (1 <= int(port_s) <= 65535):
raise ValueError(f"Invalid TCP SSH port '{self.port}'")
cmd += (" -p " if proto == "ssh" else " -P ") + port_s
else:
if proto == "ssh":
cmd += " -p " + str(self.port)
elif proto == "sftp":
cmd += " -P " + str(self.port)
if is_from_mosh:
raw_opts = self.tags.get("mosh_ssh_options", "") if isinstance(self.tags, dict) else ""
if raw_opts:
ssh_opts = str(raw_opts).strip()
if re.search(r'(?:LocalCommand|ProxyCommand)', ssh_opts, re.IGNORECASE):
raise ValueError("mosh_ssh_options cannot contain LocalCommand or ProxyCommand")
try:
shlex.split(ssh_opts)
except ValueError as exc:
raise ValueError("Invalid mosh_ssh_options: unbalanced quotes") from exc
else:
raw_opts = self.options
if raw_opts:
opts = str(raw_opts).strip()
if proto == "sftp":
# Strip SSH-only flags that sftp doesn't support # Strip SSH-only flags that sftp doesn't support
opts = re.sub(r'(?<!\S)-[XxtTAaNf]\b', '', opts).strip() opts = re.sub(r'(?<!\S)-[XxtTAaNf]\b', '', opts).strip()
if opts: if opts:
@@ -1143,6 +1182,73 @@ class node:
cmd += f" {user_host}" cmd += f" {user_host}"
return cmd return cmd
@MethodHook
def _generate_mosh_cmd(self):
if str(self.host).startswith("-"):
raise ValueError("Host cannot start with '-'")
if self.user and str(self.user).startswith("-"):
raise ValueError("User cannot start with '-'")
if not self.host or re.search(r'[\s;|&$`><"\'\\]', str(self.host)):
raise ValueError(f"Invalid characters in host: '{self.host}'")
if self.user and re.search(r'[\s;|&$`><"\'\\]', str(self.user)):
raise ValueError(f"Invalid characters in user: '{self.user}'")
cmd_parts = ["mosh"]
if isinstance(self.tags, dict):
if self.tags.get("mosh_server"):
server_bin = str(self.tags["mosh_server"]).strip()
if server_bin:
cmd_parts.append(f"--server={shlex.quote(server_bin)}")
if self.tags.get("mosh_udp_port"):
udp_port = str(self.tags["mosh_udp_port"]).strip()
if udp_port:
if not re.match(r"^\d+(:\d+)?$", udp_port):
raise ValueError(
f"Invalid mosh_udp_port '{udp_port}': must be PORT or PORT1:PORT2"
)
cmd_parts.append(f"-p {shlex.quote(udp_port)}")
ssh_parts = ["ssh"]
if self.port != "" and self.port is not None:
port_s = str(self.port).strip()
if port_s:
if not re.fullmatch(r"^\d+$", port_s) or not (1 <= int(port_s) <= 65535):
raise ValueError(f"Invalid TCP SSH port '{self.port}'")
ssh_parts.append(f"-p {port_s}")
if isinstance(self.tags, dict) and self.tags.get("mosh_ssh_options"):
ssh_opts = str(self.tags["mosh_ssh_options"]).strip()
if ssh_opts:
if re.search(r'(?:LocalCommand|ProxyCommand)', ssh_opts, re.IGNORECASE):
raise ValueError("mosh_ssh_options cannot contain LocalCommand or ProxyCommand")
try:
shlex.split(ssh_opts)
except ValueError as exc:
raise ValueError("Invalid mosh_ssh_options: unbalanced quotes") from exc
ssh_parts.append(ssh_opts)
if self.jumphost:
ssh_parts.append(self.jumphost)
if len(ssh_parts) > 1:
raw_ssh = " ".join(ssh_parts)
cmd_parts.append(f"--ssh={shlex.quote(raw_ssh)}")
if self.options:
opts = str(self.options).strip()
if opts:
if re.search(r'--(?:ssh|server|client)(?:=|\s|$)', opts):
raise ValueError("Options cannot override --ssh, --server or --client for mosh")
if re.search(r'(?:LocalCommand|ProxyCommand)', opts, re.IGNORECASE):
raise ValueError("Options cannot contain LocalCommand or ProxyCommand")
try:
shlex.split(opts)
except ValueError as exc:
raise ValueError("Invalid options: unbalanced quotes") from exc
cmd_parts.append(opts)
user_host = f"{self.user}@{self.host}" if self.user else self.host
cmd_parts.extend(["--", user_host])
return " ".join(cmd_parts)
@MethodHook @MethodHook
def _generate_telnet_cmd(self): def _generate_telnet_cmd(self):
cmd = f"telnet {self.host}" cmd = f"telnet {self.host}"
@@ -1181,9 +1287,11 @@ class node:
@MethodHook @MethodHook
def _get_cmd(self): def _get_cmd(self, force_ssh=False):
if self.protocol in ["ssh", "sftp"]: if force_ssh or self.protocol in ["ssh", "sftp"]:
return self._generate_ssh_sftp_cmd() return self._generate_ssh_sftp_cmd(force_ssh=force_ssh)
elif self.protocol == "mosh":
return self._generate_mosh_cmd()
elif self.protocol == "telnet": elif self.protocol == "telnet":
return self._generate_telnet_cmd() return self._generate_telnet_cmd()
elif self.protocol == "kubectl": elif self.protocol == "kubectl":
@@ -1198,25 +1306,56 @@ class node:
printer.error(f"Invalid protocol: {self.protocol}") printer.error(f"Invalid protocol: {self.protocol}")
sys.exit(1) sys.exit(1)
def _spawn_child(self, args, protocol=None):
if protocol is None:
protocol = getattr(self, "protocol", "")
env = None
if protocol == "mosh":
env = os.environ.copy()
if not any(
"utf-8" in env.get(k, "").lower() or "utf8" in env.get(k, "").lower()
for k in ("LC_ALL", "LC_CTYPE", "LANG")
):
env["LC_ALL"] = "C.UTF-8"
env.setdefault("TERM", "xterm-256color")
try:
if env is not None:
return pexpect.spawn(args[0], args[1:], env=env), None
return pexpect.spawn(args[0], args[1:]), None
except pexpect.exceptions.ExceptionPexpect as e:
return None, f"Connection failed: {e}"
@MethodHook @MethodHook
def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None): def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None, force_ssh=False):
if self.protocol == "local": effective_protocol = "ssh" if force_ssh else self.protocol
if effective_protocol == "mosh":
import shutil
if shutil.which("mosh") is None:
return "Connection failed: mosh binary not found in PATH"
timeout = max(timeout, 15)
if effective_protocol == "local":
cmd = self._get_cmd() cmd = self._get_cmd()
args = shlex.split(cmd) args = shlex.split(cmd)
self.child = pexpect.spawn(args[0], args[1:], env=os.environ.copy()) child, err = self._spawn_child(args, protocol=effective_protocol)
if err:
return err
self.child = child
from pexpect import fdpexpect from pexpect import fdpexpect
self.raw_child = fdpexpect.fdspawn(self.child.child_fd) self.raw_child = fdpexpect.fdspawn(self.child.child_fd)
if self.logs != '': if self.logs != '':
self.logfile = self._logfile() self.logfile = self._logfile()
return True return True
cmd = self._get_cmd() cmd = self._get_cmd(force_ssh=force_ssh)
passwords = self._passtx(self.password) if self.password and any(self.password) else [] passwords = self._passtx(self.password) if self.password and any(self.password) else []
if self.logs != '': if self.logs != '':
self.logfile = self._logfile() self.logfile = self._logfile()
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$' default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
prompt = self.tags.get("prompt", default_prompt) if isinstance(self.tags, dict) else default_prompt prompt = self.tags.get("prompt", default_prompt) if isinstance(self.tags, dict) else default_prompt
password_prompt = '[p|P]assword:|[u|U]sername:' if self.protocol != 'telnet' else '[p|P]assword:' password_prompt = '[p|P]assword:|[u|U]sername:' if effective_protocol != 'telnet' else '[p|P]assword:'
prompt_unanchored = "|".join([t[:-1] if t.endswith("$") else t for t in prompt.split("|")])
mosh_prompt = r"(?:" + prompt_unanchored + r")\s*(?:\[[0-9;?]*[a-zA-Z])*$"
expects = { expects = {
"ssh": ['yes/no', 'refused', 'supported', 'Invalid|[u|U]sage: ssh', 'ssh-keygen.*\"', 'timeout|timed.out', 'unavailable', 'closed', password_prompt, prompt, 'suspend', pexpect.EOF, pexpect.TIMEOUT, "No route to host", "resolve hostname", "no matching", "[b|B]ad (owner|permissions)"], "ssh": ['yes/no', 'refused', 'supported', 'Invalid|[u|U]sage: ssh', 'ssh-keygen.*\"', 'timeout|timed.out', 'unavailable', 'closed', password_prompt, prompt, 'suspend', pexpect.EOF, pexpect.TIMEOUT, "No route to host", "resolve hostname", "no matching", "[b|B]ad (owner|permissions)"],
@@ -1226,6 +1365,28 @@ class node:
"docker": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'not a docker command', 'unknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF], "docker": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'not a docker command', 'unknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF],
"ssm": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'SessionManagerPlugin', '[u|U]nknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF] "ssm": ['[u|U]sername:', 'Cannot', '[E|e]rror', 'failed', 'SessionManagerPlugin', '[u|U]nknown', 'unable to resolve', pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF]
} }
expects["mosh"] = [
'yes/no', # 0 (initial)
r'(?:ssh: connect to host .* port .*: Connection refused|Connection refused)', # 1 (error)
r'(?:ssh|mosh): .*supported', # 2 (error)
r'(?:(?:ssh|mosh): (?:Invalid|usage)|Unknown option:)', # 3 (error)
'ssh-keygen.*\"', # 4 (error)
r'(?:ssh: connect to host .* port .*: Connection timed out|mosh: .* timed out)', # 5 (error)
r'(?:ssh|mosh): .*unavailable', # 6 (error)
r'(?:Connection to .* closed|Connection closed by remote host)', # 7 (error)
password_prompt, # 8 (eof)
mosh_prompt, # 9 (eof)
'suspend', # 10 (eof)
pexpect.EOF, # 11 (eof)
pexpect.TIMEOUT, # 12 (error)
"No route to host", # 13 (error)
"resolve hostname", # 14 (error)
r'(?:ssh|mosh): .*no matching', # 15 (error)
"[b|B]ad (owner|permissions)", # 16 (error)
"mosh-server:.*not found|command not found", # 17 (error)
r"(?:Did not find mosh server startup message|(?:mosh: )?Nothing received from server on UDP port \d+\.?|Nothing received from server)", # 18 (error)
"needs a UTF-8 native locale to run|requires a UTF-8 locale|locale.*not available", # 19 (error)
]
error_indices = { error_indices = {
"ssh": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16], "ssh": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
@@ -1233,7 +1394,8 @@ class node:
"telnet": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16], "telnet": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
"kubectl": [1, 2, 3, 4, 8], # Define error indices for kube "kubectl": [1, 2, 3, 4, 8], # Define error indices for kube
"docker": [1, 2, 3, 4, 5, 6, 7], # Define error indices for docker "docker": [1, 2, 3, 4, 5, 6, 7], # Define error indices for docker
"ssm": [1, 2, 3, 4, 5, 6, 7] "ssm": [1, 2, 3, 4, 5, 6, 7],
"mosh": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19]
} }
eof_indices = { eof_indices = {
@@ -1242,7 +1404,8 @@ class node:
"telnet": [8, 9, 10, 11], "telnet": [8, 9, 10, 11],
"kubectl": [5, 6, 7], # Define eof indices for kube "kubectl": [5, 6, 7], # Define eof indices for kube
"docker": [8, 9, 10], # Define eof indices for docker "docker": [8, 9, 10], # Define eof indices for docker
"ssm": [8, 9, 10] "ssm": [8, 9, 10],
"mosh": [8, 9, 10, 11]
} }
initial_indices = { initial_indices = {
@@ -1251,13 +1414,17 @@ class node:
"telnet": [0], "telnet": [0],
"kubectl": [0], # Define special indices for kube "kubectl": [0], # Define special indices for kube
"docker": [0], # Define special indices for docker "docker": [0], # Define special indices for docker
"ssm": [0] "ssm": [0],
"mosh": [0]
} }
attempts = 1 attempts = 1
handshake_progressed = False
while attempts <= max_attempts: while attempts <= max_attempts:
args = shlex.split(cmd) args = shlex.split(cmd)
child = pexpect.spawn(args[0], args[1:]) child, err = self._spawn_child(args, protocol=effective_protocol)
if err:
return err
if isinstance(self.tags, dict) and self.tags.get("console"): if isinstance(self.tags, dict) and self.tags.get("console"):
child.sendline() child.sendline()
if debug: if debug:
@@ -1271,33 +1438,58 @@ class node:
endloop = False endloop = False
for i in range(len(passwords) if passwords else 1): for i in range(len(passwords) if passwords else 1):
while True: while True:
results = child.expect(expects[self.protocol], timeout=timeout) results = child.expect(expects[effective_protocol], timeout=timeout)
results_value = expects[self.protocol][results] results_value = expects[effective_protocol][results]
if results in initial_indices[self.protocol]: if results in initial_indices[effective_protocol]:
if self.protocol in ["ssh", "sftp"]: if effective_protocol in ["ssh", "sftp", "mosh"]:
child.sendline('yes') child.sendline('yes')
elif self.protocol in ["telnet", "kubectl", "docker", "ssm"]: handshake_progressed = True
elif effective_protocol in ["telnet", "kubectl", "docker", "ssm"]:
if self.user: if self.user:
child.sendline(self.user) child.sendline(self.user)
else: else:
self.missingtext = True self.missingtext = True
break break
elif results in error_indices[self.protocol]: elif results in error_indices[effective_protocol]:
try:
child.terminate() child.terminate()
if results_value == pexpect.TIMEOUT and attempts != max_attempts: except Exception:
pass
can_retry = (
results_value == pexpect.TIMEOUT
and attempts != max_attempts
and not (effective_protocol == "mosh" and handshake_progressed)
)
if can_retry:
attempts += 1 attempts += 1
endloop = True endloop = True
break break
else: else:
after = "Connection timeout" if results_value == pexpect.TIMEOUT else child.after.decode() def _to_str(val):
return f"Connection failed code: {results}\n{child.before.decode().lstrip()}{after}{child.readline().decode()}".rstrip() if val is None:
return ""
if hasattr(val, "decode"):
return val.decode()
return str(val)
after = "Connection timeout" if results_value == pexpect.TIMEOUT else _to_str(child.after)
before = _to_str(child.before)
readline_val = _to_str(child.readline())
if effective_protocol == "mosh":
after = self._logclean(after, True)
before = self._logclean(before, True)
readline_val = self._logclean(readline_val, True)
if effective_protocol == "mosh" and results == 18 and ("Nothing received from server" in after or "Nothing received from server" in before):
err_msg = after.strip() if "Nothing received from server" in after else before.strip()
return f"Connection failed code: {results}\n{err_msg} — UDP traffic is blocked or unreachable. Verify firewall rules for UDP ports (60000-61000 or mosh_udp_port)."
return f"Connection failed code: {results}\n{before.lstrip()}{after}{readline_val}".rstrip()
elif results in eof_indices[self.protocol]: elif results in eof_indices[effective_protocol]:
if results_value == password_prompt: if results_value == password_prompt:
if passwords: if passwords:
child.sendline(passwords[i]) child.sendline(passwords[i])
handshake_progressed = True
else: else:
self.missingtext = True self.missingtext = True
break break
+3
View File
@@ -161,6 +161,9 @@ class NodeServicer(connpy_pb2_grpc.NodeServiceServicer):
setattr(n, attr, params[attr]) setattr(n, attr, params[attr])
if "tags" in params: if "tags" in params:
n.tags = params["tags"] n.tags = params["tags"]
n._orig_protocol = n.protocol
if sftp:
n.protocol = "sftp"
else: else:
try: try:
node_data = user_config.getitem(unique_id, extract=False) node_data = user_config.getitem(unique_id, extract=False)
+13
View File
@@ -323,4 +323,17 @@ def test_node_connect_exact_match_priority(mock_connect_node, mock_list_nodes, a
mock_connect_node.assert_called_once_with("pe1@ctx", sftp=False, debug=False, logger=app._service_logger) mock_connect_node.assert_called_once_with("pe1@ctx", sftp=False, debug=False, logger=app._service_logger)
def test_validators_accept_mosh(app):
"""Validators accept mosh protocol and reject invalid protocols."""
import inquirer
from connpy.cli.validators import Validators
val = Validators(app)
assert val.protocol_validation({}, "mosh") is True
assert val.profile_protocol_validation({}, "mosh") is True
with pytest.raises(inquirer.errors.ValidationError):
val.protocol_validation({}, "invalid_proto")
with pytest.raises(inquirer.errors.ValidationError):
val.profile_protocol_validation({}, "invalid_proto")
+451
View File
@@ -748,3 +748,454 @@ class TestJumphostChain:
assert 'aws ssm start-session' in n.jumphost assert 'aws ssm start-session' in n.jumphost
assert 'admin@10.0.0.2' in n.jumphost assert 'admin@10.0.0.2' in n.jumphost
assert '--region us-east-1' in n.jumphost assert '--region us-east-1' in n.jumphost
# =========================================================================
# Mosh protocol tests
# =========================================================================
class TestMoshProtocol:
"""Comprehensive tests for Mosh (Mobile Shell) protocol support."""
def _make_config_with_nodes(self, tmp_config_dir, nodes, profiles=None):
import yaml
from connpy.configfile import configfile
if profiles is None:
profiles = {
"default": {
"host": "", "protocol": "ssh", "port": "", "user": "",
"password": "", "options": "", "logs": "", "tags": "", "jumphost": ""
}
}
data = {
"config": {"case": False, "idletime": 30, "fzf": False},
"connections": nodes,
"profiles": profiles
}
config_file = tmp_config_dir / "config.yaml"
config_file.write_text(yaml.dump(data, default_flow_style=False, sort_keys=False))
os.chmod(str(config_file), 0o600)
return configfile(conf=str(config_file), key=str(tmp_config_dir / ".osk"))
def test_mosh_cmd_basic_and_double_dash(self):
"""Basic mosh command generation with double dash separator."""
from connpy.core import node
n = node("m1", "10.0.0.1", user="admin", protocol="mosh")
assert n._get_cmd() == "mosh -- admin@10.0.0.1"
def test_mosh_cmd_ssh_port(self):
"""Mosh command embeds SSH TCP port into --ssh option."""
import shlex
from connpy.core import node
n1 = node("m1", "10.0.0.1", user="admin", protocol="mosh", port="2222")
tokens1 = shlex.split(n1._get_cmd())
assert "--ssh=ssh -p 2222" in tokens1
n2 = node("m2", "10.0.0.1", user="admin", protocol="mosh", port=2222)
tokens2 = shlex.split(n2._get_cmd())
assert "--ssh=ssh -p 2222" in tokens2
def test_mosh_cmd_tags_and_quoting(self):
"""Mosh tags for udp port, server binary, and ssh options are properly quoted."""
import shlex
from connpy.core import node
tags = {
"mosh_udp_port": "60001:60005",
"mosh_server": "/opt/mosh bin/mosh-server",
"mosh_ssh_options": "-i /tmp/key.pem",
}
n = node(
"m1", "10.0.0.1", user="admin", protocol="mosh", port="2222",
options="--predict=always", tags=tags
)
tokens = shlex.split(n._get_cmd())
assert "--server=/opt/mosh bin/mosh-server" in tokens
assert "-p" in tokens
idx_p = tokens.index("-p")
assert tokens[idx_p + 1] == "60001:60005"
assert "--ssh=ssh -p 2222 -i /tmp/key.pem" in tokens
assert "--predict=always" in tokens
assert "--" in tokens
assert tokens[-1] == "admin@10.0.0.1"
def test_mosh_port_validation_and_ssh_backward_compat(self):
"""Invalid port values raise ValueError for mosh while preserving legacy ssh/sftp."""
from connpy.core import node
for bad_port in ["22; id", "0", "70000", "-1"]:
n = node("m1", "10.0.0.1", user="admin", protocol="mosh", port=bad_port)
with pytest.raises(ValueError, match="Invalid TCP SSH port"):
n._get_cmd()
n_sftp = node("m2", "10.0.0.1", user="admin", protocol="mosh", port=bad_port)
n_sftp.protocol = "sftp"
with pytest.raises(ValueError, match="Invalid TCP SSH port"):
n_sftp._get_cmd()
# Legacy backward compatibility: ssh and sftp preserve original behavior
ssh_node = node("s1", "10.0.0.1", user="admin", protocol="ssh", port="2222")
assert "-p 2222" in ssh_node._get_cmd()
sftp_node = node("sf1", "10.0.0.1", user="admin", protocol="sftp", port="2222")
assert "-P 2222" in sftp_node._get_cmd()
def test_mosh_rejects_leading_dash_in_host_or_user(self):
"""Reject leading dash, whitespace, or shell metacharacters in host and user."""
from connpy.core import node
with pytest.raises(ValueError, match="Host cannot start with '-'"):
node("m1", "-oProxyCommand=evil", protocol="mosh")._get_cmd()
with pytest.raises(ValueError, match="User cannot start with '-'"):
node("m1", "10.0.0.1", user="-oProxyCommand=evil", protocol="mosh")._get_cmd()
for bad_host in ["10.0.0.1; id", "admin user", "host`id`", "host$id", "host|id", "host&id"]:
with pytest.raises(ValueError, match="Invalid characters in host"):
node("m1", bad_host, protocol="mosh")._get_cmd()
for bad_user in ["admin user", "user;id", "user`id`", "user$id", "user|id", "user&id"]:
with pytest.raises(ValueError, match="Invalid characters in user"):
node("m1", "10.0.0.1", user=bad_user, protocol="mosh")._get_cmd()
def test_mosh_rejects_forbidden_options_and_local_command(self):
"""Reject dangerous options, command injection attempts, and unbalanced quotes."""
from connpy.core import node
for forbidden in [
"--ssh='ssh -o ProxyCommand=evil'",
"--server=/tmp/x",
"--client=/tmp/y",
"--ssh",
"--server",
"--client"
]:
with pytest.raises(ValueError, match="Options cannot override --ssh, --server or --client for mosh"):
node("m1", "10.0.0.1", protocol="mosh", options=forbidden)._get_cmd()
# Legitimate options such as --ssh-agent are not falsely rejected
n_agent = node("m1", "10.0.0.1", protocol="mosh", options="--ssh-agent")
assert "--ssh-agent" in n_agent._get_cmd()
# LocalCommand / ProxyCommand in mosh_ssh_options
with pytest.raises(ValueError, match="mosh_ssh_options cannot contain LocalCommand or ProxyCommand"):
node("m1", "10.0.0.1", protocol="mosh", tags={"mosh_ssh_options": "-o LocalCommand='id'"})._get_cmd()
with pytest.raises(ValueError, match="mosh_ssh_options cannot contain LocalCommand or ProxyCommand"):
node("m1", "10.0.0.1", protocol="mosh", tags={"mosh_ssh_options": "-o ProxyCommand='nc'"})._get_cmd()
# LocalCommand / ProxyCommand in options
with pytest.raises(ValueError, match="Options cannot contain LocalCommand or ProxyCommand"):
node("m1", "10.0.0.1", protocol="mosh", options="-o LocalCommand='id'")._get_cmd()
with pytest.raises(ValueError, match="Options cannot contain LocalCommand or ProxyCommand"):
node("m1", "10.0.0.1", protocol="mosh", options="-o ProxyCommand='nc'")._get_cmd()
# Unbalanced quotes
with pytest.raises(ValueError, match="Invalid options: unbalanced quotes"):
node("m1", "10.0.0.1", protocol="mosh", options='--predict="always')._get_cmd()
with pytest.raises(ValueError, match="Invalid mosh_ssh_options: unbalanced quotes"):
node("m1", "10.0.0.1", protocol="mosh", tags={"mosh_ssh_options": '-i "/tmp/unclosed'})._get_cmd()
# Invalid mosh_udp_port
with pytest.raises(ValueError, match="Invalid mosh_udp_port"):
node("m1", "10.0.0.1", protocol="mosh", tags={"mosh_udp_port": "60001 --ssh=evil"})._get_cmd()
def test_mosh_cmd_with_two_hop_chained_jumphost(self, tmp_config_dir):
"""Two-hop chained SSH jumphost maintains nested ProxyCommand correctly inside --ssh."""
import shlex
from connpy.core import node
nodes = {
"bastionB": {
"host": "10.0.0.1", "protocol": "ssh", "port": "22",
"user": "userB", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "", "type": "connection"
},
"bastionA": {
"host": "10.0.0.2", "protocol": "ssh", "port": "22",
"user": "userA", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "bastionB", "type": "connection"
},
"dest": {
"host": "10.0.1.1", "protocol": "mosh", "port": "2222",
"user": "root", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "bastionA", "type": "connection"
}
}
config = self._make_config_with_nodes(tmp_config_dir, nodes)
n = node(
"dest", "10.0.1.1", user="root", protocol="mosh", port="2222",
jumphost="bastionA", config=config
)
cmd = n._get_cmd()
tokens = shlex.split(cmd)
ssh_token = [t for t in tokens if t.startswith("--ssh=")]
assert len(ssh_token) == 1
assert "ProxyCommand=" in ssh_token[0]
assert "userA@10.0.0.2" in ssh_token[0]
assert "userB@10.0.0.1" in ssh_token[0]
assert "-p 2222" in ssh_token[0]
assert tokens[-1] == "root@10.0.1.1"
def test_mosh_as_single_or_chained_jumphost_raises(self, tmp_config_dir):
"""A mosh node cannot be used as a direct or chained jumphost."""
from connpy.core import node
nodes1 = {
"mosh_bastion": {
"host": "10.0.0.1", "protocol": "mosh", "port": "",
"user": "admin", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "", "type": "connection"
},
"dest": {
"host": "10.0.1.1", "protocol": "ssh", "port": "",
"user": "root", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "mosh_bastion", "type": "connection"
}
}
config1 = self._make_config_with_nodes(tmp_config_dir, nodes1)
with pytest.raises(ValueError, match="cannot be used as a jumphost"):
node("dest", "10.0.1.1", jumphost="mosh_bastion", config=config1)
nodes2 = {
"mosh_bastion": {
"host": "10.0.0.1", "protocol": "mosh", "port": "",
"user": "admin", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "", "type": "connection"
},
"bastionA": {
"host": "10.0.0.2", "protocol": "ssh", "port": "",
"user": "userA", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "mosh_bastion", "type": "connection"
},
"dest": {
"host": "10.0.1.1", "protocol": "ssh", "port": "",
"user": "root", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "bastionA", "type": "connection"
}
}
config2 = self._make_config_with_nodes(tmp_config_dir, nodes2)
with pytest.raises(ValueError, match="cannot be used as a jumphost"):
node("dest", "10.0.1.1", jumphost="bastionA", config=config2)
def test_mosh_sftp_override_and_ssh_options_isolation(self, tmp_config_dir):
"""Switching a mosh node to sftp preserves _orig_protocol and uses mosh_ssh_options."""
from connpy.core import node
nodes = {
"bastion": {
"host": "10.0.0.1", "protocol": "ssh", "port": "",
"user": "admin", "password": "", "options": "",
"logs": "", "tags": "", "jumphost": "", "type": "connection"
},
"dest": {
"host": "10.0.1.1", "protocol": "@mosh_prof", "port": "2222",
"user": "root", "password": "", "options": "--predict=always",
"logs": "", "tags": {"mosh_ssh_options": "-i /tmp/key.pem -t"},
"jumphost": "bastion", "type": "connection"
}
}
profiles = {
"default": {"protocol": "ssh"},
"mosh_prof": {
"protocol": "mosh", "host": "", "user": "", "port": "",
"password": "", "options": "", "logs": "", "tags": "", "jumphost": ""
}
}
config = self._make_config_with_nodes(tmp_config_dir, nodes, profiles=profiles)
n = node(
"dest", "10.0.1.1", protocol="@mosh_prof", port="2222", user="root",
options="--predict=always", tags={"mosh_ssh_options": "-i /tmp/key.pem -t"},
jumphost="bastion", config=config
)
assert n._orig_protocol == "mosh"
assert n.protocol == "mosh"
# Switch to sftp
n.protocol = "sftp"
cmd = n._get_cmd()
assert cmd.startswith("sftp -P 2222")
assert "-i /tmp/key.pem" in cmd
assert " -t" not in cmd # -t stripped for sftp
assert "--predict=always" not in cmd # options discarded for is_from_mosh
assert "-o ProxyCommand=" in cmd
assert cmd.endswith("root@10.0.1.1")
def test_mosh_run_and_test_use_force_ssh_without_mutating_protocol(self):
"""Batch commands on mosh nodes connect via SSH without mutating self.protocol."""
from connpy.core import node
n = node(
"m1", "10.0.0.1", user="admin", protocol="mosh", port="2222",
options="--predict=always", tags={"mosh_ssh_options": "-i /tmp/key.pem"}
)
ssh_cmd = n._get_cmd(force_ssh=True)
assert ssh_cmd.startswith("ssh -p 2222")
assert "-i /tmp/key.pem" in ssh_cmd
assert "--predict=always" not in ssh_cmd
assert n.protocol == "mosh"
mock_child = MagicMock()
mock_child.expect.return_value = 0
with patch.object(n, "_connect", return_value=True) as mock_conn:
n.child = mock_child
n.run(["show version"])
mock_conn.assert_called_once()
_, kwargs = mock_conn.call_args
assert kwargs.get("force_ssh") is True
assert n.protocol == "mosh"
with patch.object(n, "_connect", return_value=True) as mock_conn_test:
n.child = mock_child
with patch.object(n, "_logclean", return_value="1.1.1.1 is alive"):
n.test(["ping 1.1.1.1"], "1.1.1.1")
mock_conn_test.assert_called_once()
_, kwargs = mock_conn_test.call_args
assert kwargs.get("force_ssh") is True
assert n.protocol == "mosh"
def test_mosh_connect_timeout_min_15_and_strict_esc_mosh_prompt(self):
"""Mosh connect enforces min 15s timeout and strict escape requirement in prompt."""
from connpy.core import node
n = node("m1", "10.0.0.1", user="admin", protocol="mosh")
mock_child = MagicMock()
mock_child.expect.side_effect = [0, 9] # 0: yes/no, 9: mosh_prompt
with patch("shutil.which", return_value="/usr/bin/mosh"), \
patch("pexpect.spawn", return_value=mock_child), \
patch("pexpect.fdpexpect.fdspawn"):
res = n._connect(timeout=10)
assert res is True
for call in mock_child.expect.call_args_list:
assert call[1]["timeout"] == 15
mock_child.sendline.assert_any_call("yes")
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
prompt_unanchored = "|".join([t[:-1] if t.endswith("$") else t for t in default_prompt.split("|")])
mosh_prompt_pattern = r"(?:" + prompt_unanchored + r")\s*(?:\x1b\[[0-9;?]*[a-zA-Z])*$"
# Must NOT match empty alternate screen without real prompt
assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;1H") is None
assert re.search(mosh_prompt_pattern, "admin@host:~$ \x1b[1;15H") is not None
assert re.search(mosh_prompt_pattern, "admin@host:~$ ") is not None
assert re.search(mosh_prompt_pattern, "admin@host:~$") is not None
# Must not match MOTD words
for word in ["supported", "unavailable", "refused", "closed", "timeout"]:
assert re.search(mosh_prompt_pattern, f"MOTD: System is {word}") is None
def test_mosh_connect_errors_missing_binary_and_no_post_handshake_retry(self):
"""Mosh connection handles missing binary, locale errors, and suppresses post-handshake retry."""
from connpy.core import node
n = node("m1", "10.0.0.1", user="admin", protocol="mosh")
# 1. Missing mosh binary
with patch("shutil.which", return_value=None), \
patch("pexpect.spawn") as mock_spawn:
err = n._connect()
assert err == "Connection failed: mosh binary not found in PATH"
mock_spawn.assert_not_called()
# 2. Locale and server not found errors
for idx, err_msg in [(19, "needs a UTF-8 native locale to run"), (17, "mosh-server: command not found")]:
mock_child = MagicMock()
mock_child.expect.return_value = idx
mock_child.after = err_msg.encode()
mock_child.before = b""
mock_child.readline.return_value = b""
with patch("shutil.which", return_value="/usr/bin/mosh"), \
patch("pexpect.spawn", return_value=mock_child):
res = n._connect()
assert f"Connection failed code: {idx}" in res
assert err_msg in res
# 3. No retry on timeout after handshake progressed
mock_child = MagicMock()
mock_child.expect.side_effect = [0, 12] # 0: yes/no, then 12: TIMEOUT
mock_child.before = b"Mosh connecting..."
mock_child.readline.return_value = b""
with patch("shutil.which", return_value="/usr/bin/mosh"), \
patch("pexpect.spawn", return_value=mock_child) as mock_spawn:
res = n._connect(max_attempts=3)
assert mock_spawn.call_count == 1
assert "Connection failed code: 12" in res
assert "Connection timeout" in res
def test_mosh_spawn_child_env_isolation(self):
"""_spawn_child applies LC_ALL=C.UTF-8 only for mosh and leaves env untouched for other protocols."""
from connpy.core import node
n_mosh = node("m1", "10.0.0.1", protocol="mosh")
n_ssh = node("s1", "10.0.0.1", protocol="ssh")
# When running mosh with a non-utf8 environment, LC_ALL=C.UTF-8 is injected
with patch.dict(os.environ, {"LC_ALL": "C", "LANG": "C", "LC_CTYPE": "C"}, clear=True), \
patch("pexpect.spawn") as mock_spawn:
mock_spawn.return_value = MagicMock()
n_mosh._spawn_child(["mosh", "10.0.0.1"], protocol="mosh")
_, kwargs = mock_spawn.call_args
assert kwargs.get("env") is not None
assert kwargs["env"]["LC_ALL"] == "C.UTF-8"
assert kwargs["env"]["TERM"] == "xterm-256color"
# When running ssh, env is not passed (pexpect inherits default untouched)
with patch("pexpect.spawn") as mock_spawn:
mock_spawn.return_value = MagicMock()
n_ssh._spawn_child(["ssh", "10.0.0.1"], protocol="ssh")
_, kwargs = mock_spawn.call_args
assert kwargs.get("env") is None
def test_mosh_prompt_rejects_bare_alternate_screen_without_prompt(self):
"""mosh_prompt does not match empty alternate screen without a real remote shell prompt."""
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
prompt_unanchored = "|".join([t[:-1] if t.endswith("$") else t for t in default_prompt.split("|")])
mosh_prompt_pattern = r"(?:" + prompt_unanchored + r")\s*(?:\x1b\[[0-9;?]*[a-zA-Z])*$"
# Bare alternate screen escape sequences without remote prompt must NOT match
assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;1H") is None
assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;24r\x1b[4l") is None
assert re.search(mosh_prompt_pattern, "\x1b[?1049h") is None
assert re.search(mosh_prompt_pattern, "\x1b[?1049h\r\n") is None
# Real prompts with cursor sequences must match
assert re.search(mosh_prompt_pattern, "admin@host:~$ \x1b[1;15H") is not None
assert re.search(mosh_prompt_pattern, "router# ") is not None
assert re.search(mosh_prompt_pattern, "admin@host:~$ ") is not None
assert re.search(mosh_prompt_pattern, "user@host:~$ \x1b[?2004h") is not None
def test_mosh_connect_early_udp_block_detection_terminates_child_and_explicit_error(self):
"""Early UDP block detection terminates child, does not return True, and returns explicit firewall error."""
from connpy.core import node
n = node("m1", "10.0.0.1", user="admin", protocol="mosh")
mock_child = MagicMock()
mock_child.expect.return_value = 18 # index 18: UDP error pattern
mock_child.after = b"mosh: Nothing received from server on UDP port 60001\r\n"
mock_child.before = b"\x1b[?1049h"
mock_child.readline.return_value = b""
with patch("shutil.which", return_value="/usr/bin/mosh"), \
patch("pexpect.spawn", return_value=mock_child):
res = n._connect()
# Ensure does NOT return True
assert res is not True
assert isinstance(res, str)
# Ensure child.terminate was called
mock_child.terminate.assert_called()
# Verify explicit firewall error message
assert "Connection failed code: 18" in res
assert "Nothing received from server on UDP port 60001" in res
assert "UDP traffic is blocked or unreachable" in res
assert "Verify firewall rules for UDP ports" in res
assert "\x1b[?1049h" not in res # Cleaned of alternate screen escapes
# Test with bare 'Nothing received from server on UDP port 60001'
mock_child2 = MagicMock()
mock_child2.expect.return_value = 18
mock_child2.after = b"Nothing received from server on UDP port 60001"
mock_child2.before = b""
mock_child2.readline.return_value = b""
with patch("shutil.which", return_value="/usr/bin/mosh"), \
patch("pexpect.spawn", return_value=mock_child2):
res2 = n._connect()
assert res2 is not True
mock_child2.terminate.assert_called()
assert "Connection failed code: 18" in res2
assert "UDP traffic is blocked or unreachable" in res2
+46
View File
@@ -14,6 +14,10 @@ class MockContext:
# --- UNIT TESTS (with mocks) --- # --- UNIT TESTS (with mocks) ---
@pytest.fixture
def grpc_servicer(populated_config):
return server.NodeServicer(populated_config)
class TestNodeServicerNaming: class TestNodeServicerNaming:
@pytest.fixture @pytest.fixture
def servicer(self, populated_config): def servicer(self, populated_config):
@@ -288,3 +292,45 @@ class TestGRPCIntegration:
assert reqs[0].copilot_action == "custom:show ip route" assert reqs[0].copilot_action == "custom:show ip route"
assert reqs[1].copilot_action == "cancel" assert reqs[1].copilot_action == "cancel"
def test_grpc_interact_node_mosh_sftp_preserves_orig_protocol(grpc_servicer):
"""Test NodeServiceServicer.interact_node with sftp=True preserves _orig_protocol='mosh'."""
servicer = grpc_servicer
params = {
"host": "10.0.0.15",
"user": "admin",
"protocol": "mosh",
"port": "2222",
"options": "--predict=always",
"tags": {"mosh_ssh_options": "-i /tmp/key.pem"}
}
request = connpy_pb2.InteractRequest(
id="dynamic",
connection_params_json=json.dumps(params),
sftp=True
)
from connpy.core import node as real_node
with patch("connpy.core.node") as mock_node_cls:
created_nodes = []
def fake_node_constructor(*args, **kwargs):
real_instance = real_node(*args, **kwargs)
real_instance._connect = MagicMock(return_value=True)
created_nodes.append(real_instance)
return real_instance
mock_node_cls.side_effect = fake_node_constructor
gen = servicer.interact_node(iter([request]), MockContext())
res = next(gen)
assert res.success is True
assert len(created_nodes) > 0
inst = created_nodes[0]
assert inst.protocol == "sftp"
assert getattr(inst, "_orig_protocol", "") == "mosh"
cmd = inst._get_cmd()
assert "sftp" in cmd
assert "-i /tmp/key.pem" in cmd
assert "--predict=always" not in cmd
+32
View File
@@ -64,3 +64,35 @@ def test_list_nodes_case_sensitivity(populated_config):
# Default case is False (case-insensitive) # Default case is False (case-insensitive)
nodes = service.list_nodes(filter_str="ROUTER") nodes = service.list_nodes(filter_str="ROUTER")
assert "router1" in nodes assert "router1" in nodes
def test_connect_node_mosh_and_sftp_override(populated_config):
"""Test connect_node preserves mosh by default and switches to sftp while keeping _orig_protocol."""
from unittest.mock import patch, MagicMock
from connpy.core import node
service = NodeService(populated_config)
service.add_node("mosh1", {
"host": "10.0.0.99",
"user": "admin",
"protocol": "mosh",
"port": "22",
"options": "",
"logs": "",
"tags": {},
"jumphost": "",
"type": "connection"
})
mock_interact = MagicMock()
with patch.object(getattr(node, "cls", node), "interact", lambda *a, **kw: mock_interact(*a, **kw)):
service.connect_node("mosh1", sftp=False)
node_obj = mock_interact.call_args[0][0]
assert node_obj.protocol == "mosh"
assert getattr(node_obj, "_orig_protocol", "") == "mosh"
service.connect_node("mosh1", sftp=True)
node_obj_sftp = mock_interact.call_args[0][0]
assert node_obj_sftp.protocol == "sftp"
assert getattr(node_obj_sftp, "_orig_protocol", "") == "mosh"
+4
View File
@@ -91,6 +91,7 @@ Here are some important instructions and tips for configuring your new node:
2. **Available Protocols and Apps**: 2. **Available Protocols and Apps**:
- ssh - ssh
- mosh (requires remote mosh-server and UDP ports 60000-61000 open; --sftp uses SSH TCP)
- telnet - telnet
- kubectl (`kubectl exec`) - kubectl (`kubectl exec`)
- docker (`docker exec`) - docker (`docker exec`)
@@ -121,6 +122,9 @@ Here are some important instructions and tips for configuring your new node:
- `profile`: AWS Profile used for `aws ssm start-session`. - `profile`: AWS Profile used for `aws ssm start-session`.
- `ssh_options`: Additional SSH options injected when an SSM node is used as a jumphost (e.g., `-i ~/.ssh/key.pem`). - `ssh_options`: Additional SSH options injected when an SSM node is used as a jumphost (e.g., `-i ~/.ssh/key.pem`).
- `nc_command`: Replaces the default `nc` command used when bridging connections through Docker or Kubernetes (e.g., `ip netns exec global-vrf nc`). - `nc_command`: Replaces the default `nc` command used when bridging connections through Docker or Kubernetes (e.g., `ip netns exec global-vrf nc`).
- `mosh_udp_port`: Server-side UDP port or range (`PORT` or `PORT1:PORT2`) passed as `-p` to `mosh`.
- `mosh_server`: Path to the `mosh-server` binary on the remote host (`--server`).
- `mosh_ssh_options`: Additional SSH options injected into `mosh --ssh=&#34;ssh ...&#34;` and reused when connecting via `--sftp` or running batch commands (`run`/`test`).
&#34;&#34;&#34; &#34;&#34;&#34;
if type == &#34;bashcompletion&#34;: if type == &#34;bashcompletion&#34;:
return &#39;&#39;&#39; return &#39;&#39;&#39;
+10 -10
View File
@@ -67,14 +67,14 @@ el.replaceWith(d);
_raise_val_err(&#34;Profile {} don&#39;t exist&#34;.format(current)) _raise_val_err(&#34;Profile {} don&#39;t exist&#34;.format(current))
return True return True
def profile_protocol_validation(self, answers, current, regex = &#34;(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)&#34;): def profile_protocol_validation(self, answers, current, regex = &#34;(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)&#34;):
if not re.match(regex, current): if not re.match(regex, current):
_raise_val_err(&#34;Pick between ssh, telnet, kubectl, docker, ssm or leave empty&#34;) _raise_val_err(&#34;Pick between ssh, mosh, telnet, kubectl, docker, ssm or leave empty&#34;)
return True return True
def protocol_validation(self, answers, current, regex = &#34;(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)&#34;): def protocol_validation(self, answers, current, regex = &#34;(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)&#34;):
if not re.match(regex, current): if not re.match(regex, current):
_raise_val_err(&#34;Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile&#34;) _raise_val_err(&#34;Pick between ssh, mosh, telnet, kubectl, docker, ssm, leave empty or @profile&#34;)
if current.startswith(&#34;@&#34;): if current.startswith(&#34;@&#34;):
if current[1:] not in self.app.profiles: if current[1:] not in self.app.profiles:
_raise_val_err(&#34;Profile {} don&#39;t exist&#34;.format(current)) _raise_val_err(&#34;Profile {} don&#39;t exist&#34;.format(current))
@@ -389,16 +389,16 @@ el.replaceWith(d);
<div class="desc"></div> <div class="desc"></div>
</dd> </dd>
<dt id="connpy.cli.validators.Validators.profile_protocol_validation"><code class="name flex"> <dt id="connpy.cli.validators.Validators.profile_protocol_validation"><code class="name flex">
<span>def <span class="ident">profile_protocol_validation</span></span>(<span>self, answers, current, regex='(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)')</span> <span>def <span class="ident">profile_protocol_validation</span></span>(<span>self,<br>answers,<br>current,<br>regex='(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)')</span>
</code></dt> </code></dt>
<dd> <dd>
<details class="source"> <details class="source">
<summary> <summary>
<span>Expand source code</span> <span>Expand source code</span>
</summary> </summary>
<pre><code class="python">def profile_protocol_validation(self, answers, current, regex = &#34;(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)&#34;): <pre><code class="python">def profile_protocol_validation(self, answers, current, regex = &#34;(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$)&#34;):
if not re.match(regex, current): if not re.match(regex, current):
_raise_val_err(&#34;Pick between ssh, telnet, kubectl, docker, ssm or leave empty&#34;) _raise_val_err(&#34;Pick between ssh, mosh, telnet, kubectl, docker, ssm or leave empty&#34;)
return True</code></pre> return True</code></pre>
</details> </details>
<div class="desc"></div> <div class="desc"></div>
@@ -425,16 +425,16 @@ el.replaceWith(d);
<div class="desc"></div> <div class="desc"></div>
</dd> </dd>
<dt id="connpy.cli.validators.Validators.protocol_validation"><code class="name flex"> <dt id="connpy.cli.validators.Validators.protocol_validation"><code class="name flex">
<span>def <span class="ident">protocol_validation</span></span>(<span>self,<br>answers,<br>current,<br>regex='(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)')</span> <span>def <span class="ident">protocol_validation</span></span>(<span>self,<br>answers,<br>current,<br>regex='(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)')</span>
</code></dt> </code></dt>
<dd> <dd>
<details class="source"> <details class="source">
<summary> <summary>
<span>Expand source code</span> <span>Expand source code</span>
</summary> </summary>
<pre><code class="python">def protocol_validation(self, answers, current, regex = &#34;(^ssh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)&#34;): <pre><code class="python">def protocol_validation(self, answers, current, regex = &#34;(^ssh$|^mosh$|^telnet$|^kubectl$|^docker$|^ssm$|^$|^@.+$)&#34;):
if not re.match(regex, current): if not re.match(regex, current):
_raise_val_err(&#34;Pick between ssh, telnet, kubectl, docker, ssm, leave empty or @profile&#34;) _raise_val_err(&#34;Pick between ssh, mosh, telnet, kubectl, docker, ssm, leave empty or @profile&#34;)
if current.startswith(&#34;@&#34;): if current.startswith(&#34;@&#34;):
if current[1:] not in self.app.profiles: if current[1:] not in self.app.profiles:
_raise_val_err(&#34;Profile {} don&#39;t exist&#34;.format(current)) _raise_val_err(&#34;Profile {} don&#39;t exist&#34;.format(current))
+3
View File
@@ -1467,6 +1467,9 @@ interceptor chooses to service this RPC, or None otherwise.</p></div>
setattr(n, attr, params[attr]) setattr(n, attr, params[attr])
if &#34;tags&#34; in params: if &#34;tags&#34; in params:
n.tags = params[&#34;tags&#34;] n.tags = params[&#34;tags&#34;]
n._orig_protocol = n.protocol
if sftp:
n.protocol = &#34;sftp&#34;
else: else:
try: try:
node_data = user_config.getitem(unique_id, extract=False) node_data = user_config.getitem(unique_id, extract=False)
+248 -51
View File
@@ -41,7 +41,7 @@ el.replaceWith(d);
<p align="center"> <p align="center">
<img src="https://nginx.gederico.dynu.net/images/CONNPY-resized.png" alt="App Logo"> <img src="https://nginx.gederico.dynu.net/images/CONNPY-resized.png" alt="App Logo">
</p> </p>
<h1 id="connpy-v630">Connpy (v6.3.0)</h1> <h1 id="connpy-v640b1">Connpy (v6.4.0b1)</h1>
<p><a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/v/connpy.svg?style=flat-square"></a> <p><a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/v/connpy.svg?style=flat-square"></a>
<a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square"></a> <a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/pyversions/connpy.svg?style=flat-square"></a>
<a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&amp;cacheSeconds=86400"></a> <a href="https://pypi.org/pypi/connpy/"><img alt="" src="https://img.shields.io/pypi/dm/connpy.svg?style=flat-square&amp;cacheSeconds=86400"></a>
@@ -50,7 +50,7 @@ el.replaceWith(d);
<a href="https://github.com/fluzzi/connpy"><img alt="" src="https://img.shields.io/badge/AI%20Core-LiteLLM-green?style=flat-square"></a> <a href="https://github.com/fluzzi/connpy"><img alt="" src="https://img.shields.io/badge/AI%20Core-LiteLLM-green?style=flat-square"></a>
<a href="https://modelcontextprotocol.io"><img alt="" src="https://img.shields.io/badge/MCP-compatible-orange?style=flat-square"></a> <a href="https://modelcontextprotocol.io"><img alt="" src="https://img.shields.io/badge/MCP-compatible-orange?style=flat-square"></a>
<a href="https://github.com/fluzzi/connpy/blob/main/LICENSE"><img alt="" src="https://img.shields.io/pypi/l/connpy.svg?style=flat-square"></a></p> <a href="https://github.com/fluzzi/connpy/blob/main/LICENSE"><img alt="" src="https://img.shields.io/pypi/l/connpy.svg?style=flat-square"></a></p>
<p><strong>Connpy</strong> is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for <strong>SSH, SFTP, Telnet, kubectl, Docker pods, and AWS SSM</strong>.</p> <p><strong>Connpy</strong> is a powerful Connection Manager and Network Automation Platform for Linux, Mac, and Docker. It provides a unified interface for <strong>SSH, SFTP, Mosh, Telnet, kubectl, Docker pods, and AWS SSM</strong>.</p>
<p>The v6 release introduces a comprehensive <strong>AI Copilot</strong> and <strong>AI Playbook Engine</strong>, transforming your terminal into an interactive network assistant that understands your device outputs, configures parameters safely, and runs simulations.</p> <p>The v6 release introduces a comprehensive <strong>AI Copilot</strong> and <strong>AI Playbook Engine</strong>, transforming your terminal into an interactive network assistant that understands your device outputs, configures parameters safely, and runs simulations.</p>
<hr> <hr>
<h2 id="1-ai-system">1. 🤖 AI System</h2> <h2 id="1-ai-system">1. 🤖 AI System</h2>
@@ -136,9 +136,10 @@ tags: { &quot;os&quot;: &quot;cisco_ios&quot;, &quot;prompt&quot;: &quot;.*#&quo
</code></pre> </code></pre>
<hr> <hr>
<h2 id="4-protocols-connection-features">4. 🔌 Protocols &amp; Connection Features</h2> <h2 id="4-protocols-connection-features">4. 🔌 Protocols &amp; Connection Features</h2>
<h3 id="4a-ssh-sftp-telnet-kubectl-docker-aws-ssm">4a. SSH / SFTP / Telnet / kubectl / Docker / AWS SSM</h3> <h3 id="4a-ssh-sftp-mosh-telnet-kubectl-docker-aws-ssm">4a. SSH / SFTP / Mosh / Telnet / kubectl / Docker / AWS SSM</h3>
<p>Connect to various architectures using native protocols: <p>Connect to various architectures using native protocols:
* <strong>SSH / Telnet</strong>: Standard CLI protocols. * <strong>SSH / Telnet</strong>: Standard CLI protocols.
* <strong>Mosh</strong>: Mobile Shell with roaming and local echo support.
* <strong>SFTP</strong>: Transfer files securely (<code>conn --sftp node</code>). * <strong>SFTP</strong>: Transfer files securely (<code>conn --sftp node</code>).
* <strong>Docker</strong>: Connect directly to local container names (host set to container name/ID). * <strong>Docker</strong>: Connect directly to local container names (host set to container name/ID).
* <strong>Kubernetes (kubectl)</strong>: Connect to pods (namespace customizable via options). * <strong>Kubernetes (kubectl)</strong>: Connect to pods (namespace customizable via options).
@@ -1715,7 +1716,7 @@ class node:
- port (str): Port to connect to node, default 22 for ssh and 23 - port (str): Port to connect to node, default 22 for ssh and 23
for telnet. for telnet.
- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh. - protocol (str): Select ssh, mosh, telnet, kubectl, docker or ssm. Default is ssh.
- user (str): Username to of the node. - user (str): Username to of the node.
@@ -1751,6 +1752,7 @@ class node:
setattr(self,key,&#34;ssh&#34;) setattr(self,key,&#34;ssh&#34;)
else: else:
setattr(self,key,attr[key]) setattr(self,key,attr[key])
self._orig_protocol = self.protocol
if isinstance(password,list): if isinstance(password,list):
self.password = [] self.password = []
for i, s in enumerate(password): for i, s in enumerate(password):
@@ -1827,6 +1829,11 @@ class node:
jh = config.getitem(jumphost_name) jh = config.getitem(jumphost_name)
jh = self._resolve_jumphost_data(jh, config) jh = self._resolve_jumphost_data(jh, config)
if jh[&#34;protocol&#34;] == &#34;mosh&#34;:
raise ValueError(
f&#34;Jumphost &#39;{jumphost_name}&#39; uses protocol &#39;mosh&#39; which cannot be used as a jumphost.&#34;
)
passwords = [] passwords = []
inner_proxy_opt = &#34;&#34; inner_proxy_opt = &#34;&#34;
@@ -2542,12 +2549,14 @@ class node:
str: Output of the commands you ran on the node. str: Output of the commands you ran on the node.
&#39;&#39;&#39; &#39;&#39;&#39;
connect = self._connect(timeout = timeout, logger = logger) force_ssh = (self.protocol == &#34;mosh&#34;)
connect = self._connect(timeout=timeout, logger=logger, force_ssh=force_ssh)
now = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H%M%S&#39;) now = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H%M%S&#39;)
if connect == True: if connect == True:
if logger: if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34; effective_protocol = &#34;ssh&#34; if force_ssh else self.protocol
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;) port_str = f&#34;:{self.port}&#34; if self.port and effective_protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {effective_protocol}&#34;)
if &#34;prompt&#34; in self.tags: if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;] prompt = self.tags[&#34;prompt&#34;]
@@ -2659,11 +2668,13 @@ class node:
&#39;&#39;&#39; &#39;&#39;&#39;
now = datetime.datetime.now().strftime(&#34;%Y-%m-%d_%H-%M-%S&#34;) now = datetime.datetime.now().strftime(&#34;%Y-%m-%d_%H-%M-%S&#34;)
connect = self._connect(timeout = timeout, logger = logger) force_ssh = (self.protocol == &#34;mosh&#34;)
connect = self._connect(timeout=timeout, logger=logger, force_ssh=force_ssh)
if connect == True: if connect == True:
if logger: if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34; effective_protocol = &#34;ssh&#34; if force_ssh else self.protocol
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;) port_str = f&#34;:{self.port}&#34; if self.port and effective_protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {effective_protocol}&#34;)
if &#34;prompt&#34; in self.tags: if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;] prompt = self.tags[&#34;prompt&#34;]
@@ -2755,16 +2766,45 @@ class node:
return connect return connect
@MethodHook @MethodHook
def _generate_ssh_sftp_cmd(self): def _generate_ssh_sftp_cmd(self, force_ssh=False):
cmd = self.protocol is_from_mosh = getattr(self, &#34;_orig_protocol&#34;, &#34;&#34;) == &#34;mosh&#34;
if self.port: if is_from_mosh:
if self.protocol == &#34;ssh&#34;: if str(self.host).startswith(&#34;-&#34;):
cmd += &#34; -p &#34; + self.port raise ValueError(&#34;Host cannot start with &#39;-&#39;&#34;)
elif self.protocol == &#34;sftp&#34;: if self.user and str(self.user).startswith(&#34;-&#34;):
cmd += &#34; -P &#34; + self.port raise ValueError(&#34;User cannot start with &#39;-&#39;&#34;)
if self.options:
opts = self.options proto = &#34;ssh&#34; if force_ssh else self.protocol
if self.protocol == &#34;sftp&#34;: cmd = proto
if self.port != &#34;&#34; and self.port is not None:
if is_from_mosh:
port_s = str(self.port).strip()
if port_s:
if not re.fullmatch(r&#34;^\d+$&#34;, port_s) or not (1 &lt;= int(port_s) &lt;= 65535):
raise ValueError(f&#34;Invalid TCP SSH port &#39;{self.port}&#39;&#34;)
cmd += (&#34; -p &#34; if proto == &#34;ssh&#34; else &#34; -P &#34;) + port_s
else:
if proto == &#34;ssh&#34;:
cmd += &#34; -p &#34; + str(self.port)
elif proto == &#34;sftp&#34;:
cmd += &#34; -P &#34; + str(self.port)
if is_from_mosh:
raw_opts = self.tags.get(&#34;mosh_ssh_options&#34;, &#34;&#34;) if isinstance(self.tags, dict) else &#34;&#34;
if raw_opts:
ssh_opts = str(raw_opts).strip()
if re.search(r&#39;(?:LocalCommand|ProxyCommand)&#39;, ssh_opts, re.IGNORECASE):
raise ValueError(&#34;mosh_ssh_options cannot contain LocalCommand or ProxyCommand&#34;)
try:
shlex.split(ssh_opts)
except ValueError as exc:
raise ValueError(&#34;Invalid mosh_ssh_options: unbalanced quotes&#34;) from exc
else:
raw_opts = self.options
if raw_opts:
opts = str(raw_opts).strip()
if proto == &#34;sftp&#34;:
# Strip SSH-only flags that sftp doesn&#39;t support # Strip SSH-only flags that sftp doesn&#39;t support
opts = re.sub(r&#39;(?&lt;!\S)-[XxtTAaNf]\b&#39;, &#39;&#39;, opts).strip() opts = re.sub(r&#39;(?&lt;!\S)-[XxtTAaNf]\b&#39;, &#39;&#39;, opts).strip()
if opts: if opts:
@@ -2775,6 +2815,73 @@ class node:
cmd += f&#34; {user_host}&#34; cmd += f&#34; {user_host}&#34;
return cmd return cmd
@MethodHook
def _generate_mosh_cmd(self):
if str(self.host).startswith(&#34;-&#34;):
raise ValueError(&#34;Host cannot start with &#39;-&#39;&#34;)
if self.user and str(self.user).startswith(&#34;-&#34;):
raise ValueError(&#34;User cannot start with &#39;-&#39;&#34;)
if not self.host or re.search(r&#39;[\s;|&amp;$`&gt;&lt;&#34;\&#39;\\]&#39;, str(self.host)):
raise ValueError(f&#34;Invalid characters in host: &#39;{self.host}&#39;&#34;)
if self.user and re.search(r&#39;[\s;|&amp;$`&gt;&lt;&#34;\&#39;\\]&#39;, str(self.user)):
raise ValueError(f&#34;Invalid characters in user: &#39;{self.user}&#39;&#34;)
cmd_parts = [&#34;mosh&#34;]
if isinstance(self.tags, dict):
if self.tags.get(&#34;mosh_server&#34;):
server_bin = str(self.tags[&#34;mosh_server&#34;]).strip()
if server_bin:
cmd_parts.append(f&#34;--server={shlex.quote(server_bin)}&#34;)
if self.tags.get(&#34;mosh_udp_port&#34;):
udp_port = str(self.tags[&#34;mosh_udp_port&#34;]).strip()
if udp_port:
if not re.match(r&#34;^\d+(:\d+)?$&#34;, udp_port):
raise ValueError(
f&#34;Invalid mosh_udp_port &#39;{udp_port}&#39;: must be PORT or PORT1:PORT2&#34;
)
cmd_parts.append(f&#34;-p {shlex.quote(udp_port)}&#34;)
ssh_parts = [&#34;ssh&#34;]
if self.port != &#34;&#34; and self.port is not None:
port_s = str(self.port).strip()
if port_s:
if not re.fullmatch(r&#34;^\d+$&#34;, port_s) or not (1 &lt;= int(port_s) &lt;= 65535):
raise ValueError(f&#34;Invalid TCP SSH port &#39;{self.port}&#39;&#34;)
ssh_parts.append(f&#34;-p {port_s}&#34;)
if isinstance(self.tags, dict) and self.tags.get(&#34;mosh_ssh_options&#34;):
ssh_opts = str(self.tags[&#34;mosh_ssh_options&#34;]).strip()
if ssh_opts:
if re.search(r&#39;(?:LocalCommand|ProxyCommand)&#39;, ssh_opts, re.IGNORECASE):
raise ValueError(&#34;mosh_ssh_options cannot contain LocalCommand or ProxyCommand&#34;)
try:
shlex.split(ssh_opts)
except ValueError as exc:
raise ValueError(&#34;Invalid mosh_ssh_options: unbalanced quotes&#34;) from exc
ssh_parts.append(ssh_opts)
if self.jumphost:
ssh_parts.append(self.jumphost)
if len(ssh_parts) &gt; 1:
raw_ssh = &#34; &#34;.join(ssh_parts)
cmd_parts.append(f&#34;--ssh={shlex.quote(raw_ssh)}&#34;)
if self.options:
opts = str(self.options).strip()
if opts:
if re.search(r&#39;--(?:ssh|server|client)(?:=|\s|$)&#39;, opts):
raise ValueError(&#34;Options cannot override --ssh, --server or --client for mosh&#34;)
if re.search(r&#39;(?:LocalCommand|ProxyCommand)&#39;, opts, re.IGNORECASE):
raise ValueError(&#34;Options cannot contain LocalCommand or ProxyCommand&#34;)
try:
shlex.split(opts)
except ValueError as exc:
raise ValueError(&#34;Invalid options: unbalanced quotes&#34;) from exc
cmd_parts.append(opts)
user_host = f&#34;{self.user}@{self.host}&#34; if self.user else self.host
cmd_parts.extend([&#34;--&#34;, user_host])
return &#34; &#34;.join(cmd_parts)
@MethodHook @MethodHook
def _generate_telnet_cmd(self): def _generate_telnet_cmd(self):
cmd = f&#34;telnet {self.host}&#34; cmd = f&#34;telnet {self.host}&#34;
@@ -2813,9 +2920,11 @@ class node:
@MethodHook @MethodHook
def _get_cmd(self): def _get_cmd(self, force_ssh=False):
if self.protocol in [&#34;ssh&#34;, &#34;sftp&#34;]: if force_ssh or self.protocol in [&#34;ssh&#34;, &#34;sftp&#34;]:
return self._generate_ssh_sftp_cmd() return self._generate_ssh_sftp_cmd(force_ssh=force_ssh)
elif self.protocol == &#34;mosh&#34;:
return self._generate_mosh_cmd()
elif self.protocol == &#34;telnet&#34;: elif self.protocol == &#34;telnet&#34;:
return self._generate_telnet_cmd() return self._generate_telnet_cmd()
elif self.protocol == &#34;kubectl&#34;: elif self.protocol == &#34;kubectl&#34;:
@@ -2830,25 +2939,56 @@ class node:
printer.error(f&#34;Invalid protocol: {self.protocol}&#34;) printer.error(f&#34;Invalid protocol: {self.protocol}&#34;)
sys.exit(1) sys.exit(1)
def _spawn_child(self, args, protocol=None):
if protocol is None:
protocol = getattr(self, &#34;protocol&#34;, &#34;&#34;)
env = None
if protocol == &#34;mosh&#34;:
env = os.environ.copy()
if not any(
&#34;utf-8&#34; in env.get(k, &#34;&#34;).lower() or &#34;utf8&#34; in env.get(k, &#34;&#34;).lower()
for k in (&#34;LC_ALL&#34;, &#34;LC_CTYPE&#34;, &#34;LANG&#34;)
):
env[&#34;LC_ALL&#34;] = &#34;C.UTF-8&#34;
env.setdefault(&#34;TERM&#34;, &#34;xterm-256color&#34;)
try:
if env is not None:
return pexpect.spawn(args[0], args[1:], env=env), None
return pexpect.spawn(args[0], args[1:]), None
except pexpect.exceptions.ExceptionPexpect as e:
return None, f&#34;Connection failed: {e}&#34;
@MethodHook @MethodHook
def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None): def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None, force_ssh=False):
if self.protocol == &#34;local&#34;: effective_protocol = &#34;ssh&#34; if force_ssh else self.protocol
if effective_protocol == &#34;mosh&#34;:
import shutil
if shutil.which(&#34;mosh&#34;) is None:
return &#34;Connection failed: mosh binary not found in PATH&#34;
timeout = max(timeout, 15)
if effective_protocol == &#34;local&#34;:
cmd = self._get_cmd() cmd = self._get_cmd()
args = shlex.split(cmd) args = shlex.split(cmd)
self.child = pexpect.spawn(args[0], args[1:], env=os.environ.copy()) child, err = self._spawn_child(args, protocol=effective_protocol)
if err:
return err
self.child = child
from pexpect import fdpexpect from pexpect import fdpexpect
self.raw_child = fdpexpect.fdspawn(self.child.child_fd) self.raw_child = fdpexpect.fdspawn(self.child.child_fd)
if self.logs != &#39;&#39;: if self.logs != &#39;&#39;:
self.logfile = self._logfile() self.logfile = self._logfile()
return True return True
cmd = self._get_cmd() cmd = self._get_cmd(force_ssh=force_ssh)
passwords = self._passtx(self.password) if self.password and any(self.password) else [] passwords = self._passtx(self.password) if self.password and any(self.password) else []
if self.logs != &#39;&#39;: if self.logs != &#39;&#39;:
self.logfile = self._logfile() self.logfile = self._logfile()
default_prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39; default_prompt = r&#39;&gt;$|#$|\$$|&gt;.$|#.$|\$.$&#39;
prompt = self.tags.get(&#34;prompt&#34;, default_prompt) if isinstance(self.tags, dict) else default_prompt prompt = self.tags.get(&#34;prompt&#34;, default_prompt) if isinstance(self.tags, dict) else default_prompt
password_prompt = &#39;[p|P]assword:|[u|U]sername:&#39; if self.protocol != &#39;telnet&#39; else &#39;[p|P]assword:&#39; password_prompt = &#39;[p|P]assword:|[u|U]sername:&#39; if effective_protocol != &#39;telnet&#39; else &#39;[p|P]assword:&#39;
prompt_unanchored = &#34;|&#34;.join([t[:-1] if t.endswith(&#34;$&#34;) else t for t in prompt.split(&#34;|&#34;)])
mosh_prompt = r&#34;(?:&#34; + prompt_unanchored + r&#34;)\s*(?:\[[0-9;?]*[a-zA-Z])*$&#34;
expects = { expects = {
&#34;ssh&#34;: [&#39;yes/no&#39;, &#39;refused&#39;, &#39;supported&#39;, &#39;Invalid|[u|U]sage: ssh&#39;, &#39;ssh-keygen.*\&#34;&#39;, &#39;timeout|timed.out&#39;, &#39;unavailable&#39;, &#39;closed&#39;, password_prompt, prompt, &#39;suspend&#39;, pexpect.EOF, pexpect.TIMEOUT, &#34;No route to host&#34;, &#34;resolve hostname&#34;, &#34;no matching&#34;, &#34;[b|B]ad (owner|permissions)&#34;], &#34;ssh&#34;: [&#39;yes/no&#39;, &#39;refused&#39;, &#39;supported&#39;, &#39;Invalid|[u|U]sage: ssh&#39;, &#39;ssh-keygen.*\&#34;&#39;, &#39;timeout|timed.out&#39;, &#39;unavailable&#39;, &#39;closed&#39;, password_prompt, prompt, &#39;suspend&#39;, pexpect.EOF, pexpect.TIMEOUT, &#34;No route to host&#34;, &#34;resolve hostname&#34;, &#34;no matching&#34;, &#34;[b|B]ad (owner|permissions)&#34;],
@@ -2858,6 +2998,28 @@ class node:
&#34;docker&#34;: [&#39;[u|U]sername:&#39;, &#39;Cannot&#39;, &#39;[E|e]rror&#39;, &#39;failed&#39;, &#39;not a docker command&#39;, &#39;unknown&#39;, &#39;unable to resolve&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF], &#34;docker&#34;: [&#39;[u|U]sername:&#39;, &#39;Cannot&#39;, &#39;[E|e]rror&#39;, &#39;failed&#39;, &#39;not a docker command&#39;, &#39;unknown&#39;, &#39;unable to resolve&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF],
&#34;ssm&#34;: [&#39;[u|U]sername:&#39;, &#39;Cannot&#39;, &#39;[E|e]rror&#39;, &#39;failed&#39;, &#39;SessionManagerPlugin&#39;, &#39;[u|U]nknown&#39;, &#39;unable to resolve&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF] &#34;ssm&#34;: [&#39;[u|U]sername:&#39;, &#39;Cannot&#39;, &#39;[E|e]rror&#39;, &#39;failed&#39;, &#39;SessionManagerPlugin&#39;, &#39;[u|U]nknown&#39;, &#39;unable to resolve&#39;, pexpect.TIMEOUT, password_prompt, prompt, pexpect.EOF]
} }
expects[&#34;mosh&#34;] = [
&#39;yes/no&#39;, # 0 (initial)
r&#39;(?:ssh: connect to host .* port .*: Connection refused|Connection refused)&#39;, # 1 (error)
r&#39;(?:ssh|mosh): .*supported&#39;, # 2 (error)
r&#39;(?:(?:ssh|mosh): (?:Invalid|usage)|Unknown option:)&#39;, # 3 (error)
&#39;ssh-keygen.*\&#34;&#39;, # 4 (error)
r&#39;(?:ssh: connect to host .* port .*: Connection timed out|mosh: .* timed out)&#39;, # 5 (error)
r&#39;(?:ssh|mosh): .*unavailable&#39;, # 6 (error)
r&#39;(?:Connection to .* closed|Connection closed by remote host)&#39;, # 7 (error)
password_prompt, # 8 (eof)
mosh_prompt, # 9 (eof)
&#39;suspend&#39;, # 10 (eof)
pexpect.EOF, # 11 (eof)
pexpect.TIMEOUT, # 12 (error)
&#34;No route to host&#34;, # 13 (error)
&#34;resolve hostname&#34;, # 14 (error)
r&#39;(?:ssh|mosh): .*no matching&#39;, # 15 (error)
&#34;[b|B]ad (owner|permissions)&#34;, # 16 (error)
&#34;mosh-server:.*not found|command not found&#34;, # 17 (error)
r&#34;(?:Did not find mosh server startup message|(?:mosh: )?Nothing received from server on UDP port \d+\.?|Nothing received from server)&#34;, # 18 (error)
&#34;needs a UTF-8 native locale to run|requires a UTF-8 locale|locale.*not available&#34;, # 19 (error)
]
error_indices = { error_indices = {
&#34;ssh&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16], &#34;ssh&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
@@ -2865,7 +3027,8 @@ class node:
&#34;telnet&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16], &#34;telnet&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
&#34;kubectl&#34;: [1, 2, 3, 4, 8], # Define error indices for kube &#34;kubectl&#34;: [1, 2, 3, 4, 8], # Define error indices for kube
&#34;docker&#34;: [1, 2, 3, 4, 5, 6, 7], # Define error indices for docker &#34;docker&#34;: [1, 2, 3, 4, 5, 6, 7], # Define error indices for docker
&#34;ssm&#34;: [1, 2, 3, 4, 5, 6, 7] &#34;ssm&#34;: [1, 2, 3, 4, 5, 6, 7],
&#34;mosh&#34;: [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16, 17, 18, 19]
} }
eof_indices = { eof_indices = {
@@ -2874,7 +3037,8 @@ class node:
&#34;telnet&#34;: [8, 9, 10, 11], &#34;telnet&#34;: [8, 9, 10, 11],
&#34;kubectl&#34;: [5, 6, 7], # Define eof indices for kube &#34;kubectl&#34;: [5, 6, 7], # Define eof indices for kube
&#34;docker&#34;: [8, 9, 10], # Define eof indices for docker &#34;docker&#34;: [8, 9, 10], # Define eof indices for docker
&#34;ssm&#34;: [8, 9, 10] &#34;ssm&#34;: [8, 9, 10],
&#34;mosh&#34;: [8, 9, 10, 11]
} }
initial_indices = { initial_indices = {
@@ -2883,13 +3047,17 @@ class node:
&#34;telnet&#34;: [0], &#34;telnet&#34;: [0],
&#34;kubectl&#34;: [0], # Define special indices for kube &#34;kubectl&#34;: [0], # Define special indices for kube
&#34;docker&#34;: [0], # Define special indices for docker &#34;docker&#34;: [0], # Define special indices for docker
&#34;ssm&#34;: [0] &#34;ssm&#34;: [0],
&#34;mosh&#34;: [0]
} }
attempts = 1 attempts = 1
handshake_progressed = False
while attempts &lt;= max_attempts: while attempts &lt;= max_attempts:
args = shlex.split(cmd) args = shlex.split(cmd)
child = pexpect.spawn(args[0], args[1:]) child, err = self._spawn_child(args, protocol=effective_protocol)
if err:
return err
if isinstance(self.tags, dict) and self.tags.get(&#34;console&#34;): if isinstance(self.tags, dict) and self.tags.get(&#34;console&#34;):
child.sendline() child.sendline()
if debug: if debug:
@@ -2903,33 +3071,58 @@ class node:
endloop = False endloop = False
for i in range(len(passwords) if passwords else 1): for i in range(len(passwords) if passwords else 1):
while True: while True:
results = child.expect(expects[self.protocol], timeout=timeout) results = child.expect(expects[effective_protocol], timeout=timeout)
results_value = expects[self.protocol][results] results_value = expects[effective_protocol][results]
if results in initial_indices[self.protocol]: if results in initial_indices[effective_protocol]:
if self.protocol in [&#34;ssh&#34;, &#34;sftp&#34;]: if effective_protocol in [&#34;ssh&#34;, &#34;sftp&#34;, &#34;mosh&#34;]:
child.sendline(&#39;yes&#39;) child.sendline(&#39;yes&#39;)
elif self.protocol in [&#34;telnet&#34;, &#34;kubectl&#34;, &#34;docker&#34;, &#34;ssm&#34;]: handshake_progressed = True
elif effective_protocol in [&#34;telnet&#34;, &#34;kubectl&#34;, &#34;docker&#34;, &#34;ssm&#34;]:
if self.user: if self.user:
child.sendline(self.user) child.sendline(self.user)
else: else:
self.missingtext = True self.missingtext = True
break break
elif results in error_indices[self.protocol]: elif results in error_indices[effective_protocol]:
try:
child.terminate() child.terminate()
if results_value == pexpect.TIMEOUT and attempts != max_attempts: except Exception:
pass
can_retry = (
results_value == pexpect.TIMEOUT
and attempts != max_attempts
and not (effective_protocol == &#34;mosh&#34; and handshake_progressed)
)
if can_retry:
attempts += 1 attempts += 1
endloop = True endloop = True
break break
else: else:
after = &#34;Connection timeout&#34; if results_value == pexpect.TIMEOUT else child.after.decode() def _to_str(val):
return f&#34;Connection failed code: {results}\n{child.before.decode().lstrip()}{after}{child.readline().decode()}&#34;.rstrip() if val is None:
return &#34;&#34;
if hasattr(val, &#34;decode&#34;):
return val.decode()
return str(val)
after = &#34;Connection timeout&#34; if results_value == pexpect.TIMEOUT else _to_str(child.after)
before = _to_str(child.before)
readline_val = _to_str(child.readline())
if effective_protocol == &#34;mosh&#34;:
after = self._logclean(after, True)
before = self._logclean(before, True)
readline_val = self._logclean(readline_val, True)
if effective_protocol == &#34;mosh&#34; and results == 18 and (&#34;Nothing received from server&#34; in after or &#34;Nothing received from server&#34; in before):
err_msg = after.strip() if &#34;Nothing received from server&#34; in after else before.strip()
return f&#34;Connection failed code: {results}\n{err_msg} — UDP traffic is blocked or unreachable. Verify firewall rules for UDP ports (60000-61000 or mosh_udp_port).&#34;
return f&#34;Connection failed code: {results}\n{before.lstrip()}{after}{readline_val}&#34;.rstrip()
elif results in eof_indices[self.protocol]: elif results in eof_indices[effective_protocol]:
if results_value == password_prompt: if results_value == password_prompt:
if passwords: if passwords:
child.sendline(passwords[i]) child.sendline(passwords[i])
handshake_progressed = True
else: else:
self.missingtext = True self.missingtext = True
break break
@@ -2990,7 +3183,7 @@ class node:
- port (str): Port to connect to node, default 22 for ssh and 23 - port (str): Port to connect to node, default 22 for ssh and 23
for telnet. for telnet.
- protocol (str): Select ssh, telnet, kubectl or docker. Default is ssh. - protocol (str): Select ssh, mosh, telnet, kubectl, docker or ssm. Default is ssh.
- user (str): Username to of the node. - user (str): Username to of the node.
@@ -3154,12 +3347,14 @@ def run(self, commands, vars = None,*, folder = &#39;&#39;, prompt = r&#39;&gt;$
str: Output of the commands you ran on the node. str: Output of the commands you ran on the node.
&#39;&#39;&#39; &#39;&#39;&#39;
connect = self._connect(timeout = timeout, logger = logger) force_ssh = (self.protocol == &#34;mosh&#34;)
connect = self._connect(timeout=timeout, logger=logger, force_ssh=force_ssh)
now = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H%M%S&#39;) now = datetime.datetime.now().strftime(&#39;%Y-%m-%d_%H%M%S&#39;)
if connect == True: if connect == True:
if logger: if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34; effective_protocol = &#34;ssh&#34; if force_ssh else self.protocol
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;) port_str = f&#34;:{self.port}&#34; if self.port and effective_protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {effective_protocol}&#34;)
if &#34;prompt&#34; in self.tags: if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;] prompt = self.tags[&#34;prompt&#34;]
@@ -3312,11 +3507,13 @@ def test(self, commands, expected, vars = None,*, folder = &#39;&#39;, prompt =
&#39;&#39;&#39; &#39;&#39;&#39;
now = datetime.datetime.now().strftime(&#34;%Y-%m-%d_%H-%M-%S&#34;) now = datetime.datetime.now().strftime(&#34;%Y-%m-%d_%H-%M-%S&#34;)
connect = self._connect(timeout = timeout, logger = logger) force_ssh = (self.protocol == &#34;mosh&#34;)
connect = self._connect(timeout=timeout, logger=logger, force_ssh=force_ssh)
if connect == True: if connect == True:
if logger: if logger:
port_str = f&#34;:{self.port}&#34; if self.port and self.protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34; effective_protocol = &#34;ssh&#34; if force_ssh else self.protocol
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}&#34;) port_str = f&#34;:{self.port}&#34; if self.port and effective_protocol not in [&#34;ssm&#34;, &#34;kubectl&#34;, &#34;docker&#34;] else &#34;&#34;
logger(&#34;success&#34;, f&#34;Connected to {self.unique} at {self.host}{port_str} via: {effective_protocol}&#34;)
if &#34;prompt&#34; in self.tags: if &#34;prompt&#34; in self.tags:
prompt = self.tags[&#34;prompt&#34;] prompt = self.tags[&#34;prompt&#34;]
@@ -4112,7 +4309,7 @@ def test(self, commands, expected, vars = None,*, folder = None, prompt = None,
<nav id="sidebar"> <nav id="sidebar">
<div class="toc"> <div class="toc">
<ul> <ul>
<li><a href="#connpy-v630">Connpy (v6.3.0)</a><ul> <li><a href="#connpy-v640b1">Connpy (v6.4.0b1)</a><ul>
<li><a href="#1-ai-system">1. 🤖 AI System</a><ul> <li><a href="#1-ai-system">1. 🤖 AI System</a><ul>
<li><a href="#1a-terminal-copilot-ctrlspace">1a. Terminal Copilot (Ctrl+Space)</a></li> <li><a href="#1a-terminal-copilot-ctrlspace">1a. Terminal Copilot (Ctrl+Space)</a></li>
<li><a href="#1b-ai-chat-conn-ai">1b. AI Chat (conn ai)</a></li> <li><a href="#1b-ai-chat-conn-ai">1b. AI Chat (conn ai)</a></li>
@@ -4135,7 +4332,7 @@ def test(self, commands, expected, vars = None,*, folder = None, prompt = None,
</ul> </ul>
</li> </li>
<li><a href="#4-protocols-connection-features">4. 🔌 Protocols &amp; Connection Features</a><ul> <li><a href="#4-protocols-connection-features">4. 🔌 Protocols &amp; Connection Features</a><ul>
<li><a href="#4a-ssh-sftp-telnet-kubectl-docker-aws-ssm">4a. SSH / SFTP / Telnet / kubectl / Docker / AWS SSM</a></li> <li><a href="#4a-ssh-sftp-mosh-telnet-kubectl-docker-aws-ssm">4a. SSH / SFTP / Mosh / Telnet / kubectl / Docker / AWS SSM</a></li>
<li><a href="#4b-jumphosts">4b. Jumphosts</a></li> <li><a href="#4b-jumphosts">4b. Jumphosts</a></li>
<li><a href="#4c-debug-mode-keepalive-logging">4c. Debug Mode, Keepalive, Logging</a></li> <li><a href="#4c-debug-mode-keepalive-logging">4c. Debug Mode, Keepalive, Logging</a></li>
</ul> </ul>