| 1 |
# Derived from ansible/plugins/connection/proxmox_pct_remote.py (c) 2024 Nils Stein (@mietzen) <[email protected]> |
| 2 |
# Derived from ansible/plugins/connection/paramiko_ssh.py (c) 2012, Michael DeHaan <[email protected]> |
| 3 |
# Copyright (c) 2025 Rui Lopes (@rgl) <ruilopes.com> |
| 4 |
# Copyright (c) 2025 Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
author: Rui Lopes (@rgl) <ruilopes.com> |
| 12 |
name: wsl |
| 13 |
short_description: Run tasks in WSL distribution using wsl.exe CLI using SSH |
| 14 |
requirements: |
| 15 |
- paramiko |
| 16 |
description: |
| 17 |
- Run commands or put/fetch files to an existing WSL distribution using wsl.exe CLI using SSH. |
| 18 |
- Uses the Python SSH implementation (Paramiko) to connect to the WSL host. |
| 19 |
version_added: "10.6.0" |
| 20 |
options: |
| 21 |
remote_addr: |
| 22 |
description: |
| 23 |
- Address of the remote target. |
| 24 |
default: inventory_hostname |
| 25 |
type: string |
| 26 |
vars: |
| 27 |
- name: inventory_hostname |
| 28 |
- name: ansible_host |
| 29 |
- name: ansible_ssh_host |
| 30 |
- name: ansible_paramiko_host |
| 31 |
port: |
| 32 |
description: Remote port to connect to. |
| 33 |
type: int |
| 34 |
default: 22 |
| 35 |
ini: |
| 36 |
- section: defaults |
| 37 |
key: remote_port |
| 38 |
- section: paramiko_connection |
| 39 |
key: remote_port |
| 40 |
env: |
| 41 |
- name: ANSIBLE_REMOTE_PORT |
| 42 |
- name: ANSIBLE_REMOTE_PARAMIKO_PORT |
| 43 |
vars: |
| 44 |
- name: ansible_port |
| 45 |
- name: ansible_ssh_port |
| 46 |
- name: ansible_paramiko_port |
| 47 |
keyword: |
| 48 |
- name: port |
| 49 |
remote_user: |
| 50 |
description: |
| 51 |
- User to login/authenticate as. |
| 52 |
- Can be set from the CLI with the C(--user) or C(-u) options. |
| 53 |
type: string |
| 54 |
vars: |
| 55 |
- name: ansible_user |
| 56 |
- name: ansible_ssh_user |
| 57 |
- name: ansible_paramiko_user |
| 58 |
env: |
| 59 |
- name: ANSIBLE_REMOTE_USER |
| 60 |
- name: ANSIBLE_PARAMIKO_REMOTE_USER |
| 61 |
ini: |
| 62 |
- section: defaults |
| 63 |
key: remote_user |
| 64 |
- section: paramiko_connection |
| 65 |
key: remote_user |
| 66 |
keyword: |
| 67 |
- name: remote_user |
| 68 |
password: |
| 69 |
description: |
| 70 |
- Secret used to either login the SSH server or as a passphrase for SSH keys that require it. |
| 71 |
- Can be set from the CLI with the C(--ask-pass) option. |
| 72 |
type: string |
| 73 |
vars: |
| 74 |
- name: ansible_password |
| 75 |
- name: ansible_ssh_pass |
| 76 |
- name: ansible_ssh_password |
| 77 |
- name: ansible_paramiko_pass |
| 78 |
- name: ansible_paramiko_password |
| 79 |
use_rsa_sha2_algorithms: |
| 80 |
description: |
| 81 |
- Whether or not to enable RSA SHA2 algorithms for pubkeys and hostkeys. |
| 82 |
- On paramiko versions older than 2.9, this only affects hostkeys. |
| 83 |
- For behavior matching paramiko<2.9 set this to V(false). |
| 84 |
vars: |
| 85 |
- name: ansible_paramiko_use_rsa_sha2_algorithms |
| 86 |
ini: |
| 87 |
- {key: use_rsa_sha2_algorithms, section: paramiko_connection} |
| 88 |
env: |
| 89 |
- {name: ANSIBLE_PARAMIKO_USE_RSA_SHA2_ALGORITHMS} |
| 90 |
default: true |
| 91 |
type: boolean |
| 92 |
host_key_auto_add: |
| 93 |
description: "Automatically add host keys to C(~/.ssh/known_hosts)." |
| 94 |
env: |
| 95 |
- name: ANSIBLE_PARAMIKO_HOST_KEY_AUTO_ADD |
| 96 |
ini: |
| 97 |
- key: host_key_auto_add |
| 98 |
section: paramiko_connection |
| 99 |
type: boolean |
| 100 |
look_for_keys: |
| 101 |
default: true |
| 102 |
description: "Set to V(false) to disable searching for private key files in C(~/.ssh/)." |
| 103 |
env: |
| 104 |
- name: ANSIBLE_PARAMIKO_LOOK_FOR_KEYS |
| 105 |
ini: |
| 106 |
- {key: look_for_keys, section: paramiko_connection} |
| 107 |
type: boolean |
| 108 |
proxy_command: |
| 109 |
default: "" |
| 110 |
description: |
| 111 |
- Proxy information for running the connection through a jumphost. |
| 112 |
- This option is supported by paramiko version 1.9.0 or newer. |
| 113 |
type: string |
| 114 |
env: |
| 115 |
- name: ANSIBLE_PARAMIKO_PROXY_COMMAND |
| 116 |
ini: |
| 117 |
- {key: proxy_command, section: paramiko_connection} |
| 118 |
vars: |
| 119 |
- name: ansible_paramiko_proxy_command |
| 120 |
record_host_keys: |
| 121 |
default: true |
| 122 |
description: "Save the host keys to a file." |
| 123 |
env: |
| 124 |
- name: ANSIBLE_PARAMIKO_RECORD_HOST_KEYS |
| 125 |
ini: |
| 126 |
- section: paramiko_connection |
| 127 |
key: record_host_keys |
| 128 |
type: boolean |
| 129 |
host_key_checking: |
| 130 |
description: "Set this to V(false) if you want to avoid host key checking by the underlying tools Ansible uses to connect |
| 131 |
to the host." |
| 132 |
type: boolean |
| 133 |
default: true |
| 134 |
env: |
| 135 |
- name: ANSIBLE_HOST_KEY_CHECKING |
| 136 |
- name: ANSIBLE_SSH_HOST_KEY_CHECKING |
| 137 |
- name: ANSIBLE_PARAMIKO_HOST_KEY_CHECKING |
| 138 |
ini: |
| 139 |
- section: defaults |
| 140 |
key: host_key_checking |
| 141 |
- section: paramiko_connection |
| 142 |
key: host_key_checking |
| 143 |
vars: |
| 144 |
- name: ansible_host_key_checking |
| 145 |
- name: ansible_ssh_host_key_checking |
| 146 |
- name: ansible_paramiko_host_key_checking |
| 147 |
use_persistent_connections: |
| 148 |
description: "Toggles the use of persistence for connections." |
| 149 |
type: boolean |
| 150 |
default: false |
| 151 |
env: |
| 152 |
- name: ANSIBLE_USE_PERSISTENT_CONNECTIONS |
| 153 |
ini: |
| 154 |
- section: defaults |
| 155 |
key: use_persistent_connections |
| 156 |
banner_timeout: |
| 157 |
type: float |
| 158 |
default: 30 |
| 159 |
description: |
| 160 |
- Configures, in seconds, the amount of time to wait for the SSH banner to be presented. |
| 161 |
- This option is supported by paramiko version 1.15.0 or newer. |
| 162 |
ini: |
| 163 |
- section: paramiko_connection |
| 164 |
key: banner_timeout |
| 165 |
env: |
| 166 |
- name: ANSIBLE_PARAMIKO_BANNER_TIMEOUT |
| 167 |
timeout: |
| 168 |
type: int |
| 169 |
default: 10 |
| 170 |
description: |
| 171 |
- Number of seconds until the plugin gives up on failing to establish a TCP connection. |
| 172 |
- This option is supported by paramiko version 2.2.0 or newer. |
| 173 |
ini: |
| 174 |
- section: defaults |
| 175 |
key: timeout |
| 176 |
- section: ssh_connection |
| 177 |
key: timeout |
| 178 |
- section: paramiko_connection |
| 179 |
key: timeout |
| 180 |
env: |
| 181 |
- name: ANSIBLE_TIMEOUT |
| 182 |
- name: ANSIBLE_SSH_TIMEOUT |
| 183 |
- name: ANSIBLE_PARAMIKO_TIMEOUT |
| 184 |
vars: |
| 185 |
- name: ansible_ssh_timeout |
| 186 |
- name: ansible_paramiko_timeout |
| 187 |
cli: |
| 188 |
- name: timeout |
| 189 |
lock_file_timeout: |
| 190 |
type: int |
| 191 |
default: 60 |
| 192 |
description: Number of seconds until the plugin gives up on trying to write a lock file when writing SSH known host keys. |
| 193 |
vars: |
| 194 |
- name: ansible_lock_file_timeout |
| 195 |
env: |
| 196 |
- name: ANSIBLE_LOCK_FILE_TIMEOUT |
| 197 |
private_key_file: |
| 198 |
description: |
| 199 |
- Path to private key file to use for authentication. |
| 200 |
type: path |
| 201 |
ini: |
| 202 |
- section: defaults |
| 203 |
key: private_key_file |
| 204 |
- section: paramiko_connection |
| 205 |
key: private_key_file |
| 206 |
env: |
| 207 |
- name: ANSIBLE_PRIVATE_KEY_FILE |
| 208 |
- name: ANSIBLE_PARAMIKO_PRIVATE_KEY_FILE |
| 209 |
vars: |
| 210 |
- name: ansible_private_key_file |
| 211 |
- name: ansible_ssh_private_key_file |
| 212 |
- name: ansible_paramiko_private_key_file |
| 213 |
cli: |
| 214 |
- name: private_key_file |
| 215 |
option: "--private-key" |
| 216 |
user_known_hosts_file: |
| 217 |
description: |
| 218 |
- Path to the user known hosts file. |
| 219 |
- Used to verify the ssh hosts keys. |
| 220 |
type: path |
| 221 |
default: ~/.ssh/known_hosts |
| 222 |
ini: |
| 223 |
- section: paramiko_connection |
| 224 |
key: user_known_hosts_file |
| 225 |
vars: |
| 226 |
- name: ansible_paramiko_user_known_hosts_file |
| 227 |
wsl_distribution: |
| 228 |
description: |
| 229 |
- WSL distribution name. |
| 230 |
type: string |
| 231 |
required: true |
| 232 |
vars: |
| 233 |
- name: wsl_distribution |
| 234 |
wsl_remote_ssh_shell_type: |
| 235 |
description: |
| 236 |
- The shell type expected in the SSH session (not inside the WSL session). |
| 237 |
- See also C(ansible_shell_type). |
| 238 |
type: string |
| 239 |
choices: |
| 240 |
- cmd |
| 241 |
- powershell |
| 242 |
default: cmd |
| 243 |
vars: |
| 244 |
- name: wsl_remote_ssh_shell_type |
| 245 |
version_added: 12.2.0 |
| 246 |
wsl_user: |
| 247 |
description: |
| 248 |
- WSL distribution user. |
| 249 |
type: string |
| 250 |
vars: |
| 251 |
- name: wsl_user |
| 252 |
become_user: |
| 253 |
description: |
| 254 |
- WSL distribution user. |
| 255 |
type: string |
| 256 |
default: root |
| 257 |
vars: |
| 258 |
- name: become_user |
| 259 |
- name: ansible_become_user |
| 260 |
become: |
| 261 |
description: |
| 262 |
- Whether to use the user defined by O(become_user). |
| 263 |
type: bool |
| 264 |
default: false |
| 265 |
vars: |
| 266 |
- name: become |
| 267 |
- name: ansible_become |
| 268 |
""" |
| 269 |
|
| 270 |
EXAMPLES = r""" |
| 271 |
# ------------------------ |
| 272 |
# Inventory: inventory.yml |
| 273 |
# ------------------------ |
| 274 |
--- |
| 275 |
all: |
| 276 |
children: |
| 277 |
wsl: |
| 278 |
hosts: |
| 279 |
example-wsl-ubuntu: |
| 280 |
ansible_host: 10.0.0.10 |
| 281 |
wsl_distribution: ubuntu |
| 282 |
wsl_user: ubuntu |
| 283 |
vars: |
| 284 |
ansible_connection: community.general.wsl |
| 285 |
ansible_user: vagrant |
| 286 |
# ---------------------- |
| 287 |
# Playbook: playbook.yml |
| 288 |
# ---------------------- |
| 289 |
--- |
| 290 |
- name: WSL Example |
| 291 |
hosts: wsl |
| 292 |
gather_facts: true |
| 293 |
become: true |
| 294 |
tasks: |
| 295 |
- name: Ping |
| 296 |
ansible.builtin.ping: |
| 297 |
- name: Id (with become false) |
| 298 |
become: false |
| 299 |
changed_when: false |
| 300 |
args: |
| 301 |
executable: /bin/bash |
| 302 |
ansible.builtin.shell: | |
| 303 |
exec 2>&1 |
| 304 |
set -x |
| 305 |
echo "$0" |
| 306 |
pwd |
| 307 |
id |
| 308 |
- name: Id (with become true) |
| 309 |
changed_when: false |
| 310 |
args: |
| 311 |
executable: /bin/bash |
| 312 |
ansible.builtin.shell: | |
| 313 |
exec 2>&1 |
| 314 |
set -x |
| 315 |
echo "$0" |
| 316 |
pwd |
| 317 |
id |
| 318 |
- name: Reboot |
| 319 |
ansible.builtin.reboot: |
| 320 |
boot_time_command: systemctl show -p ActiveEnterTimestamp init.scope |
| 321 |
""" |
| 322 |
|
| 323 |
import io |
| 324 |
import os |
| 325 |
import pathlib |
| 326 |
import shlex |
| 327 |
import tempfile |
| 328 |
import traceback |
| 329 |
import typing as t |
| 330 |
from binascii import hexlify |
| 331 |
from subprocess import list2cmdline |
| 332 |
|
| 333 |
from ansible.errors import ( |
| 334 |
AnsibleAuthenticationFailure, |
| 335 |
AnsibleConnectionFailure, |
| 336 |
AnsibleError, |
| 337 |
) |
| 338 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 339 |
from ansible.playbook.play_context import PlayContext |
| 340 |
from ansible.plugins.connection import ConnectionBase |
| 341 |
from ansible.utils.display import Display |
| 342 |
from ansible.utils.path import makedirs_safe |
| 343 |
|
| 344 |
from ansible_collections.community.general.plugins.module_utils._filelock import FileLock, LockTimeout |
| 345 |
from ansible_collections.community.general.plugins.module_utils._version import LooseVersion |
| 346 |
|
| 347 |
PARAMIKO_IMPORT_ERR: str | None |
| 348 |
try: |
| 349 |
import paramiko |
| 350 |
from paramiko import MissingHostKeyPolicy |
| 351 |
|
| 352 |
PARAMIKO_IMPORT_ERR = None |
| 353 |
except ImportError: |
| 354 |
PARAMIKO_IMPORT_ERR = traceback.format_exc() |
| 355 |
MissingHostKeyPolicy = object # type: ignore |
| 356 |
|
| 357 |
|
| 358 |
display = Display() |
| 359 |
|
| 360 |
|
| 361 |
def authenticity_msg(hostname: str, ktype: str, fingerprint: bytes) -> str: |
| 362 |
msg = f""" |
| 363 |
paramiko: The authenticity of host '{hostname}' can't be established. |
| 364 |
The {ktype} key fingerprint is {to_text(fingerprint)}. |
| 365 |
Are you sure you want to continue connecting (yes/no)? |
| 366 |
""" |
| 367 |
return msg |
| 368 |
|
| 369 |
|
| 370 |
class MyAddPolicy(MissingHostKeyPolicy): |
| 371 |
""" |
| 372 |
Based on AutoAddPolicy in paramiko so we can determine when keys are added |
| 373 |
|
| 374 |
and also prompt for input. |
| 375 |
|
| 376 |
Policy for automatically adding the hostname and new host key to the |
| 377 |
local L{HostKeys} object, and saving it. This is used by L{SSHClient}. |
| 378 |
""" |
| 379 |
|
| 380 |
def __init__(self, connection: Connection) -> None: |
| 381 |
self.connection = connection |
| 382 |
self._options = connection._options |
| 383 |
|
| 384 |
def missing_host_key(self, client: paramiko.SSHClient, hostname: str, key: paramiko.PKey) -> None: |
| 385 |
if all((self.connection.get_option("host_key_checking"), not self.connection.get_option("host_key_auto_add"))): |
| 386 |
fingerprint = hexlify(key.get_fingerprint()) |
| 387 |
ktype = key.get_name() |
| 388 |
|
| 389 |
if self.connection.get_option("use_persistent_connections") or self.connection.force_persistence: |
| 390 |
# don't print the prompt string since the user cannot respond |
| 391 |
# to the question anyway |
| 392 |
raise AnsibleError(authenticity_msg(hostname, ktype, fingerprint)[1:92]) |
| 393 |
|
| 394 |
inp = to_text( |
| 395 |
display.prompt_until(authenticity_msg(hostname, ktype, fingerprint), private=False), |
| 396 |
errors="surrogate_or_strict", |
| 397 |
) |
| 398 |
|
| 399 |
if inp.lower() not in ["yes", "y", ""]: |
| 400 |
raise AnsibleError("host connection rejected by user") |
| 401 |
|
| 402 |
key._added_by_ansible_this_time = True # type: ignore |
| 403 |
|
| 404 |
# existing implementation below: |
| 405 |
client._host_keys.add(hostname, key.get_name(), key) # type: ignore[attr-defined] # TODO: figure out what _host_keys is! |
| 406 |
|
| 407 |
# host keys are actually saved in close() function below |
| 408 |
# in order to control ordering. |
| 409 |
|
| 410 |
|
| 411 |
class Connection(ConnectionBase): |
| 412 |
"""SSH based connections (paramiko) to WSL""" |
| 413 |
|
| 414 |
transport = "community.general.wsl" |
| 415 |
_log_channel: str | None = None |
| 416 |
|
| 417 |
def __init__( |
| 418 |
self, play_context: PlayContext, new_stdin: io.TextIOWrapper | None = None, *args: t.Any, **kwargs: t.Any |
| 419 |
): |
| 420 |
super().__init__(play_context, new_stdin, *args, **kwargs) |
| 421 |
|
| 422 |
def _set_log_channel(self, name: str) -> None: |
| 423 |
"""Mimic paramiko.SSHClient.set_log_channel""" |
| 424 |
self._log_channel = name |
| 425 |
|
| 426 |
def _parse_proxy_command(self, port: int = 22) -> dict[str, t.Any]: |
| 427 |
proxy_command = self.get_option("proxy_command") or None |
| 428 |
|
| 429 |
sock_kwarg = {} |
| 430 |
if proxy_command: |
| 431 |
replacers: dict[str, str] = { |
| 432 |
"%h": self.get_option("remote_addr"), |
| 433 |
"%p": str(port), |
| 434 |
"%r": self.get_option("remote_user"), |
| 435 |
} |
| 436 |
for find, replace in replacers.items(): |
| 437 |
proxy_command = proxy_command.replace(find, replace) |
| 438 |
try: |
| 439 |
sock_kwarg = {"sock": paramiko.ProxyCommand(proxy_command)} |
| 440 |
display.vvv( |
| 441 |
f"CONFIGURE PROXY COMMAND FOR CONNECTION: {proxy_command}", host=self.get_option("remote_addr") |
| 442 |
) |
| 443 |
except AttributeError: |
| 444 |
display.warning( |
| 445 |
"Paramiko ProxyCommand support unavailable. " |
| 446 |
"Please upgrade to Paramiko 1.9.0 or newer. " |
| 447 |
"Not using configured ProxyCommand" |
| 448 |
) |
| 449 |
|
| 450 |
return sock_kwarg |
| 451 |
|
| 452 |
def _connect(self) -> Connection: |
| 453 |
"""activates the connection object""" |
| 454 |
|
| 455 |
if PARAMIKO_IMPORT_ERR is not None: |
| 456 |
raise AnsibleError(f"paramiko is not installed: {to_native(PARAMIKO_IMPORT_ERR)}") |
| 457 |
|
| 458 |
port = self.get_option("port") |
| 459 |
display.vvv( |
| 460 |
f"ESTABLISH PARAMIKO SSH CONNECTION FOR USER: {self.get_option('remote_user')} on PORT {to_text(port)} TO {self.get_option('remote_addr')}", |
| 461 |
host=self.get_option("remote_addr"), |
| 462 |
) |
| 463 |
|
| 464 |
ssh = paramiko.SSHClient() |
| 465 |
|
| 466 |
# Set pubkey and hostkey algorithms to disable, the only manipulation allowed currently |
| 467 |
# is keeping or omitting rsa-sha2 algorithms |
| 468 |
# default_keys: t.Tuple[str] = () |
| 469 |
paramiko_preferred_pubkeys = getattr(paramiko.Transport, "_preferred_pubkeys", ()) |
| 470 |
paramiko_preferred_hostkeys = getattr(paramiko.Transport, "_preferred_keys", ()) |
| 471 |
use_rsa_sha2_algorithms = self.get_option("use_rsa_sha2_algorithms") |
| 472 |
disabled_algorithms: dict[str, t.Iterable[str]] = {} |
| 473 |
if not use_rsa_sha2_algorithms: |
| 474 |
if paramiko_preferred_pubkeys: |
| 475 |
disabled_algorithms["pubkeys"] = tuple(a for a in paramiko_preferred_pubkeys if "rsa-sha2" in a) |
| 476 |
if paramiko_preferred_hostkeys: |
| 477 |
disabled_algorithms["keys"] = tuple(a for a in paramiko_preferred_hostkeys if "rsa-sha2" in a) |
| 478 |
|
| 479 |
# override paramiko's default logger name |
| 480 |
if self._log_channel is not None: |
| 481 |
ssh.set_log_channel(self._log_channel) |
| 482 |
|
| 483 |
self.keyfile = os.path.expanduser(self.get_option("user_known_hosts_file")) |
| 484 |
|
| 485 |
if self.get_option("host_key_checking"): |
| 486 |
for ssh_known_hosts in ("/etc/ssh/ssh_known_hosts", "/etc/openssh/ssh_known_hosts", self.keyfile): |
| 487 |
try: |
| 488 |
ssh.load_system_host_keys(ssh_known_hosts) |
| 489 |
break |
| 490 |
except OSError: |
| 491 |
pass # file was not found, but not required to function |
| 492 |
except paramiko.hostkeys.InvalidHostKey as e: |
| 493 |
raise AnsibleConnectionFailure(f"Invalid host key: {to_text(e.line)}") from e |
| 494 |
try: |
| 495 |
ssh.load_system_host_keys() |
| 496 |
except paramiko.hostkeys.InvalidHostKey as e: |
| 497 |
raise AnsibleConnectionFailure(f"Invalid host key: {to_text(e.line)}") from e |
| 498 |
|
| 499 |
ssh_connect_kwargs = self._parse_proxy_command(port) |
| 500 |
ssh.set_missing_host_key_policy(MyAddPolicy(self)) |
| 501 |
conn_password = self.get_option("password") |
| 502 |
allow_agent = True |
| 503 |
|
| 504 |
if conn_password is not None: |
| 505 |
allow_agent = False |
| 506 |
|
| 507 |
try: |
| 508 |
key_filename = None |
| 509 |
if self.get_option("private_key_file"): |
| 510 |
key_filename = os.path.expanduser(self.get_option("private_key_file")) |
| 511 |
|
| 512 |
# paramiko 2.2 introduced auth_timeout parameter |
| 513 |
if LooseVersion(paramiko.__version__) >= LooseVersion("2.2.0"): |
| 514 |
ssh_connect_kwargs["auth_timeout"] = self.get_option("timeout") |
| 515 |
|
| 516 |
# paramiko 1.15 introduced banner timeout parameter |
| 517 |
if LooseVersion(paramiko.__version__) >= LooseVersion("1.15.0"): |
| 518 |
ssh_connect_kwargs["banner_timeout"] = self.get_option("banner_timeout") |
| 519 |
|
| 520 |
ssh.connect( |
| 521 |
self.get_option("remote_addr").lower(), |
| 522 |
username=self.get_option("remote_user"), |
| 523 |
allow_agent=allow_agent, |
| 524 |
look_for_keys=self.get_option("look_for_keys"), |
| 525 |
key_filename=key_filename, |
| 526 |
password=conn_password, |
| 527 |
timeout=self.get_option("timeout"), |
| 528 |
port=port, |
| 529 |
disabled_algorithms=disabled_algorithms, |
| 530 |
**ssh_connect_kwargs, |
| 531 |
) |
| 532 |
except paramiko.ssh_exception.BadHostKeyException as e: |
| 533 |
raise AnsibleConnectionFailure(f"host key mismatch for {to_text(e.hostname)}") from e |
| 534 |
except paramiko.ssh_exception.AuthenticationException as e: |
| 535 |
msg = f"Failed to authenticate: {e}" |
| 536 |
raise AnsibleAuthenticationFailure(msg) from e |
| 537 |
except Exception as e: |
| 538 |
msg = to_text(e) |
| 539 |
if "PID check failed" in msg: |
| 540 |
raise AnsibleError( |
| 541 |
"paramiko version issue, please upgrade paramiko on the machine running ansible" |
| 542 |
) from e |
| 543 |
elif "Private key file is encrypted" in msg: |
| 544 |
msg = ( |
| 545 |
f"ssh {self.get_option('remote_user')}@{self.get_options('remote_addr')}:{port} : " |
| 546 |
f"{msg}\nTo connect as a different user, use -u <username>." |
| 547 |
) |
| 548 |
raise AnsibleConnectionFailure(msg) from e |
| 549 |
else: |
| 550 |
raise AnsibleConnectionFailure(msg) from e |
| 551 |
self.ssh = ssh |
| 552 |
self._connected = True |
| 553 |
return self |
| 554 |
|
| 555 |
def _any_keys_added(self) -> bool: |
| 556 |
for host_keys in self.ssh._host_keys.values(): # type: ignore[attr-defined] # TODO: figure out what _host_keys is! |
| 557 |
for key in host_keys.values(): |
| 558 |
added_this_time = getattr(key, "_added_by_ansible_this_time", False) |
| 559 |
if added_this_time: |
| 560 |
return True |
| 561 |
return False |
| 562 |
|
| 563 |
def _save_ssh_host_keys(self, filename: str) -> None: |
| 564 |
""" |
| 565 |
not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks |
| 566 |
don't complain about it :) |
| 567 |
""" |
| 568 |
|
| 569 |
if not self._any_keys_added(): |
| 570 |
return |
| 571 |
|
| 572 |
path = os.path.expanduser("~/.ssh") |
| 573 |
makedirs_safe(path) |
| 574 |
|
| 575 |
with open(filename, "w") as f: |
| 576 |
for hostname, keys in self.ssh._host_keys.items(): # type: ignore[attr-defined] # TODO: figure out what _host_keys is! |
| 577 |
for keytype, key in keys.items(): |
| 578 |
# was f.write |
| 579 |
added_this_time = getattr(key, "_added_by_ansible_this_time", False) |
| 580 |
if not added_this_time: |
| 581 |
f.write(f"{hostname} {keytype} {key.get_base64()}\n") |
| 582 |
|
| 583 |
for hostname, keys in self.ssh._host_keys.items(): # type: ignore[attr-defined] # TODO: figure out what _host_keys is! |
| 584 |
for keytype, key in keys.items(): |
| 585 |
added_this_time = getattr(key, "_added_by_ansible_this_time", False) |
| 586 |
if added_this_time: |
| 587 |
f.write(f"{hostname} {keytype} {key.get_base64()}\n") |
| 588 |
|
| 589 |
def _build_wsl_command(self, cmd: str) -> str: |
| 590 |
wsl_distribution = self.get_option("wsl_distribution") |
| 591 |
become = self.get_option("become") |
| 592 |
become_user = self.get_option("become_user") |
| 593 |
wsl_remote_ssh_shell_type = self.get_option("wsl_remote_ssh_shell_type") |
| 594 |
is_integration_test = os.getenv("_ANSIBLE_TEST_WSL_CONNECTION_PLUGIN_WAERI5TEPHEESHA2FAE8") |
| 595 |
if "%" in cmd: |
| 596 |
if wsl_remote_ssh_shell_type == "powershell": |
| 597 |
# there is no universal way to escape '%' here |
| 598 |
# if this is raised, add a workaround to allow the specific situation (if possible) |
| 599 |
raise AnsibleError("The command contains '%', cannot safely escape it for Powershell") |
| 600 |
else: |
| 601 |
cmd = cmd.replace("%", "^%") |
| 602 |
if become and become_user: |
| 603 |
wsl_user = become_user |
| 604 |
else: |
| 605 |
wsl_user = self.get_option("wsl_user") |
| 606 |
args = ["wsl.exe"] |
| 607 |
if wsl_remote_ssh_shell_type == "powershell" and not is_integration_test: |
| 608 |
# Powershell stop-parsing token, treat the rest as arguments to the native command wsl.exe |
| 609 |
args.append("--%") |
| 610 |
args.extend(["--distribution", wsl_distribution]) |
| 611 |
if wsl_user: |
| 612 |
args.extend(["--user", wsl_user]) |
| 613 |
args.extend(["--"]) |
| 614 |
args.extend(shlex.split(cmd)) |
| 615 |
if is_integration_test: |
| 616 |
return shlex.join(args) |
| 617 |
else: |
| 618 |
return list2cmdline(args) # see https://github.com/python/cpython/blob/3.11/Lib/subprocess.py#L576 |
| 619 |
|
| 620 |
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]: |
| 621 |
"""run a command on inside a WSL distribution""" |
| 622 |
|
| 623 |
cmd = self._build_wsl_command(cmd) |
| 624 |
|
| 625 |
super().exec_command(cmd, in_data=in_data, sudoable=sudoable) # type: ignore[safe-super] |
| 626 |
|
| 627 |
bufsize = 4096 |
| 628 |
|
| 629 |
try: |
| 630 |
transport = self.ssh.get_transport() |
| 631 |
if transport is None: |
| 632 |
raise ValueError("Transport not available") |
| 633 |
transport.set_keepalive(5) |
| 634 |
chan = transport.open_session() |
| 635 |
except Exception as e: |
| 636 |
text_e = to_text(e) |
| 637 |
msg = "Failed to open session" |
| 638 |
if text_e: |
| 639 |
msg += f": {text_e}" |
| 640 |
raise AnsibleConnectionFailure(to_native(msg)) from e |
| 641 |
|
| 642 |
display.vvv(f"EXEC {cmd}", host=self.get_option("remote_addr")) |
| 643 |
|
| 644 |
cmd_b = to_bytes(cmd, errors="surrogate_or_strict") |
| 645 |
|
| 646 |
no_prompt_out = b"" |
| 647 |
no_prompt_err = b"" |
| 648 |
become_output = b"" |
| 649 |
|
| 650 |
try: |
| 651 |
chan.exec_command(cmd_b) |
| 652 |
if self.become and self.become.expect_prompt(): |
| 653 |
password_prompt = False |
| 654 |
become_success = False |
| 655 |
while not (become_success or password_prompt): |
| 656 |
display.debug("Waiting for Privilege Escalation input") |
| 657 |
|
| 658 |
chunk = chan.recv(bufsize) |
| 659 |
display.debug(f"chunk is: {to_text(chunk)}") |
| 660 |
if not chunk: |
| 661 |
if b"unknown user" in become_output: |
| 662 |
n_become_user = to_native(self.become.get_option("become_user")) |
| 663 |
raise AnsibleError(f"user {n_become_user} does not exist") |
| 664 |
else: |
| 665 |
break |
| 666 |
# raise AnsibleError('ssh connection closed waiting for password prompt') |
| 667 |
become_output += chunk |
| 668 |
|
| 669 |
# need to check every line because we might get lectured |
| 670 |
# and we might get the middle of a line in a chunk |
| 671 |
for line in become_output.splitlines(True): |
| 672 |
if self.become.check_success(line): |
| 673 |
become_success = True |
| 674 |
break |
| 675 |
elif self.become.check_password_prompt(line): |
| 676 |
password_prompt = True |
| 677 |
break |
| 678 |
|
| 679 |
if password_prompt: |
| 680 |
if self.become: |
| 681 |
become_pass = self.become.get_option("become_pass") |
| 682 |
chan.sendall(to_bytes(f"{become_pass}\n", errors="surrogate_or_strict")) |
| 683 |
else: |
| 684 |
raise AnsibleError("A password is required but none was supplied") |
| 685 |
else: |
| 686 |
no_prompt_out += become_output |
| 687 |
no_prompt_err += become_output |
| 688 |
|
| 689 |
if in_data: |
| 690 |
for i in range(0, len(in_data), bufsize): |
| 691 |
chan.send(in_data[i : i + bufsize]) |
| 692 |
chan.shutdown_write() |
| 693 |
elif in_data == b"": |
| 694 |
chan.shutdown_write() |
| 695 |
|
| 696 |
except TimeoutError as e: |
| 697 |
raise AnsibleError(f"ssh timed out waiting for privilege escalation.\n{to_text(become_output)}") from e |
| 698 |
|
| 699 |
stdout = b"".join(chan.makefile("rb", bufsize)) |
| 700 |
stderr = b"".join(chan.makefile_stderr("rb", bufsize)) |
| 701 |
returncode = chan.recv_exit_status() |
| 702 |
|
| 703 |
# NB the full english error message is: |
| 704 |
# 'wsl.exe' is not recognized as an internal or external command, |
| 705 |
# operable program or batch file. |
| 706 |
if "'wsl.exe' is not recognized" in stderr.decode("utf-8"): |
| 707 |
raise AnsibleError(f"wsl.exe not found in path of host: {to_text(self.get_option('remote_addr'))}") |
| 708 |
|
| 709 |
return (returncode, no_prompt_out + stdout, no_prompt_out + stderr) |
| 710 |
|
| 711 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 712 |
"""transfer a file from local to remote""" |
| 713 |
|
| 714 |
display.vvv(f"PUT {in_path} TO {out_path}", host=self.get_option("remote_addr")) |
| 715 |
try: |
| 716 |
with open(in_path, "rb") as f: |
| 717 |
data = f.read() |
| 718 |
returncode, stdout, stderr = self.exec_command( |
| 719 |
f"{self._shell.executable} -c {self._shell.quote(f'cat > {out_path}')}", |
| 720 |
in_data=data, |
| 721 |
sudoable=False, |
| 722 |
) |
| 723 |
if returncode != 0: |
| 724 |
if "cat: not found" in stderr.decode("utf-8"): |
| 725 |
raise AnsibleError( |
| 726 |
f"cat not found in path of WSL distribution: {to_text(self.get_option('wsl_distribution'))}" |
| 727 |
) |
| 728 |
raise AnsibleError(f"{to_text(stdout)}\n{to_text(stderr)}") |
| 729 |
except Exception as e: |
| 730 |
raise AnsibleError(f"error occurred while putting file from {in_path} to {out_path}!\n{to_text(e)}") from e |
| 731 |
|
| 732 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 733 |
"""save a remote file to the specified path""" |
| 734 |
|
| 735 |
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.get_option("remote_addr")) |
| 736 |
try: |
| 737 |
returncode, stdout, stderr = self.exec_command( |
| 738 |
f"{self._shell.executable} -c {self._shell.quote(f'cat {in_path}')}", sudoable=False |
| 739 |
) |
| 740 |
if returncode != 0: |
| 741 |
if "cat: not found" in stderr.decode("utf-8"): |
| 742 |
raise AnsibleError( |
| 743 |
f"cat not found in path of WSL distribution: {to_text(self.get_option('wsl_distribution'))}" |
| 744 |
) |
| 745 |
raise AnsibleError(f"{to_text(stdout)}\n{to_text(stderr)}") |
| 746 |
with open(out_path, "wb") as f: |
| 747 |
f.write(stdout) |
| 748 |
except Exception as e: |
| 749 |
raise AnsibleError(f"error occurred while fetching file from {in_path} to {out_path}!\n{to_text(e)}") from e |
| 750 |
|
| 751 |
def reset(self) -> None: |
| 752 |
"""reset the connection""" |
| 753 |
|
| 754 |
if not self._connected: |
| 755 |
return |
| 756 |
self.close() |
| 757 |
self._connect() |
| 758 |
|
| 759 |
def close(self) -> None: |
| 760 |
"""terminate the connection""" |
| 761 |
|
| 762 |
if self.get_option("host_key_checking") and self.get_option("record_host_keys") and self._any_keys_added(): |
| 763 |
# add any new SSH host keys -- warning -- this could be slow |
| 764 |
# (This doesn't acquire the connection lock because it needs |
| 765 |
# to exclude only other known_hosts writers, not connections |
| 766 |
# that are starting up.) |
| 767 |
lockfile = os.path.basename(self.keyfile) |
| 768 |
dirname = os.path.dirname(self.keyfile) |
| 769 |
makedirs_safe(dirname) |
| 770 |
tmp_keyfile_name = None |
| 771 |
try: |
| 772 |
with FileLock().lock_file(lockfile, dirname, self.get_option("lock_file_timeout")): |
| 773 |
# just in case any were added recently |
| 774 |
|
| 775 |
self.ssh.load_system_host_keys() |
| 776 |
self.ssh._host_keys.update(self.ssh._system_host_keys) # type: ignore[attr-defined] # TODO this is a HACK! |
| 777 |
|
| 778 |
# gather information about the current key file, so |
| 779 |
# we can ensure the new file has the correct mode/owner |
| 780 |
|
| 781 |
key_dir = os.path.dirname(self.keyfile) |
| 782 |
if os.path.exists(self.keyfile): |
| 783 |
key_stat = os.stat(self.keyfile) |
| 784 |
mode = key_stat.st_mode & 0o777 |
| 785 |
uid = key_stat.st_uid |
| 786 |
gid = key_stat.st_gid |
| 787 |
else: |
| 788 |
mode = 0o644 |
| 789 |
uid = os.getuid() |
| 790 |
gid = os.getgid() |
| 791 |
|
| 792 |
# Save the new keys to a temporary file and move it into place |
| 793 |
# rather than rewriting the file. We set delete=False because |
| 794 |
# the file will be moved into place rather than cleaned up. |
| 795 |
|
| 796 |
with tempfile.NamedTemporaryFile(dir=key_dir, delete=False) as tmp_keyfile: |
| 797 |
tmp_keyfile_name = tmp_keyfile.name |
| 798 |
os.chmod(tmp_keyfile_name, mode) |
| 799 |
os.chown(tmp_keyfile_name, uid, gid) |
| 800 |
self._save_ssh_host_keys(tmp_keyfile_name) |
| 801 |
|
| 802 |
os.rename(tmp_keyfile_name, self.keyfile) |
| 803 |
except LockTimeout as e: |
| 804 |
raise AnsibleError( |
| 805 |
f"writing lock file for {self.keyfile} ran in to the timeout of {self.get_option('lock_file_timeout')}s" |
| 806 |
) from e |
| 807 |
except paramiko.hostkeys.InvalidHostKey as e: |
| 808 |
raise AnsibleConnectionFailure(f"Invalid host key: {e.line}") from e |
| 809 |
except Exception as e: |
| 810 |
# unable to save keys, including scenario when key was invalid |
| 811 |
# and caught earlier |
| 812 |
raise AnsibleError(f"error occurred while writing SSH host keys!\n{to_text(e)}") from e |
| 813 |
finally: |
| 814 |
if tmp_keyfile_name is not None: |
| 815 |
pathlib.Path(tmp_keyfile_name).unlink(missing_ok=True) |
| 816 |
|
| 817 |
self.ssh.close() |
| 818 |
self._connected = False |