diff --git a/README.md b/README.md index ed61f45..5a263c0 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@
-# Connpy (v6.3.0) +# Connpy (v6.4.0b1) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) @@ -13,7 +13,7 @@ [](https://modelcontextprotocol.io) [](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. @@ -134,9 +134,10 @@ tags: { "os": "cisco_ios", "prompt": ".*#", "screen_length_command": "terminal l ## 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: * **SSH / Telnet**: Standard CLI protocols. +* **Mosh**: Mobile Shell with roaming and local echo support. * **SFTP**: Transfer files securely (`conn --sftp node`). * **Docker**: Connect directly to local container names (host set to container name/ID). * **Kubernetes (kubectl)**: Connect to pods (namespace customizable via options). diff --git a/connpy/__init__.py b/connpy/__init__.py index 41b5b80..ff995c8 100644 --- a/connpy/__init__.py +++ b/connpy/__init__.py @@ -5,7 +5,7 @@ -# Connpy (v6.3.0) +# Connpy (v6.4.0b1) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) [](https://pypi.org/pypi/connpy/) diff --git a/connpy/_version.py b/connpy/_version.py index 833eacf..5cd848d 100644 --- a/connpy/_version.py +++ b/connpy/_version.py @@ -1 +1 @@ -__version__ = "6.3.0" +__version__ = "6.4.0b1" diff --git a/docs/connpy/cli/help_text.html b/docs/connpy/cli/help_text.html index 1440196..eaa2cc0 100644 --- a/docs/connpy/cli/help_text.html +++ b/docs/connpy/cli/help_text.html @@ -91,6 +91,7 @@ Here are some important instructions and tips for configuring your new node: 2. **Available Protocols and Apps**: - ssh + - mosh (requires remote mosh-server and UDP ports 60000-61000 open; --sftp uses SSH TCP) - telnet - kubectl (`kubectl 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`. - `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`). + - `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": return ''' diff --git a/docs/connpy/cli/validators.html b/docs/connpy/cli/validators.html index c797b53..1c7c41f 100644 --- a/docs/connpy/cli/validators.html +++ b/docs/connpy/cli/validators.html @@ -67,14 +67,14 @@ el.replaceWith(d); _raise_val_err("Profile {} don't exist".format(current)) 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): - _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 - 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): - _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[1:] not in self.app.profiles: _raise_val_err("Profile {} don't exist".format(current)) @@ -389,16 +389,16 @@ el.replaceWith(d);
-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$|^$)')
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):
- _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
-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$|^$|^@.+$)')
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):
- _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[1:] not in self.app.profiles:
_raise_val_err("Profile {} don't exist".format(current))
diff --git a/docs/connpy/grpc_layer/server.html b/docs/connpy/grpc_layer/server.html
index 162c657..cd55201 100644
--- a/docs/connpy/grpc_layer/server.html
+++ b/docs/connpy/grpc_layer/server.html
@@ -1467,6 +1467,9 @@ interceptor chooses to service this RPC, or None otherwise.
setattr(n, attr, params[attr])
if "tags" in params:
n.tags = params["tags"]
+ n._orig_protocol = n.protocol
+ if sftp:
+ n.protocol = "sftp"
else:
try:
node_data = user_config.getitem(unique_id, extract=False)
diff --git a/docs/connpy/index.html b/docs/connpy/index.html
index 6b2c44d..95dbe58 100644
--- a/docs/connpy/index.html
+++ b/docs/connpy/index.html
@@ -41,7 +41,7 @@ el.replaceWith(d);
-Connpy (v6.3.0)
+Connpy (v6.4.0b1)
@@ -50,7 +50,7 @@ el.replaceWith(d);

-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.
1. 🤖 AI System
@@ -136,9 +136,10 @@ tags: { "os": "cisco_ios", "prompt": ".*#&quo
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:
* SSH / Telnet: Standard CLI protocols.
+* Mosh: Mobile Shell with roaming and local echo support.
* SFTP: Transfer files securely (conn --sftp node).
* Docker: Connect directly to local container names (host set to container name/ID).
* Kubernetes (kubectl): 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
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.
@@ -1751,6 +1752,7 @@ class node:
setattr(self,key,"ssh")
else:
setattr(self,key,attr[key])
+ self._orig_protocol = self.protocol
if isinstance(password,list):
self.password = []
for i, s in enumerate(password):
@@ -1827,6 +1829,11 @@ class node:
jh = config.getitem(jumphost_name)
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 = []
inner_proxy_opt = ""
@@ -2542,12 +2549,14 @@ class 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')
if connect == True:
if logger:
- port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
- logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}")
+ effective_protocol = "ssh" if force_ssh else 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:
prompt = self.tags["prompt"]
@@ -2659,11 +2668,13 @@ class node:
'''
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 logger:
- port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
- logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}")
+ effective_protocol = "ssh" if force_ssh else 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:
prompt = self.tags["prompt"]
@@ -2755,16 +2766,45 @@ class node:
return connect
@MethodHook
- def _generate_ssh_sftp_cmd(self):
- cmd = self.protocol
- if self.port:
- if self.protocol == "ssh":
- cmd += " -p " + self.port
- elif self.protocol == "sftp":
- cmd += " -P " + self.port
- if self.options:
- opts = self.options
- if self.protocol == "sftp":
+ def _generate_ssh_sftp_cmd(self, force_ssh=False):
+ is_from_mosh = getattr(self, "_orig_protocol", "") == "mosh"
+ if is_from_mosh:
+ 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 '-'")
+
+ proto = "ssh" if force_ssh else self.protocol
+ 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
opts = re.sub(r'(?<!\S)-[XxtTAaNf]\b', '', opts).strip()
if opts:
@@ -2775,6 +2815,73 @@ class node:
cmd += f" {user_host}"
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
def _generate_telnet_cmd(self):
cmd = f"telnet {self.host}"
@@ -2813,9 +2920,11 @@ class node:
@MethodHook
- def _get_cmd(self):
- if self.protocol in ["ssh", "sftp"]:
- return self._generate_ssh_sftp_cmd()
+ def _get_cmd(self, force_ssh=False):
+ if force_ssh or self.protocol in ["ssh", "sftp"]:
+ return self._generate_ssh_sftp_cmd(force_ssh=force_ssh)
+ elif self.protocol == "mosh":
+ return self._generate_mosh_cmd()
elif self.protocol == "telnet":
return self._generate_telnet_cmd()
elif self.protocol == "kubectl":
@@ -2830,25 +2939,56 @@ class node:
printer.error(f"Invalid protocol: {self.protocol}")
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
- def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None):
- if self.protocol == "local":
+ def _connect(self, debug=False, timeout=10, max_attempts=3, logger=None, force_ssh=False):
+ 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()
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
self.raw_child = fdpexpect.fdspawn(self.child.child_fd)
if self.logs != '':
self.logfile = self._logfile()
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 []
if self.logs != '':
self.logfile = self._logfile()
default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$'
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 = {
"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)"],
@@ -2858,6 +2998,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],
"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 = {
"ssh": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
@@ -2865,7 +3027,8 @@ class node:
"telnet": [1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16],
"kubectl": [1, 2, 3, 4, 8], # Define error indices for kube
"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 = {
@@ -2874,7 +3037,8 @@ class node:
"telnet": [8, 9, 10, 11],
"kubectl": [5, 6, 7], # Define eof indices for kube
"docker": [8, 9, 10], # Define eof indices for docker
- "ssm": [8, 9, 10]
+ "ssm": [8, 9, 10],
+ "mosh": [8, 9, 10, 11]
}
initial_indices = {
@@ -2883,13 +3047,17 @@ class node:
"telnet": [0],
"kubectl": [0], # Define special indices for kube
"docker": [0], # Define special indices for docker
- "ssm": [0]
+ "ssm": [0],
+ "mosh": [0]
}
attempts = 1
+ handshake_progressed = False
while attempts <= max_attempts:
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"):
child.sendline()
if debug:
@@ -2903,33 +3071,58 @@ class node:
endloop = False
for i in range(len(passwords) if passwords else 1):
while True:
- results = child.expect(expects[self.protocol], timeout=timeout)
- results_value = expects[self.protocol][results]
+ results = child.expect(expects[effective_protocol], timeout=timeout)
+ results_value = expects[effective_protocol][results]
- if results in initial_indices[self.protocol]:
- if self.protocol in ["ssh", "sftp"]:
+ if results in initial_indices[effective_protocol]:
+ if effective_protocol in ["ssh", "sftp", "mosh"]:
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:
child.sendline(self.user)
else:
self.missingtext = True
break
- elif results in error_indices[self.protocol]:
- child.terminate()
- if results_value == pexpect.TIMEOUT and attempts != max_attempts:
+ elif results in error_indices[effective_protocol]:
+ try:
+ child.terminate()
+ 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
endloop = True
break
else:
- after = "Connection timeout" if results_value == pexpect.TIMEOUT else child.after.decode()
- return f"Connection failed code: {results}\n{child.before.decode().lstrip()}{after}{child.readline().decode()}".rstrip()
+ def _to_str(val):
+ 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 passwords:
child.sendline(passwords[i])
+ handshake_progressed = True
else:
self.missingtext = True
break
@@ -2990,7 +3183,7 @@ class node:
- port (str): Port to connect to node, default 22 for ssh and 23
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.
@@ -3154,12 +3347,14 @@ def run(self, commands, vars = None,*, folder = '', prompt = r'>$
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')
if connect == True:
if logger:
- port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
- logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}")
+ effective_protocol = "ssh" if force_ssh else 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:
prompt = self.tags["prompt"]
@@ -3312,11 +3507,13 @@ def test(self, commands, expected, vars = None,*, folder = '', prompt =
'''
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 logger:
- port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
- logger("success", f"Connected to {self.unique} at {self.host}{port_str} via: {self.protocol}")
+ effective_protocol = "ssh" if force_ssh else 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:
prompt = self.tags["prompt"]
@@ -4112,7 +4309,7 @@ def test(self, commands, expected, vars = None,*, folder = None, prompt = None,