
    Vh                       d dl mZ dZd dlm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Zd dlZd dlZd dlZd dlZd dlmZ d dlmZmZmZmZ d dlmZ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*m+Z+  e(       Z, ejZ                  d      Z.dZ/da0 ejb                  d      Z2 G d de      Z3e,f	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ4	 	 	 	 ddZ5 G d de#      Z6y)    )annotationsa4  
    name: ssh
    short_description: connect via SSH client binary
    description:
        - This connection plugin allows Ansible to communicate to the target machines through normal SSH command line.
        - Ansible does not expose a channel to allow communication between the user and the SSH process to accept
          a password manually to decrypt an SSH key when using this connection plugin (which is the default). The
          use of C(ssh-agent) is highly recommended.
    author: ansible (@core)
    extends_documentation_fragment:
        - connection_pipelining
    version_added: historical
    notes:
        - This plugin is mostly a wrapper to the ``ssh`` CLI utility and the exact behavior of the options depends on this tool.
          This means that the documentation provided here is subject to be overridden by the CLI tool itself.
        - Many options default to V(None) here but that only means we do not override the SSH tool's defaults and/or configuration.
          For example, if you specify the port in this plugin it will override any C(Port) entry in your C(.ssh/config).
        - The ssh CLI tool uses return code 255 as a 'connection error', this can conflict with commands/tools that
          also return 255 as an error code and will look like an 'unreachable' condition or 'connection error' to this plugin.
    options:
      host:
          description: Hostname/IP to connect to.
          default: inventory_hostname
          type: string
          vars:
               - name: inventory_hostname
               - name: ansible_host
               - name: ansible_ssh_host
               - name: delegated_vars['ansible_host']
               - name: delegated_vars['ansible_ssh_host']
      host_key_checking:
          description: Determines if SSH should reject or not a connection after checking host keys.
          default: True
          type: boolean
          ini:
              - section: defaults
                key: 'host_key_checking'
              - section: ssh_connection
                key: 'host_key_checking'
                version_added: '2.5'
          env:
              - name: ANSIBLE_HOST_KEY_CHECKING
              - name: ANSIBLE_SSH_HOST_KEY_CHECKING
                version_added: '2.5'
          vars:
              - name: ansible_host_key_checking
                version_added: '2.5'
              - name: ansible_ssh_host_key_checking
                version_added: '2.5'
      password:
          description: Authentication password for the O(remote_user). Can be supplied as CLI option.
          type: string
          vars:
              - name: ansible_password
              - name: ansible_ssh_pass
              - name: ansible_ssh_password
      sshpass_prompt:
          description:
              - Password prompt that sshpass should search for. Supported by sshpass 1.06 and up.
              - Defaults to C(Enter PIN for) when pkcs11_provider is set.
          default: ''
          type: string
          ini:
              - section: 'ssh_connection'
                key: 'sshpass_prompt'
          env:
              - name: ANSIBLE_SSHPASS_PROMPT
          vars:
              - name: ansible_sshpass_prompt
          version_added: '2.10'
      ssh_args:
          description: Arguments to pass to all SSH CLI tools.
          default: '-C -o ControlMaster=auto -o ControlPersist=60s'
          type: string
          ini:
              - section: 'ssh_connection'
                key: 'ssh_args'
          env:
              - name: ANSIBLE_SSH_ARGS
          vars:
              - name: ansible_ssh_args
                version_added: '2.7'
      ssh_common_args:
          description: Common extra args for all SSH CLI tools.
          type: string
          ini:
              - section: 'ssh_connection'
                key: 'ssh_common_args'
                version_added: '2.7'
          env:
              - name: ANSIBLE_SSH_COMMON_ARGS
                version_added: '2.7'
          vars:
              - name: ansible_ssh_common_args
          cli:
              - name: ssh_common_args
          default: ''
      ssh_executable:
          default: ssh
          description:
            - This defines the location of the SSH binary. It defaults to V(ssh) which will use the first SSH binary available in $PATH.
            - This option is usually not required, it might be useful when access to system SSH is restricted,
              or when using SSH wrappers to connect to remote hosts.
          type: string
          env: [{name: ANSIBLE_SSH_EXECUTABLE}]
          ini:
          - {key: ssh_executable, section: ssh_connection}
          #const: ANSIBLE_SSH_EXECUTABLE
          version_added: "2.2"
          vars:
              - name: ansible_ssh_executable
                version_added: '2.7'
      sftp_executable:
          default: sftp
          description:
            - This defines the location of the sftp binary. It defaults to V(sftp) which will use the first binary available in $PATH.
          type: string
          env: [{name: ANSIBLE_SFTP_EXECUTABLE}]
          ini:
          - {key: sftp_executable, section: ssh_connection}
          version_added: "2.6"
          vars:
              - name: ansible_sftp_executable
                version_added: '2.7'
      scp_executable:
          default: scp
          description:
            - This defines the location of the scp binary. It defaults to V(scp) which will use the first binary available in $PATH.
          type: string
          env: [{name: ANSIBLE_SCP_EXECUTABLE}]
          ini:
          - {key: scp_executable, section: ssh_connection}
          version_added: "2.6"
          vars:
              - name: ansible_scp_executable
                version_added: '2.7'
      scp_extra_args:
          description: Extra exclusive to the C(scp) CLI
          type: string
          vars:
              - name: ansible_scp_extra_args
          env:
            - name: ANSIBLE_SCP_EXTRA_ARGS
              version_added: '2.7'
          ini:
            - key: scp_extra_args
              section: ssh_connection
              version_added: '2.7'
          cli:
            - name: scp_extra_args
          default: ''
      sftp_extra_args:
          description: Extra exclusive to the C(sftp) CLI
          type: string
          vars:
              - name: ansible_sftp_extra_args
          env:
            - name: ANSIBLE_SFTP_EXTRA_ARGS
              version_added: '2.7'
          ini:
            - key: sftp_extra_args
              section: ssh_connection
              version_added: '2.7'
          cli:
            - name: sftp_extra_args
          default: ''
      ssh_extra_args:
          description: Extra exclusive to the SSH CLI.
          type: string
          vars:
              - name: ansible_ssh_extra_args
          env:
            - name: ANSIBLE_SSH_EXTRA_ARGS
              version_added: '2.7'
          ini:
            - key: ssh_extra_args
              section: ssh_connection
              version_added: '2.7'
          cli:
            - name: ssh_extra_args
          default: ''
      reconnection_retries:
          description:
            - Number of attempts to connect.
            - Ansible retries connections only if it gets an SSH error with a return code of 255.
            - Any errors with return codes other than 255 indicate an issue with program execution.
          default: 0
          type: integer
          env:
            - name: ANSIBLE_SSH_RETRIES
          ini:
            - section: connection
              key: retries
            - section: ssh_connection
              key: retries
          vars:
            - name: ansible_ssh_retries
              version_added: '2.7'
      port:
          description: Remote port to connect to.
          type: int
          ini:
            - section: defaults
              key: remote_port
          env:
            - name: ANSIBLE_REMOTE_PORT
          vars:
            - name: ansible_port
            - name: ansible_ssh_port
          keyword:
            - name: port
      remote_user:
          description:
              - User name with which to login to the remote server, normally set by the remote_user keyword.
              - If no user is supplied, Ansible will let the SSH client binary choose the user as it normally.
          type: string
          ini:
            - section: defaults
              key: remote_user
          env:
            - name: ANSIBLE_REMOTE_USER
          vars:
            - name: ansible_user
            - name: ansible_ssh_user
          cli:
            - name: user
          keyword:
            - name: remote_user
      pipelining:
          env:
            - name: ANSIBLE_PIPELINING
            - name: ANSIBLE_SSH_PIPELINING
          ini:
            - section: defaults
              key: pipelining
            - section: connection
              key: pipelining
            - section: ssh_connection
              key: pipelining
          vars:
            - name: ansible_pipelining
            - name: ansible_ssh_pipelining

      private_key_file:
          description:
              - Path to private key file to use for authentication.
          type: string
          ini:
            - section: defaults
              key: private_key_file
          env:
            - name: ANSIBLE_PRIVATE_KEY_FILE
          vars:
            - name: ansible_private_key_file
            - name: ansible_ssh_private_key_file
          cli:
            - name: private_key_file
              option: '--private-key'

      control_path:
        description:
          - This is the location to save SSH's ControlPath sockets, it uses SSH's variable substitution.
          - Since 2.3, if null (default), ansible will generate a unique hash. Use ``%(directory)s`` to indicate where to use the control dir path setting.
          - Before 2.3 it defaulted to ``control_path=%(directory)s/ansible-ssh-%%h-%%p-%%r``.
          - Be aware that this setting is ignored if C(-o ControlPath) is set in ssh args.
        type: string
        env:
          - name: ANSIBLE_SSH_CONTROL_PATH
        ini:
          - key: control_path
            section: ssh_connection
        vars:
          - name: ansible_control_path
            version_added: '2.7'
      control_path_dir:
        default: ~/.ansible/cp
        description:
          - This sets the directory to use for ssh control path if the control path setting is null.
          - Also, provides the ``%(directory)s`` variable for the control path setting.
        type: string
        env:
          - name: ANSIBLE_SSH_CONTROL_PATH_DIR
        ini:
          - section: ssh_connection
            key: control_path_dir
        vars:
          - name: ansible_control_path_dir
            version_added: '2.7'
      sftp_batch_mode:
        default: true
        description: 'TODO: write it'
        env: [{name: ANSIBLE_SFTP_BATCH_MODE}]
        ini:
        - {key: sftp_batch_mode, section: ssh_connection}
        type: bool
        vars:
          - name: ansible_sftp_batch_mode
            version_added: '2.7'
      ssh_transfer_method:
        description: Preferred method to use when transferring files over ssh
        choices:
              sftp: This is the most reliable way to copy things with SSH.
              scp: Deprecated in OpenSSH. For OpenSSH >=9.0 you must add an additional option to enable scp C(scp_extra_args="-O").
              piped: Creates an SSH pipe with C(dd) on either side to copy the data.
              smart: Tries each method in order (sftp > scp > piped), until one succeeds or they all fail.
        default: smart
        type: string
        env: [{name: ANSIBLE_SSH_TRANSFER_METHOD}]
        ini:
            - {key: transfer_method, section: ssh_connection}
        vars:
            - name: ansible_ssh_transfer_method
              version_added: '2.12'
      use_tty:
        version_added: '2.5'
        default: true
        description: add -tt to ssh commands to force tty allocation.
        env: [{name: ANSIBLE_SSH_USETTY}]
        ini:
        - {key: usetty, section: ssh_connection}
        type: bool
        vars:
          - name: ansible_ssh_use_tty
            version_added: '2.7'
      timeout:
        default: 10
        description:
            - This is the default amount of time we will wait while establishing an SSH connection.
            - It also controls how long we can wait to access reading the connection once established (select on the socket).
        env:
            - name: ANSIBLE_TIMEOUT
            - name: ANSIBLE_SSH_TIMEOUT
              version_added: '2.11'
        ini:
            - key: timeout
              section: defaults
            - key: timeout
              section: ssh_connection
              version_added: '2.11'
        vars:
          - name: ansible_ssh_timeout
            version_added: '2.11'
        cli:
          - name: timeout
        type: integer
      pkcs11_provider:
        version_added: '2.12'
        default: ""
        type: string
        description:
          - "PKCS11 SmartCard provider such as opensc, example: /usr/local/lib/opensc-pkcs11.so"
          - Requires sshpass version 1.06+, sshpass must support the -P option.
        env: [{name: ANSIBLE_PKCS11_PROVIDER}]
        ini:
          - {key: pkcs11_provider, section: ssh_connection}
        vars:
          - name: ansible_ssh_pkcs11_provider
Nwraps)AnsibleAuthenticationFailureAnsibleConnectionFailureAnsibleErrorAnsibleFileNotFound)PY3	text_typebinary_type)to_bytes	to_nativeto_text)ConnectionBaseBUFSIZE)_replace_stderr_clixml)Display)unfrackpathmakedirs_safeP)s"   Traceback (most recent call last):s   PHP Parse error:s   chmod: invalid modes-   chmod: A flag or octal number is not correct.z^debug\d+: .*c                      e Zd ZdZy)$AnsibleControlPersistBrokenPipeErrorz ControlPersist broken pipe N)__name__
__module____qualname____doc__     N/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/connection/ssh.pyr   r     s    &r   r   c                   |dk(  r|d   dk(  rmdj                  |       }| dk  rd}|rdj                  |      }t        |      dj                  |t        |d         j                               }t        |      |d   d	v red
}|rdj                  |      }nOt        |d         j                         }d|v rd}t	        dj                  ||            dj                  ||      }|d   dk(  rxd}t
        D ]  }	|	|d   v s|	|d   v sd} n |rWd}|rdj                  |      }t        |      dj                  |t        |d         j                               }t        |      d|d   cxk  rdk  rYn y d}|rdj                  |      }n,dj                  |t        |d         j                               }|j                  ||       y y )N   sshpassr      z_Invalid/incorrect username/password. Skipping remaining {0} retries to prevent account lockout:zInvalid/incorrect password:z"{0} <error censored due to no log>z{0} {1}   )   r#            zsshpass error:zsshpass: invalid option -- 'P'zInstalled sshpass version does not support customized password prompts. Upgrade sshpass to use sshpass_prompt, or otherwise switch to ssh keys.   Tr$   Fz&Failed to connect to the host via ssh:   host)	formatr   rstripr   r   b_NOT_SSH_ERRORSr   r   vvv)
remaining_retriescommandreturn_tupleno_logr+   displaymsgdetails	SSH_ERROR	signatures
             r   _handle_errorr9     s    *?aszz  |M  NC A%3:AA#F /s33  &&sIl1o,F,M,M,OP.s33
 !_/"C:AA#F#LO4;;=3w>hG&y'7'7W'EFF&&sG4A#	) 	ILO+yLO/K!			 :C:AA#F +3//  &&sIl1o,F,M,M,OP*3// 	LO"s"77>>sCC##Ca)A)H)H)JKCCd# #r   c                0     t               d fd       }|S )a+  
    Decorator to retry ssh/scp/sftp in the case of a connection failure

    Will retry if:
    * an exception is caught
    * ssh returns 255
    Will not retry if
    * sshpass returns 5 (invalid password, to prevent account lockouts)
    * remaining_tries is < 2
    * retries limit reached
    c                   t        | j                  d            dz   }dt        |d         z  }| j                  d      xs | j                  j                  }t        |      D ]'  }t        j                  t        t           |d         }|dk7  rL|rJt        |t              r:t        j                         | _        dt        | j                  d   dd	      z   |d<   	 	  | g|i |}| j                  j                  r(t         j#                  d
|d   z  | j$                         n*t         j#                  t'        |      | j$                         ||z
  dz
  }	t+        |	|d   || j                  j                  | j$                          |S  S # t(        $ r t        j                  t        t           |d         }|rJt        |t              r:t        j                         | _        dt        | j                  d   dd	      z   |d<   t         j#                  d        | g|i |}Y w xY w# t,        $ r  t.        t0        f$ r}
||dz
  k(  r d|z  dz
  }|dkD  rd}t        |
t.              rd|dz   ||fz  }nd|dz   t        |
      ||fz  }t         j3                  || j$                         t5        j6                  |       Y d }
~
jd }
~
ww xY w)Nreconnection_retriesr$   z%s...r   password   -d
simplereprsurrogate_or_strict	nonstringerrorsz/rc=%s, stdout and stderr censored due to no logr*   z.RETRYING BECAUSE OF CONTROLPERSIST BROKEN PIPEr#      zPssh_retry: attempt: %d, ssh return code is 255. cmd (%s), pausing for %d secondszRssh_retry: attempt: %d, caught exception(%s) from cmd (%s), pausing for %d seconds)int
get_optionr   _play_contextr=   rangetcastlistbytes
isinstanceospipesshpass_piper   r3   r4   r/   r+   strr   r9   r   r   	Exceptionvvtimesleep)selfargskwargsremaining_triescmd_summaryconn_passwordattemptcmdr2   r0   epauser5   funcs                r   wrappedz_ssh_retry.<locals>.wrapped  s   doo.DEFJa!11
3Rt7I7I7R7R_- 8	G&&ed1g.C!|*S$2G$&GGI!$*;*;A*>,_t!uuA1?#'#>t#>v#>L))00$VYefgYh$hosoxoxyC$5DIIF %4g$=$A!/QtGYGYG`G`bfbkbkl6 u8	t Q = ?&&ed1g6C$C)>,.GGI)!&$2C2CA2FR^g|)}!}AKK QR#'#>t#>v#>L?  0 ,i8 o11L1,Erz "!!%=>qu|  @A  vA  CN  PU  uV  V 9<CaKQRU`bg;h i JJsJ3JJu%%s9   A4F8H1BH.+H1-H..H11K	A?KK)rV   
ConnectionrW   zP.argsrX   zP.kwargsreturntuple[int, bytes, bytes]r   )r`   ra   s   ` r   
_ssh_retryre     s#     4[> >~ Nr   c                  &    e Zd ZdZdZdZd fdZddZe	 	 d	 	 	 	 	 	 	 	 	 	 	 dd       Z	edd       Z
edd       Zdd	Zdd
ZddZed d       Zd!dZd"d#dZed"d#d       Zed$d       Zd%dZd&d' fdZd( fdZd( fdZd)dZd)dZ xZS )*rb   z ssh based connections sshTc                R   t        t        | 
  |i | | j                  j                  | _        | j                  j                  | _        | j                  j                  | _        d | _	        d | _
        t        | j                  dd      rd| _        d| _        d| _        d| _        y y )N_IS_WINDOWSFT)z.ps1z.exe )superrb   __init__rG   remote_addrr+   portremote_userusercontrol_pathcontrol_path_dirgetattr_shellhas_native_asyncalways_pipeline_modules!module_implementation_preferencesallow_executable)rV   rW   rX   	__class__s      r   rl   zConnection.__init__7  s    j$($9&9 &&22	&&++	&&22	(,,0
 4;;u5$(D!+/D(5ID2$)D!	 6r   c                    | S Nr   rV   s    r   _connectzConnection._connectN  s    r   c                    | d|d|}|r|d|z  z  }|r|dt        |      z  z  }t        j                         }|j                  t	        |             |j                         }d|dd z   }|S )z7Make a hash for the controlpath based on con attributes-z-%sz%(directory)s/N
   )r   hashlibsha1updater   	hexdigest)	r+   rn   rp   
connectionpidpstringmdigestcpaths	            r   _create_control_pathzConnection._create_control_pathQ  st     !%dD1uz))Guws|++GLLN	'"# 6#2;.r   c                     t         ]	 t        j                  dgt        j                  t        j                  t        j                        } | j	                          da t         S t         S # t
        $ r
 da Y t         S w xY w)NsshpassstdinstdoutstderrTF)SSHPASS_AVAILABLE
subprocessPopenPIPEcommunicateOSErrorps    r   _sshpass_availablezConnection._sshpass_availablee  ss     $*$$i[
PZP_P_hrhwhwx$(! !     *$)!  *s   AA* *A=<A=c                J    d}d}d | D        D ]  }d|v rd}
d|v sd} ||fS )a  
        Takes a command array and scans it for ControlPersist and ControlPath
        settings and returns two booleans indicating whether either was found.
        This could be smarter, e.g. returning false if ControlPersist is 'no',
        but for now we do it simple way.
        Fc              3  <   K   | ]  }|j                           y wr{   )lower.0as     r   	<genexpr>z3Connection._persistence_controls.<locals>.<genexpr>  s     3Aaggi3s   s   controlpersistTs   controlpathr   )	b_commandcontrolpersistcontrolpathb_args       r   _persistence_controlsz Connection._persistence_controlsw  sI     33 	#E E)!%5("		# {**r   c           	         t         j                  d|ddj                  d |D              d| j                         ||z  }y)a  
        Adds arguments to the ssh command and displays a caller-supplied explanation of why.

        :arg b_command: A list containing the command to add the new arguments to.
            This list will be modified by this method.
        :arg b_args: An iterable of new arguments to add.  This iterable is used
            more than once so it must be persistent (ie: a list is okay but a
            StringIO would not)
        :arg explanation: A text string containing explaining why the arguments
            were added.  It will be displayed with a high enough verbosity.
        .. note:: This function does its work via side-effect.  The b_command list has the new arguments appended.
        zSSH: z: (z)(c              3  2   K   | ]  }t        |        y wr{   )r   r   s     r   r   z'Connection._add_args.<locals>.<genexpr>  s     @\PQ@\s   )r*   N)r4   vvvvvjoinr+   )rV   r   b_argsexplanations       r   	_add_argszConnection._add_args  s:     	+tyy@\U[@\7\]dhdmdmnV	r   c                
   g }| j                  d      xs | j                  j                  }| j                  d      }|s|r| j                         st	        d      |s|rt	        d      t        j                         | _        |ddt        | j                  d   dd	
      z   gz  }| j                  d      }|s|rd}|r|dt        |d	      gz  }|t        |d	      gz  }|r)|r'| j                  |dddddddt        d|z        fd       |dk(  r1| j                  d      r |rddg}| j                  ||d       |ddgz  }t        j                  r%|j                  ddt        j                  z  z          | j                  d      }	|	r<| j                  |	      D 
cg c]  }
t        |
d	       }}
| j                  ||d       | j                  d      du rd }| j                  ||d!       | j                  d"      | _        | j                  0dd#t        | j                  dd	
      z   f}| j                  ||d$       | j                  d%      }|rEdd&t        t
        j                  j!                  |      d	      z   d'z   f}| j                  ||d(       |s| j                  |d)d*       | j                  d+      | _        | j"                  r-| j                  |dd,t        | j"                  d	      z  fd-       | j                  d.      }| j                  |dd/t        |d	d0      z   fd1       d2d3j%                  |      fD ]U  }| j                  |      }|| j                  |      D 
cg c]  }
t        |
d	       }}
| j                  ||d4|z         W | j'                  |      \  }}|rd5| _        |s| j                  d6      | _        t-        | j*                        }t        |d	      }t/        |d7       t        j0                  |t
        j2                        st	        d8t5        |      z        | j                  d9      | _        | j6                  s6| j9                  | j:                  | j                  | j"                        | _        dd:t        | j6                  t=        |;      z  d	      z  f}| j                  ||d<       |r||D 
cg c]  }
t        |
       c}
z  }|S c c}
w c c}
w c c}
w )=a  
        Takes a executable (ssh, scp, sftp or wrapper) and optional extra arguments and returns the remote command
        wrapped in local ssh shell commands and ready for execution.

        :arg binary: actual executable to use to execute command.
        :arg subsystem: type of executable provided, ssh/sftp/scp, needed because wrappers for ssh might have diff names.
        :arg other_args: dict of, value pairs passed as arguments to the ssh binary

        r=   pkcs11_providerzhto use the 'ssh' connection type with passwords or pkcs11_provider, you must install the sshpass programz6to use pkcs11_provider you must specify a password/pinr!   r>   r   r?   r@   rA   sshpass_promptzEnter PIN for s   -PrC      -o   KbdInteractiveAuthentication=nos"   PreferredAuthentications=publickey   PasswordAuthentication=nozPKCS11Provider=%szEnable pkcs11sftpsftp_batch_modes   BatchMode=nozdisable batch mode for sshpasss   -b   -   vssh_argszansible.cfg set ssh_argshost_key_checkingF)r   s   StrictHostKeyChecking=noz4ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabledrn   s   Port=z0ANSIBLE_REMOTE_PORT/remote_port/ansible_port setprivate_key_files   IdentityFile="   "zJANSIBLE_PRIVATE_KEY_FILE/private_key_file/ansible_ssh_private_key_file set)r   r   r   sI   PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickeyr   r   z-ansible_password/ansible_ssh_password not setro   s	   User="%s"z8ANSIBLE_REMOTE_USER/remote_user/ansible_user/user/-u settimeouts   ConnectTimeout=)rC   rB   zANSIBLE_TIMEOUT/timeout setssh_common_argsz{0}_extra_argszSet %sTrr   i  zCannot write to ControlPath %srq   s   ControlPath="%s")	directoryz,found only ControlPersist; added ControlPath)rF   rG   r=   r   r   rN   rO   rP   r   r   r4   	verbosityappend_split_ssh_argsrn   path
expanduserrp   r,   r   _persistentrr   r   r   accessW_OKr   rq   r   r+   dict)rV   binary	subsystem
other_argsr   r[   r   password_promptr   r   r   keyr   optattrr   r   cpdirb_cpdirs                      r   _build_commandzConnection._build_command  s    	
3Rt7I7I7R7R //*;<O**,"  $N  O  O _"#[\\ "	D*eht7H7H7KWc  mB  /C  'C  D  DI"oo.>?O""2eXoF[%\]]	hv.CDEE	 _NN9!#E!#H!#?!8,@?,R#SU ,- 4??3D#E1y&2ST%&ITTG,=,=%=>? ??:.**846Ahq)>? 6F 6NN9f.IJ ??./589FNN9f.efOOF+	99 Xl[p(qqrFNN9f.aboo01."'':L:LS:QZo1ppswwxFNN9f.{|NN 
 A OOM2	99NNx		BW'XXYK //),&'BWco)ppq*	
 '(9(@(@(KL 	CC??3'DMQMaMabfMgh(1-BChhy&)c/B		C '+&@&@&K##D(,8J(K%#D$9$9:"51FG gu-yy"''2&'G)TYJZ'Z[[$(OON$C!(((,(A(A						)D%
  !4x@Q@QTXchTi@i  sH  8I  "I  Jy&2ab z:!(1+::Ik6d iB ;s   S20S7S<c           	        t         j                  d       	 |j                  t        |             |j	                          t         j                  dt        |      z         y# t
        t        f$ rb}t        j                  d       |j                          t        |dd      &t        d| j                  dt        |      |      Y d}~d}~ww xY w)	z
        Writes initial data to the stdin filehandle of the subprocess and closes
        it. (The handle must be closed; otherwise, for example, "sftp -b -" will
        just hang forever waiting for more commands.)
        zSending initial datagMbP?
returncodeN'Data could not be sent to remote host "0". Make sure this host can be reached over ssh: )orig_exczSent initial data (%d bytes))r4   debugwriter   closer   IOErrorrT   rU   pollrs   r   r+   r   len)rV   fhin_datassh_processr^   s        r   _send_initial_datazConnection._send_initial_data8  s     	-.	HHXg&'HHJ 	5GDE ! 		 JJu{L$7?.&*ii1?IJ  @		s   *A# #C2ACCc                P    	 | j                          y# t        t        f$ r Y yw xY w)z& Terminate a process, ignoring errors N)	terminater   r   r   s    r   _terminate_processzConnection._terminate_processR  s'    	KKM! 		s    %%c           
        g }|j                  d      D ]  }t        |      j                  d      }d}t        j	                  |      rn_| j
                  j                         rL| j
                  j                  |      r1t        j                  d|d|d|d       d| j                  d<   d}n| j
                  j                  rL| j
                  j                  |      r1t        j                  d	|d|d|d       d| j                  d
<   d}n|rJ| j
                  j                  |      r/t        j                  d|d|d|d       d| j                  d<   nK|rI| j
                  j                  |      r.t        j                  d|d|d|d       d| j                  d<   |r|j                  |        d}	|r|d   j!                  d      s
|d   }	|dd }dj#                  |      |	fS )ai  
        Takes a string, extracts complete lines from it, tests to see if they
        are a prompt, error message, etc., and sets appropriate flags in self.
        Prompt and success lines are removed.

        Returns the processed (i.e. possibly-edited) output and the unprocessed
        remainder (to be processed with the next chunk) as strings.
        Tz
Fzbecome_prompt: (source=z, state=z): ''become_promptzbecome_success: (source=become_successzbecome_error: (source=become_errorzbecome_nopasswd_error: (source=become_nopasswd_errorr      
N)
splitlinesr   r-   	SSH_DEBUGmatchbecomeexpect_promptcheck_password_promptr4   r   _flagssuccesscheck_successcheck_incorrect_passwordcheck_missing_passwordr   endswithr   )
rV   sourcestateb_chunksudoableoutputb_linedisplay_linesuppress_output	remainders
             r   _examine_outputzConnection._examine_output\  s    ((. 	&F"6?11&9L#O |,**,1R1RSY1ZvW\^jkl/3O,"&$$)B)B6)JPVX]_klm04,-"&dkkBB6JfV[]ijk.2N+dkk@@HW]_dfrst7;34"f%1	&> 	&*--e4r
ICR[Fxx**r   c           	        dj                  d |D              }t        j                  dj                  |      | j                         d}t        |t        t        f      rt        |      }nt        t        t        |            }| j                  d      xs | j                  j                  }|s	 t        j                         \  }}	t         rC|rAt#        j$                  ||	t"        j&                  t"        j&                  | j(                        }n5t#        j$                  ||	t"        j&                  t"        j&                        }t+        j,                  |d	d
      }
t+        j.                  |	       |s	 t         rQ|rOt#        j$                  |t"        j&                  t"        j&                  t"        j&                  | j(                        }nCt#        j$                  |t"        j&                  t"        j&                  t"        j&                        }|j4                  }
|rtt+        j.                  | j(                  d
          	 t+        j:                  | j(                  d   t        |      dz          t+        j.                  | j(                  d          g d}|jC                  d      }t        | j                  d            |v r|rtE        | jF                  dd      }|r9|jC                  d      }t        jI                  d||   dtK        |             nn| jF                  rb| jF                  jL                  rL|jC                  d      }t        jI                  d||   dtK        | jF                  jL                               dx}}dx}}tO        dddd      | _(        d| j                  d      z   }|jR                  |jT                  fD ]Z  }tW        jV                  |tV        jX                  tW        jV                  |tV        jZ                        t*        j\                  z         \ t_        j`                         }|jc                  |jR                  t^        jd                         |jc                  |jT                  t^        jd                         ||   dk(  r|r| jg                  
||       |dz  }	 	 |jA                         }|ji                  |      }|sB||jC                  d      k  r.|n| jk                  |       t7        d|t9        |      fz        |D ]  \  }}|jl                  |jR                  k(  rg|jR                  jo                         }|dk(  r|jq                  |jR                         d}||z  }t        jI                  d|dtK        |      d       |jl                  |jT                  k(  s|jT                  jo                         }|dk(  r|jq                  |jT                         ||z  }t        jI                  d|dtK        |      d        ||jC                  d      k  rG|r!| js                  d ||   ||      \  }}||z  }|}|r0| js                  d!||   ||      \  }}||z  }|}n||z  }||z  }dx}}||   dk(  r| jP                  d"   rt        jI                  d#       | jF                  j                  d$| j                  %      }
j;                  t        |d&'      dz          |
ju                          d| jP                  d"<   |dz  }n| jP                  d(   r|dz  }||   dk(  rl| jP                  d(   r+t        j                  d)       d| jP                  d(<   |dz  }n2| jP                  d*   rWt        j                  d+       | jk                  |       d| jP                  d*<   t7        d,| jF                  jv                  z        | jP                  d-   rWt        j                  d.       | jk                  |       d| jP                  d-<   t7        d/| jF                  jv                  z        | jP                  d"   rWt        j                  d0       | jk                  |       d| jP                  d"<   t7        d,| jF                  jv                  z        ||   dk(  r|r| jg                  
||       |dz  }||jy                         r|sn'd
}4|jy                         s|j{                          nV|j/                          
j/                          |jR                  j/                          |jT                  j/                          | j                  d1      r"|d
   d2k(  r|j|                  d3k(  rt7        d4      d5|v xs d6|v }|j|                  d
k7  r|rt7        d7      d8|v }|j|                  d9k(  r:t9        |      } |rt        d:| z        |r|rt        d;| j                  d<|       |j|                  ||fS # t0        t2        f$ r d}Y w xY w# t0        t2        f$ r}t7        dt9        |      z        d}~ww xY w# t0        $ r9}|j<                  t<        j>                  k7  s|jA                          Y d}~(d}~ww xY w# |j/                          
j/                          |jR                  j/                          |jT                  j/                          w xY w)=zL
        Starts the command and communicates with it until it ends.
         c              3  X   K   | ]"  }t        j                  t        |             $ y wr{   )shlexquoter   )r   cs     r   r   z'Connection._bare_run.<locals>.<genexpr>  s     EAGAJ 7Es   (*zSSH: EXEC {0}r*   Nr=   )r   r   r   pass_fdsr   wbr   z=Unable to execute ssh command line on a controller due to: %sr$   r   )awaiting_promptawaiting_escalationready_to_sendawaiting_exitr  ssh_executablepromptr  zInitial state: : r  r   F)r   r   r   r   r#   r   z9Timeout (%ds) waiting for privilege escalation prompt: %szstdout chunk (state=z):
>>>z<<<
zstderr chunk (state=r   r   r   z-Sending become_password in response to promptbecome_pass)playcontextr@   r   r   zEscalation succeededr   zEscalation failedzIncorrect %s passwordr   zEscalation requires passwordzMissing %s passwordzEscalation prompt repeatedr   r!   r'   zUsing a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host.s(   Bad configuration option: ControlPersists,   unknown configuration option: ControlPersistzusing -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ssh_args in [ssh_connection] section of the config file) before running agains4   mux_client_hello_exchange: write packet: Broken piper(   z@Data could not be sent because of ControlPersist broken pipe: %sr   r   )Ar   r4   r/   r,   r+   rM   r   r   r   rK   maprF   rG   r=   ptyopenptyr
   r   r   r   rP   rN   fdopenr   r   r   r   r   r   r   errnoEPIPEr   indexrs   r   r   r   r   r   r   r   r   fcntlF_SETFLF_GETFL
O_NONBLOCK	selectorsDefaultSelectorregister
EVENT_READr   selectr   fileobjread
unregisterr  flushnameget_mapwaitr   r   r   )!rV   r]   r   r   checkrcdisplay_cmdr   r[   masterslaver   r^   statesr   r  b_stdoutb_stderrb_tmp_stdoutb_tmp_stderrr   fdselectorr   eventsr   eventr   b_outputb_unprocessedr  controlpersisterrorcontrolpersist_broken_pipe
additionals!                                    r   	_bare_runzConnection._bare_run  s	    iiEEE$++K8tyyI cI{343-Cs8S)*C
3Rt7I7I7R7R #="((E*//ZdZiZitx  uF  uF  GA"((E*//ZdZiZijA		&$2 
s="((JOOJOO0:$J[J[]A #((JOOJOO0:AA HHT&&q)***1-x/F/NO
 HHT&&q)*
 _-DOO$456#=(T[[(D9F %67&-QWYZ!4!4 %:;&-QUQ\Q\QdQdIefg "!8&))|e
 dooi0088QXX& 	[BKKEMM5;;r5==+IBMM+YZ	[
 ,,.!((I$8$89!((I$8$89 %=O+##E7A6QJEN	vvx!1 -B CC  +!//2*+fjqs|  ~F  tG  jH  ,H  I  I
 #) jJC{{ahh."#((--/"c>$//9 '(G$/QVX_`gXh&ij0"#((--/"c>$//9$/PUW^_fWg&hi-j8 6<<88#262F2FxQWX]Q^`lnv2w/- H,'4#262F2FxQWX]Q^`lnv2w/- H,'4,H,H255L< %=$55{{?3&VW&*kk&<&<]X\XjXj&<&kH[AV$WZ_$_` 7<O4
%56

 %=$99{{#34$;<8=$45
^4$89//26;N3*+BT[[EUEU+UVV%<=$CD//2?D$;<*+@4;;CSCS+STT_5  $AB//27<O4*+BT[[EUEU+UVV %=O3//wBQJE
 ##++-V  G "))+FFHI P NN KKMHHNNHHNN??./1v#(9" $~   JXU  U  ZI  MU  ZU<<1!4  s t t
 &]`h%h"<<3"8,J):;}  AK  <K  L  LW.26))Z0I J J h11G W%  W% s"#benopeq#qrrs  77ekk)QVVX-= .>\ NN KKMHHNNHHNNsY   2Ch 6B&h- /i 5Dj  >Mj  h*)h*-i<ii	j$.jj Ak6c                ,    | j                  ||||      S )z=Wrapper around _bare_run that retries the connection
        )r   r,  )r>  )rV   r]   r   r   r,  s        r   _runzConnection._run  s     ~~c7Xw~OOr   c                   d| j                   z  }g d}t        | j                  dd      r|j                  d       g }| j	                  d      }|dk(  r|}n|g}|D ]  }d x}	x}
}|dk(  r| j                  | j	                  d	      dt        |            }d
j                  |t        j                  |      t        j                  |            }t        |d      }| j                  ||d      \  }	}
}n|dk(  r| j	                  d      }|dk(  r>| j                  |ddj                  || j                  j                  |            |      }n=| j                  |d|dj                  || j                  j                  |                  }d }| j                  ||d      \  }	}
}n|dk(  r|dk(  rl| j                  d| j                  j                  |      dt        d      \  }	}
}t        t        |d      d      5 }|j                  |
       d d d        nft        t        |d      d      5 }t        |j                         d      }d d d        sd}nd}| j                  d|dt        ||d      \  }	}
}|	dk(  r|	|
|fc S t!        |      dkD  sCt"        j%                  |d|d        t"        j'                  d!t)        |
      z         t"        j'                  d!t)        |      z          	d"k(  rt+        d#d$t-                    t/        d%t-        |      d&t-        |      d't-        
      d(t-                    # 1 sw Y   xY w# 1 sw Y   xY w))Nz[%s])r   scppipedri   FrC  ssh_transfer_methodsmartr   sftp_executablez{0} {1} {2}
passthru)rB   )r,  rB  scp_executablegetz{0}:{1}zdd if=z bs=r   r@   r   zwb+rbz count=0rj   zdd of=r   r   r   r$   z transfer mechanism failed on z1. Use ANSIBLE_DEBUG=1 to see detailed informationz%sr(   z"Failed to connect to the host via r  zfailed to transfer file to r  z:

)r+   rs   rt   removerF   r   r   r,   r  r  r>  exec_commandr   openr   r&  r   r4   warningr   r   r   r   r   )rV   in_pathout_pathsftp_actionr+   smart_methodsmethodsrD  methodr   r   r   r]   r   rB  out_filefcounts                     r   _file_transport_commandz"Connection._file_transport_command  s    		!0 4;;u5  )  #oo.CD')#G*+G (	;F+//J/&))$//:K*LfV^_cVde*11+u{{7?SUZU`U`aiUjk"7jA/3~~c7TY~/Z,VV5oo&67%'--c5*:K:KDRVR]R]RcRcdkRl:mowxC--c5':CTCTUY[_[f[f[l[lmu[vCwxC/3~~c7TY~/Z,VV7"%' 483D3DY]YdYdYjYjkrYsu|E}  IN3D  4O0Zhx8MNPUV /Zb v./ / hw7LMtT KXY"*1668z"JK" * "373D3D[celnsEt  F  QV3D  4W0Z Q"FF33 w<!#OO  E  GK  %L  MMM%'&/"9:MM%'&/"9:Q(	;T *Y_ajkqar+stt )' 2Ih4GSYIZ\efl\m o p p1/ /K Ks   M4M%M"	%M/	c                b    d}t        j                  d|      rd}||j                  dd      S )zA converts a Windows path to one that's supported by SFTP and SCP rj   z^\w{1}:/\)rer   replace)rV   r   prefixs      r   _escape_win_pathzConnection._escape_win_path  s4     88J%F  dC!899r   c                d   t         t        |   |||       | j                  d      xs | j                  j
                  | _        t        j                  dj                  | j                        | j                         t        | j                  dd      rd}| j                  d      }| j                  d      }|s|r|rd	| j                  |f}n| j                  |f} | j                  |d
g| }| j                  |||      \  }}}	t        | j                  dd      rt        |	      }	|||	fS )z" run a command on the remote host rL  r+   z&ESTABLISH SSH CONNECTION FOR USER: {0}r*   ri   Fr  use_ttyz-ttrg   rJ  )rk   rb   rO  rF   rG   rm   r+   r4   r/   r,   rp   rs   rt   r   r@  r   )rV   r]   r   r   r  rd  rW   r   r   r   ry   s             r   rO  zConnection.exec_command  s    	j$,S'H,UOOF+Mt/A/A/M/M	=DDTYYOVZV_V_`4;;u5 H )9: //), 8499c*DIIs#D!d!!.%?$?'+yygy'Q$VV 4;;u5+F3FFF++r   c                   t         t        |   ||       | j                  d      xs | j                  j
                  | _        t        j                  dj                  ||      | j                         t        j                  j                  t        |d            s#t        dj                  t        |                  t!        | j"                  dd      r| j%                  |      }| j'                  ||d	      S )
z& transfer a file from local to remote r+   zPUT {0} TO {1}r*   r@   r   z"file or module does not exist: {0}ri   Fput)rk   rb   put_filerF   rG   rm   r+   r4   r/   r,   rN   r   existsr   r	   r   rs   rt   rb  r[  rV   rR  rS  ry   s      r   rg  zConnection.put_file7  s     	j$((;OOF+Mt/A/A/M/M	%,,Wh?diiPww~~hw7LMN%&J&Q&QR[\cRd&eff4;;u5,,X6H++GXuEEr   c                `   t         t        |   ||       | j                  d      xs | j                  j
                  | _        t        j                  dj                  ||      | j                         t        | j                  dd      r| j                  |      }| j                  ||d      S )z# fetch a file from remote to local r+   zFETCH {0} TO {1}r*   ri   FrI  )rk   rb   
fetch_filerF   rG   rm   r+   r4   r/   r,   rs   rt   rb  r[  ri  s      r   rk  zConnection.fetch_fileG  s     	j$*7H=OOF+Mt/A/A/M/M	'..wA		R 4;;u5++G4G++GXuEEr   c                   d}| j                  d      xs | j                  j                  | _        | j	                  | j                  d      ddd| j                        }t
        j                  dt        |      z         t        j                  |t        j                  t        j                  t        j                        }|j                         \  }}|j                         }|d	k7  r"t
        j                  d
t        |      z         nd}|r| j	                  | j                  d      ddd| j                        }t
        j                  dt        |      z         t        j                  |t        j                  t        j                  t        j                        }|j                         \  }}|j                         }|d	k7  r!t
        j                  dt        |      z         | j                          y )NFr+   r  rg   z-Ocheckzsending connection check: %sr   r   zNo connection to reset: %sTstopzsending connection stop: %szFailed to reset connection:%s)rF   rG   rm   r+   r   r4   r/   r   r   r   r   r   r+  rQ  r   )rV   	run_resetr]   r   r   r   status_codes          r   resetzConnection.resetV  sv   	OOF+Mt/A/A/M/M	
 !!$//2B"CUDRY[_[d[de3gclBCS

XbXgXghffh!KK5GHI%%doo6F&GPTV\^b^g^ghCKK6EF  JOOJOO\f\k\klA]]_NFF&&(Ka @76? RS

r   c                    d| _         y )NF)
_connectedr|   s    r   r   zConnection.closes  s	    r   )rW   t.AnyrX   rt  rc   None)rc   rb   )NN)r+   
str | Nonern   
int | Nonerp   rv  r   zConnectionBase | Noner   rw  rc   rQ   )rc   bool)r   list[bytes]rc   ztuple[bool, bool])r   ry  r   zt.Iterable[bytes]r   rQ   rc   ru  )r   rQ   r   rQ   r   zbytes | strrc   ry  )r   z	io.IOBaser   rL   r   subprocess.Popenrc   ru  )r   rz  rc   ru  )
r   rQ   r   rQ   r   rL   r   rx  rc   ztuple[bytes, bytes])TT)
r]   ry  r   bytes | Noner   rx  r,  rx  rc   rd   )rR  rQ   rS  rQ   rT  rQ   rc   rd   )r   rQ   rc   rQ   )NT)r]   rQ   r   r{  r   rx  rc   rd   )rR  rQ   rS  rQ   rc   rd   )rc   ru  )r   r   r   r   	transporthas_pipeliningrl   r}   staticmethodr   r   r   r   r   r   r   r  r>  re   r@  r[  rb  rO  rg  rk  rq  r   __classcell__)ry   s   @r   rb   rb   1  s   !IN*. 
 -1  *	
  
 & ! !" + +& [zF4  /+be2N	 P P
 Dp DpL:',RF F: r   rb   )r0   rE   r1   rL   r2   rd   r3   rx  r+   rQ   r4   r   rc   ru  )r`   Bc.Callable[t.Concatenate[Connection, P], tuple[int, bytes, bytes]]rc   r  )7
__future__r   DOCUMENTATIONcollections.abcabcr	  r  r  r   iorN   r  r_  r   r  r   rT   typingrI   	functoolsr   ansible.errorsr   r   r   r	   ansible.module_utils.sixr
   r   r   +ansible.module_utils.common.text.convertersr   r   r   ansible.plugins.connectionr   r    ansible.plugins.shell.powershellr   ansible.utils.displayr   ansible.utils.pathr   r   r4   	ParamSpecr   r.   r   compiler   r   r9   re   rb   r   r   r   <module>r     s   #eN     	 	 
 	        A @ T T > C ) 9
)AKK   BJJ'(		< 	 <$<$<$ +<$ 	<$
 <$ <$ 
<$~N
LNGNbC  C r   