feat: completed TASK-MOSH-01 - Soporte Nativo para el Protocolo Mosh

This commit is contained in:
fluzzi32 committed 2026-10-19 18:33:02 -03:00
1 parent 01690c815f
commit d8a4357826
8 files changed
+300 -41

No files matched your search

+3 -2
View File
@@ -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).
+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))
+204 -35
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,7 +916,7 @@ 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) connect = self._connect(timeout=timeout, logger=logger, force_ssh=(self.protocol == "mosh"))
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:
@@ -1027,7 +1033,7 @@ 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) connect = self._connect(timeout=timeout, logger=logger, force_ssh=(self.protocol == "mosh"))
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 "" port_str = f":{self.port}" if self.port and self.protocol not in ["ssm", "kubectl", "docker"] else ""
@@ -1123,16 +1129,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 +1178,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)', 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 +1283,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 +1302,49 @@ 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):
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:
return pexpect.spawn(args[0], args[1:], env=env), 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)
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:'
mosh_prompt = r"(?:(?:" + prompt + r")(?:\x1b\[[0-9;?]*[a-zA-Z])*|\x1b\[\?1049h.*)$"
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 +1354,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)
"Did not find mosh server startup message|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 +1383,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 +1393,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 +1403,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)
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 +1427,46 @@ 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]:
child.terminate() child.terminate()
if results_value == pexpect.TIMEOUT and attempts != max_attempts: 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)
return f"Connection failed code: {results}\n{_to_str(child.before).lstrip()}{after}{_to_str(child.readline())}".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")
+42
View File
@@ -288,3 +288,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(populated_config):
"""Test NodeServiceServicer.interact_node with sftp=True preserves _orig_protocol='mosh'."""
servicer = server.NodeServicer(populated_config)
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
)
with patch("connpy.grpc_layer.server.node") as mock_node_cls:
from connpy.core import node as real_node
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
+27
View File
@@ -64,3 +64,30 @@ 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
from connpy.core import node
service = NodeService(populated_config)
populated_config.connections.append({
"id": "mosh1",
"host": "10.0.0.99",
"user": "admin",
"protocol": "mosh",
"type": "connection"
})
with patch.object(node, "interact", autospec=True) as mock_interact:
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"