
    Vh*s                       U d dl mZ dZdZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Zd dlmZmZmZ d dlmZmZ d dlmZmZmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dl m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z' ejP                  rerd dlm)Z) d dl*m+Z+ d dl,m-Z- ne.Z)de/d<   e.Z+de/d<   e.Z-de/d<    e!       Z0ddZ1 G d de)      Z2 G d de      Z3y)    )annotationsa+  
author: Rui Lopes (@rgl) <ruilopes.com>
name: wsl
short_description: Run tasks in WSL distribution using wsl.exe CLI via SSH
requirements:
  - paramiko
description:
  - Run commands or put/fetch files to an existing WSL distribution using wsl.exe CLI via SSH.
  - Uses the Python SSH implementation (Paramiko) to connect to the WSL host.
version_added: "10.6.0"
options:
  remote_addr:
    description:
      - Address of the remote target.
    default: inventory_hostname
    type: string
    vars:
      - name: inventory_hostname
      - name: ansible_host
      - name: ansible_ssh_host
      - name: ansible_paramiko_host
  port:
    description: Remote port to connect to.
    type: int
    default: 22
    ini:
      - section: defaults
        key: remote_port
      - section: paramiko_connection
        key: remote_port
    env:
      - name: ANSIBLE_REMOTE_PORT
      - name: ANSIBLE_REMOTE_PARAMIKO_PORT
    vars:
      - name: ansible_port
      - name: ansible_ssh_port
      - name: ansible_paramiko_port
    keyword:
      - name: port
  remote_user:
    description:
      - User to login/authenticate as.
      - Can be set from the CLI via the C(--user) or C(-u) options.
    type: string
    vars:
      - name: ansible_user
      - name: ansible_ssh_user
      - name: ansible_paramiko_user
    env:
      - name: ANSIBLE_REMOTE_USER
      - name: ANSIBLE_PARAMIKO_REMOTE_USER
    ini:
      - section: defaults
        key: remote_user
      - section: paramiko_connection
        key: remote_user
    keyword:
      - name: remote_user
  password:
    description:
      - Secret used to either login the SSH server or as a passphrase for SSH keys that require it.
      - Can be set from the CLI via the C(--ask-pass) option.
    type: string
    vars:
      - name: ansible_password
      - name: ansible_ssh_pass
      - name: ansible_ssh_password
      - name: ansible_paramiko_pass
      - name: ansible_paramiko_password
  use_rsa_sha2_algorithms:
    description:
      - Whether or not to enable RSA SHA2 algorithms for pubkeys and hostkeys.
      - On paramiko versions older than 2.9, this only affects hostkeys.
      - For behavior matching paramiko<2.9 set this to V(false).
    vars:
      - name: ansible_paramiko_use_rsa_sha2_algorithms
    ini:
      - {key: use_rsa_sha2_algorithms, section: paramiko_connection}
    env:
      - {name: ANSIBLE_PARAMIKO_USE_RSA_SHA2_ALGORITHMS}
    default: true
    type: boolean
  host_key_auto_add:
    description: "Automatically add host keys to C(~/.ssh/known_hosts)."
    env:
      - name: ANSIBLE_PARAMIKO_HOST_KEY_AUTO_ADD
    ini:
      - key: host_key_auto_add
        section: paramiko_connection
    type: boolean
  look_for_keys:
    default: true
    description: "Set to V(false) to disable searching for private key files in C(~/.ssh/)."
    env:
      - name: ANSIBLE_PARAMIKO_LOOK_FOR_KEYS
    ini:
      - {key: look_for_keys, section: paramiko_connection}
    type: boolean
  proxy_command:
    default: ""
    description:
      - Proxy information for running the connection via a jumphost.
      - This option is supported by paramiko version 1.9.0 or newer.
    type: string
    env:
      - name: ANSIBLE_PARAMIKO_PROXY_COMMAND
    ini:
      - {key: proxy_command, section: paramiko_connection}
    vars:
      - name: ansible_paramiko_proxy_command
  record_host_keys:
    default: true
    description: "Save the host keys to a file."
    env:
      - name: ANSIBLE_PARAMIKO_RECORD_HOST_KEYS
    ini:
      - section: paramiko_connection
        key: record_host_keys
    type: boolean
  host_key_checking:
    description: "Set this to V(false) if you want to avoid host key checking by the underlying tools Ansible uses to connect to the host."
    type: boolean
    default: true
    env:
      - name: ANSIBLE_HOST_KEY_CHECKING
      - name: ANSIBLE_SSH_HOST_KEY_CHECKING
      - name: ANSIBLE_PARAMIKO_HOST_KEY_CHECKING
    ini:
      - section: defaults
        key: host_key_checking
      - section: paramiko_connection
        key: host_key_checking
    vars:
      - name: ansible_host_key_checking
      - name: ansible_ssh_host_key_checking
      - name: ansible_paramiko_host_key_checking
  use_persistent_connections:
    description: "Toggles the use of persistence for connections."
    type: boolean
    default: false
    env:
      - name: ANSIBLE_USE_PERSISTENT_CONNECTIONS
    ini:
      - section: defaults
        key: use_persistent_connections
  banner_timeout:
    type: float
    default: 30
    description:
      - Configures, in seconds, the amount of time to wait for the SSH
        banner to be presented.
      - This option is supported by paramiko version 1.15.0 or newer.
    ini:
      - section: paramiko_connection
        key: banner_timeout
    env:
      - name: ANSIBLE_PARAMIKO_BANNER_TIMEOUT
  timeout:
    type: int
    default: 10
    description:
      - Number of seconds until the plugin gives up on failing to establish a TCP connection.
      - This option is supported by paramiko version 2.2.0 or newer.
    ini:
      - section: defaults
        key: timeout
      - section: ssh_connection
        key: timeout
      - section: paramiko_connection
        key: timeout
    env:
      - name: ANSIBLE_TIMEOUT
      - name: ANSIBLE_SSH_TIMEOUT
      - name: ANSIBLE_PARAMIKO_TIMEOUT
    vars:
      - name: ansible_ssh_timeout
      - name: ansible_paramiko_timeout
    cli:
      - name: timeout
  lock_file_timeout:
    type: int
    default: 60
    description: Number of seconds until the plugin gives up on trying to write a lock file when writing SSH known host keys.
    vars:
      - name: ansible_lock_file_timeout
    env:
      - name: ANSIBLE_LOCK_FILE_TIMEOUT
  private_key_file:
    description:
      - Path to private key file to use for authentication.
    type: path
    ini:
      - section: defaults
        key: private_key_file
      - section: paramiko_connection
        key: private_key_file
    env:
      - name: ANSIBLE_PRIVATE_KEY_FILE
      - name: ANSIBLE_PARAMIKO_PRIVATE_KEY_FILE
    vars:
      - name: ansible_private_key_file
      - name: ansible_ssh_private_key_file
      - name: ansible_paramiko_private_key_file
    cli:
      - name: private_key_file
        option: "--private-key"
  user_known_hosts_file:
    description:
      - Path to the user known hosts file.
      - Used to verify the ssh hosts keys.
    type: path
    default: ~/.ssh/known_hosts
    ini:
      - section: paramiko_connection
        key: user_known_hosts_file
    vars:
      - name: ansible_paramiko_user_known_hosts_file
  wsl_distribution:
    description:
      - WSL distribution name
    type: string
    required: true
    vars:
      - name: wsl_distribution
  wsl_user:
    description:
      - WSL distribution user
    type: string
    vars:
      - name: wsl_user
  become_user:
    description:
      - WSL distribution user
    type: string
    default: root
    vars:
      - name: become_user
      - name: ansible_become_user
  become:
    description:
      - whether to use the user defined by ansible_become_user.
    type: bool
    default: false
    vars:
      - name: become
      - name: ansible_become
aP  
# ------------------------
# Inventory: inventory.yml
# ------------------------
---
all:
  children:
    wsl:
      hosts:
        example-wsl-ubuntu:
          ansible_host: 10.0.0.10
          wsl_distribution: ubuntu
          wsl_user: ubuntu
      vars:
        ansible_connection: community.general.wsl
        ansible_user: vagrant
# ----------------------
# Playbook: playbook.yml
# ----------------------
---
- name: WSL Example
  hosts: wsl
  gather_facts: true
  become: true
  tasks:
    - name: Ping
      ansible.builtin.ping:
    - name: Id (with become false)
      become: false
      changed_when: false
      args:
        executable: /bin/bash
      ansible.builtin.shell: |
        exec 2>&1
        set -x
        echo "$0"
        pwd
        id
    - name: Id (with become true)
      changed_when: false
      args:
        executable: /bin/bash
      ansible.builtin.shell: |
        exec 2>&1
        set -x
        echo "$0"
        pwd
        id
    - name: Reboot
      ansible.builtin.reboot:
        boot_time_command: systemctl show -p ActiveEnterTimestamp init.scope
N)AnsibleAuthenticationFailureAnsibleConnectionFailureAnsibleError)FileLockLockTimeout)to_bytes	to_nativeto_text)PARAMIKO_IMPORT_ERRparamiko)LooseVersion)PlayContext)ConnectionBase)Display)makedirs_safe)hexlify)list2cmdline)MissingHostKeyPolicy)	SSHClient)PKeytyper   r   r   c                    d|  d| d| d}|S )Nz)
    paramiko: The authenticity of host 'z ' can't be established.
    The z key fingerprint is zA.
    Are you sure you want to continue connecting (yes/no)?
     )hostnamektypefingerprintmsgs       l/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/connection/wsl.pyauthenticity_msgr    ^  s0    ))1
 3		#K= 1C
 J    c                       e Zd ZdZddZddZy)MyAddPolicya	  
    Based on AutoAddPolicy in paramiko so we can determine when keys are added

    and also prompt for input.

    Policy for automatically adding the hostname and new host key to the
    local L{HostKeys} object, and saving it. This is used by L{SSHClient}.
    c                4    || _         |j                  | _        y N)
connection_options)selfr&   s     r   __init__zMyAddPolicy.__init__q  s    $"++r!   c           	     b   t        | j                  j                  d      | j                  j                  d       f      rt        |j	                               }|j                         }| j                  j                  d      s| j                  j                  rt        t        |||      dd       t        t        j                  t        |||      d      d	      }|j                         d
vrt        d      d|_        |j                  j                  ||j                         |       y )Nhost_key_checkinghost_key_auto_adduse_persistent_connections   \   F)privatesurrogate_or_stricterrors)yesy z host connection rejected by userT)allr&   
get_optionr   get_fingerprintget_nameforce_persistencer   r    r   displayprompt_untillower_added_by_ansible_this_time
_host_keysadd)r(   clientr   keyr   r   inps          r   missing_host_keyzMyAddPolicy.missing_host_keyu  s    **+>?T__E_E_`sEtAtuv!#"5"5"78KLLNE))*FG4??KlKl ##3He[#QRSTV#WXX$$%5h{%S]b$c,C
 yy{"22"#EFF*.' 	h<r!   N)r&   
ConnectionreturnNone)rB   r   r   strrC   r   rG   rH   )__name__
__module____qualname____doc__r)   rE   r   r!   r   r#   r#   g  s    ,=r!   r#   c                       e Zd ZU dZdZdZded<   dd fdZddZdddZ	dd	Z
dd
ZddZddZdd fdZddZddZddZddZ xZS )rF   z) SSH based connections (paramiko) to WSL zcommunity.general.wslNz
str | None_log_channelc                6    t        t        | 
  ||g|i | y r%   )superrF   r)   )r(   play_context	new_stdinargskwargs	__class__s        r   r)   zConnection.__init__  s    j$(yR4R6Rr!   c                    || _         y)z* Mimic paramiko.SSHClient.set_log_channel N)rO   )r(   names     r   _set_log_channelzConnection._set_log_channel  s
     r!   c                   | j                  d      xs d }i }|r| j                  d      t        |      | j                  d      d}|j                         D ]  \  }}|j                  ||      } 	 dt	        j
                  |      i}t        j                  d| | j                  d             |S |S # t        $ r t        j                  d       Y |S w xY w)	Nproxy_commandremote_addrremote_user)z%hz%pz%rsockz(CONFIGURE PROXY COMMAND FOR CONNECTION: hostzwParamiko ProxyCommand support unavailable. Please upgrade to Paramiko 1.9.0 or newer. Not using configured ProxyCommand)
r8   rI   itemsreplacer   ProxyCommandr<   vvvAttributeErrorwarning)r(   portr[   
sock_kwarg	replacersfindrb   s          r   _parse_proxy_commandzConnection._parse_proxy_command  s    8@D
oom4$ioom4+I
 "+!2 Eg - 5 5dG DEE$h&;&;M&JK
F}oV]a]l]lmz]{| z " E !D E Es   2A B6 6CCc                D	   t         t        dt        t                     | j	                  d      }t
        j                  d| j	                  d       dt        |       d| j	                  d       | j	                  d      	       t        j                         }t        t         j                  d
d      }t        t         j                  dd      }| j	                  d      }i }|s.|rt        d |D              |d<   |rt        d |D              |d<   | j                  |j                  | j                         t        j                  j!                  | j	                  d            | _        | j	                  d      r8dd| j"                  fD ]  }	 |j%                  |        n 	 |j%                          | j1                  |      }	|j3                  t5        |              | j	                  d      }
d}|
d}	 d}| j	                  d      r.t        j                  j!                  | j	                  d            }t7        t         j8                        t7        d      k\  r| j	                  d      |	d<   t7        t         j8                        t7        d      k\  r| j	                  d      |	d<    |j:                  | j	                  d      j=                         f| j	                  d      || j	                  d       ||
| j	                  d      ||d!|	 || _&        d| _'        | S # t&        $ r Y t         j(                  j*                  $ r&}t-        dt        |j.                               d}~ww xY w# t         j(                  j*                  $ r&}t-        dt        |j.                               d}~ww xY w# t         j>                  j@                  $ r&}t-        d"t        |jB                               d}~wt         j>                  jD                  $ r}d#| }tG        |      d}~wtH        $ ri}t        |      }d$|v rt        d%      d&|v r;d'| j	                  d       d(| jK                  d       d)| d*| d+z   }t-        |      t-        |      d}~ww xY w),z! activates the connection object Nzparamiko is not installed: rg   z,ESTABLISH PARAMIKO SSH CONNECTION FOR USER: r]   z	 on PORT  TO r\   r_   _preferred_pubkeysr   _preferred_keysuse_rsa_sha2_algorithmsc              3  *   K   | ]  }d |v s|  ywzrsa-sha2Nr   .0as     r   	<genexpr>z&Connection._connect.<locals>.<genexpr>  s     6pQ`jno`oq6p   	pubkeysc              3  *   K   | ]  }d |v s|  ywrr   r   rs   s     r   rv   z&Connection._connect.<locals>.<genexpr>  s     3n!^hlm^mA3nrw   keysuser_known_hosts_filer+   z/etc/ssh/ssh_known_hostsz/etc/openssh/ssh_known_hostsInvalid host key: passwordTFprivate_key_filez2.2.0timeoutauth_timeoutz1.15.0banner_timeoutlook_for_keys)usernameallow_agentr   key_filenamer}   r   rg   disabled_algorithmszhost key mismatch for zFailed to authenticate: zPID check failedzNparamiko version issue, please upgrade paramiko on the machine running ansiblezPrivate key file is encryptedzssh @:z : z3
To connect as a different user, use -u <username>.)(r   r   r
   r   r8   r<   rd   r   r   getattr	TransporttuplerO   set_log_channelospath
expanduserkeyfileload_system_host_keysIOErrorhostkeysInvalidHostKeyr   linerk   set_missing_host_key_policyr#   r   __version__connectr>   ssh_exceptionBadHostKeyExceptionr   AuthenticationExceptionr   	Exceptionget_optionsssh
_connected)r(   rg   r   paramiko_preferred_pubkeysparamiko_preferred_hostkeysrp   r   ssh_known_hostsessh_connect_kwargsconn_passwordr   r   r   s                 r   _connectzConnection._connect  s    !<YGZ=[<\]^^v&B4??S`CaBbbklstxlykzz~  @D  @O  @O  P]  @^  _  `7 	 	9   "
 &-X-?-?AUWY%Z"&-h.@.@BSUW&X#"&//2K"L<>&)166pB\6p1p#I.*.33n?Z3n.n#F+ ( 1 12ww))$//:Q*RS??./$>@^`d`l`l#m [[--o>[W))+ "66t<''D(9:
3$K'	4L12!ww11$//BT2UV H001\'5JJ59__Y5O">2 H001\(5KK7;GW7X"#34CKK.4467'"ooo>)&	2$7 %6 w  ((77 [25GPQPVPVGX3YZZ[ $$33 W.1CGAFFOCT/UVVWH %%99 	[*-CGAJJDWCX+YZZ%%== 	4,QC0C.s33 		4!*C"c)"#stt1S8T__];<Ad>N>N}>]=^^_`d_eehieOPQ.s33.s33		4sh   L%)M6 <DN< %	M31M3!M..M36N9!N44N9<R!O:: RP**R6A$RRc                    | j                   j                  j                         D ]/  \  }}|j                         D ]  \  }}t        |dd      }|s  y 1 y)Nr?   FT)r   r@   ra   r   )r(   r   rz   keytyperC   added_this_times         r   _any_keys_addedzConnection._any_keys_added  s[    "hh11779 	 NHd $

  ")#/Le"T" 	 
 r!   c                   | j                         syt        j                  j                  d      }t	        |       t        |d      5 }| j                  j                  j                         D ]U  \  }}|j                         D ]=  \  }}t        |dd      }|r|j                  | d| d|j                          d       ? W | j                  j                  j                         D ]U  \  }}|j                         D ]=  \  }}t        |dd      }|s|j                  | d| d|j                          d       ? W 	 ddd       y# 1 sw Y   yxY w)z
        not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks
        don't complain about it :)
        Nz~/.sshwr?   F 
)r   r   r   r   r   openr   r@   ra   r   write
get_base64)	r(   filenamer   fr   rz   r   rC   r   s	            r   _save_ssh_host_keyszConnection._save_ssh_host_keys  sP    ##%ww!!(+d(C  	NA"&(("5"5";";"= N$$(JJL NLGS&-c3PRW&XO*8*AgYa8H7I LM	NN #'(("5"5";";"= N$$(JJL NLGS&-c3PRW&XO&8*AgYa8H7I LMNN	N 	N 	Ns   AEA;E,EEc                   | j                  d      }| j                  d      }| j                  d      }|r|r|}n| j                  d      }dd|g}|r|j                  d|g       |j                  dg       |j                  t        j                  |             t	        j
                  d	      rt        j                  |      S t        |      S )
Nwsl_distributionbecomebecome_userwsl_userzwsl.exez--distributionz--userz--8_ANSIBLE_TEST_WSL_CONNECTION_PLUGIN_Waeri5tepheeSha2fae8)r8   extendshlexsplitr   getenvjoinr   )r(   cmdr   r   r   r   rT   s          r   _build_wsl_commandzConnection._build_wsl_command8  s    ??+=>*oom4k"Hz2H+-=>KK8,-TFEKK$%99OP::d##D!!r!   c                $   | j                  |      }t        t        |   |||       d}	 | j                  j                         j                  d       | j                  j                         j                         }t        j                  d| | j                  d      	       t        |d
      }d}	d}
d}	 |j                  |       | j                   r`| j                   j#                         rEd}d}|s|st        j%                  d       |j'                  |      }t        j%                  dt        |              |s8d|v r3t        | j                   j                  d            }t)        d| d      n^||z  }|j+                  d      D ]@  }| j                   j-                  |      rd} n!| j                   j/                  |      s>d} n |s|s|rR| j                   r;| j                   j                  d      }|j1                  t        |dz   d
             nt)        d      |	|z  }	|
|z  }
|rCt3        dt5        |      |      D ]  }|j7                  ||||z            |j9                          n|dk(  r|j9                          dj?                  |jA                  d|            }dj?                  |jC                  d|            }|jE                         }d|jG                  d      v r&t)        dt        | j                  d                   ||	|z   |	|z   fS # t        $ r0}t        |      }d}|r|d| z  }t        t        |            d}~ww xY w# t:        j<                  $ r t)        dt        |      z         w xY w)z, run a command on inside a WSL distribution in_datasudoablei      zFailed to open sessionz: NzEXEC r\   r_   r1   r2   r!   Fz&Waiting for Privilege Escalation inputz
chunk is: s   unknown userr   zuser z does not existTbecome_passr   z,A password is required but none was suppliedr   z0ssh timed out waiting for privilege escalation.
rbz'wsl.exe' is not recognizedutf-8z#wsl.exe not found in path of host: )$r   rQ   rF   exec_commandr   get_transportset_keepaliveopen_sessionr   r   r   r
   r<   rd   r8   r	   r   expect_promptdebugrecvr   
splitlinescheck_successcheck_password_promptsendallrangelensendshutdown_writesocketr   r   makefilemakefile_stderrrecv_exit_statusdecode)r(   r   r   r   bufsizechanr   text_er   no_prompt_outno_prompt_errbecome_outputpassword_promptbecome_successchunkn_become_userr   r   istdoutstderr
returncoderV   s                         r   r   zConnection.exec_commandI  sh    %%c*j$,S'H,U	;HH""$221588))+88:D 	eC5M(FGs#89/	mc"{{t{{88:"'!&)_MM"JK IIg.EMMJwu~.>"?@ *m;,5dkk6L6L]6[,\M".}o_/U"VV!!U*M !. 8 8 > ";;44T:-1N!![[>>tD.2O!"! *_0 #{{&*kk&<&<]&KXkD.@I^%_`*+YZZ!]2M!]2Mq#g,8 6AIIgaG456##%C##%
 $--g67$..tW=>**,

 )FMM',BB5gdoom>\6]5^_a a MF2MF4JKKW  	;QZF*CF8}$*9S>::	;z ~~ 	mRU\]jUkkll	ms2   AL( :DM$ 	M$ B8M$ (	M!1+MM!$+Nc                   t         j                  d| d| | j                  d             	 t        |d      5 }|j	                         }| j                  dj                  | j                  j                  d| j                  j                  d|       g      |d	
      \  }}}ddd       dk7  r[dj                  d      v r&t        dt        | j                  d                   t        t               dt        |             y# 1 sw Y   jxY w# t        $ r"}t        d| d| dt        |             d}~ww xY w)z& transfer a file from local to remote zPUT rm   r\   r_   r   r   -czcat > Fr   Nr   cat: not foundr   +cat not found in path of WSL distribution: r   r   z'error occurred while putting file from  to !
)r<   rd   r8   r   readr   r   _shell
executablequoter   r   r   r   )	r(   in_pathout_pathr   datar   r   r   r   s	            r   put_filezConnection.put_file  si    	d7)4z29WX	bgt$ $vvx-1->->HH..))F8**=>@ A !" .? .$*
FF$ Q#v}}W'==&Egdoo^pNqFrEstv v"v'r'&/):;= =	 $ $  	b9'$xjPST[\]T^S_`b b	bs0   D A+D%A(D DD 	E#E  Ec                   t         j                  d| d| | j                  d             	 | j                  dj	                  | j
                  j                  d| j
                  j                  d|       g      d	      \  }}}|d
k7  r[d|j                  d      v r&t        dt        | j                  d                   t        t        |       dt        |             t        |d      5 }|j                  |       ddd       y# 1 sw Y   yxY w# t        $ r"}t        d| d| dt        |             d}~ww xY w)z* save a remote file to the specified path zFETCH rm   r\   r_   r   r   zcat F)r   r   r   r   r   r   r   wbNz(error occurred while fetching file from r   r   )r<   rd   r8   r   r   r   r   r   r   r   r   r   r   r   )r(   r   r   r   r   r   r   r   s           r   
fetch_filezConnection.fetch_file  s]    	fWIT(44??=;YZ	c)-):):KK**DKK%%WI&679 : 	 *; * &J
 Q#v}}W'==&Egdoo^pNqFrEstv v"v'r'&/):;= =h%        	c:7)4zQTU\]^U_T`ac c	cs6   CD 3DD DD D 	E#E  Ec                ^    | j                   sy| j                          | j                          y)z reset the connection N)r   closer   )r(   s    r   resetzConnection.reset  s      

r!   c           	        | j                  d      r~| j                  d      rl| j                         r[t        j                  j	                  | j
                        }t        j                  j                  | j
                        }t        |       d}	 t               j                  ||| j                  d            5  | j                  j                          | j                  j                  j                  | j                  j                         t        j                  j                  | j
                        }t        j                  j                  | j
                        rGt        j                   | j
                        }|j"                  dz  }|j$                  }|j&                  }n*d}t        j(                         }t        j*                         }t-        j.                  |d      5 }	|	j0                  }t        j2                  ||       t        j4                  |||       | j7                  |       ddd       t        j8                  || j
                         ddd       |&tM        jN                  |      jQ                  d       	 | j                  jS                          d| _*        y# 1 sw Y   {xY w# 1 sw Y   _xY w# t:        $ r, t=        d	| j
                   d
| j                  d       d      t>        j@                  jB                  $ r}
tE        d|
jF                         d}
~
wtH        $ r}
t=        dtK        |
             d}
~
ww xY w# |&tM        jN                  |      jQ                  d       w w xY w)z terminate the connection r+   record_host_keysNlock_file_timeouti  i  F)dirdeletezwriting lock file for z ran in to the timeout of sr|   z,error occurred while writing SSH host keys!
T)
missing_ok)+r8   r   r   r   basenamer   dirnamer   r   	lock_filer   r   r@   update_system_host_keysexistsstatst_modest_uidst_gidgetuidgetgidtempfileNamedTemporaryFilerX   chmodchownr   renamer   r   r   r   r   r   r   r   r   pathlibPathunlinkr   r   )r(   lockfiler  tmp_keyfile_namekey_dirkey_statmodeuidgidtmp_keyfiler   s              r   r   zConnection.close  s    ??./DOODV4W\`\p\p\r
 ww''5Hggoodll3G'"#,KZ))(GT__M`=ab > HH224HH''..txx/I/IJ
 !ggoodll;Gww~~dll3#%774<<#8'//%7&oo&oo$ iik iik "44O CS^+6+;+;(!148!13<001AB	C II.==>T $/LL!1299T9J-C C1> >>  ~",T\\N:TUYUdUdexUyTzz{|~ ~$$33 N.1CAFF8/LMM R #CGAJ<PR RR $/LL!1299T9J 0sc   *K  D.J?.AJ39(J?!K 3J<	8J??KK AML33M?MMM *Nr%   )rR   r   rS   zio.TextIOWrapper | NonerT   t.AnyrU   r#  )rX   rI   rG   rH   )   )rg   intrG   zdict[str, t.Any])rG   rF   )rG   bool)r   rI   rG   rH   )r   rI   rG   rI   )NT)r   rI   r   zbytes | Noner   r&  rG   ztuple[int, bytes, bytes])r   rI   r   rI   rG   rH   )rG   rH   )rJ   rK   rL   rM   	transportrO   __annotations__r)   rY   rk   r   r   r   r   r   r   r   r   r   __classcell__)rV   s   @r   rF   rF     sZ    3'I#L*#S!,_BN4""WLrb.c,; r!   rF   )r   rI   r   rI   r   rI   rG   rI   )4
__future__r   DOCUMENTATIONEXAMPLESior   r  r   r   r  typingtansible.errorsr   r   r   Dansible_collections.community.general.plugins.module_utils._filelockr   r   +ansible.module_utils.common.text.convertersr	   r
   r   $ansible.module_utils.compat.paramikor   r   #ansible.module_utils.compat.versionr   ansible.playbook.play_contextr   ansible.plugins.connectionr   ansible.utils.displayr   ansible.utils.pathr   binasciir   
subprocessr   TYPE_CHECKINGr   paramiko.clientr   paramiko.pkeyr   objectr(  r<   r    r#   rF   r   r!   r   <module>r?     s    #vp3j 
 	      
 g T T N < 5 5 ) ,  # ??x-)"!'$'ItD$ )%=& %=V@  @ r!   