
    Vh[                     J   d dl mZmZmZ eZd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mZ d dlmZ d dlmZ d dlmZ d d	lmZ  e       Z	 d d
lmZ d dlm Z m!Z! d dl"m#Z# dZ$dZ& e	jN                  d      Z( G d de)      Z*i Z+i Z, G d de      Z-y# e%$ r dZ$Y 8w xY w)    )absolute_importdivisionprint_functionaW  
    author:
      - Ansible Networking Team (@ansible-network)
    name: libssh
    short_description: Run tasks using libssh for ssh connection
    description:
        - Use the ansible-pylibssh python bindings to connect to targets
        - The python bindings use libssh C library (https://www.libssh.org/) to connect to targets
        - This plugin borrows a lot of settings from the ssh plugin as they both cover the same protocol.
    version_added: 1.1.0
    options:
      remote_addr:
        description:
            - Address of the remote target
        type: string
        default: inventory_hostname
        vars:
            - name: inventory_hostname
            - name: ansible_host
            - name: ansible_ssh_host
            - name: ansible_libssh_host
      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_libssh_user
        env:
            - name: ANSIBLE_REMOTE_USER
            - name: ANSIBLE_LIBSSH_REMOTE_USER
        ini:
            - section: defaults
              key: remote_user
            - section: libssh_connection
              key: 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_libssh_pass
            - name: ansible_libssh_password
      password_prompt:
        description:
          - Text to match when using keyboard-interactive authentication to determine if the prompt is
            for the password.
          - Requires ansible-pylibssh version >= 1.0.0
        type: string
        vars:
          - name: ansible_libssh_password_prompt
        version_added: 3.1.0
      host_key_auto_add:
        description: 'TODO: write it'
        env: [{name: ANSIBLE_LIBSSH_HOST_KEY_AUTO_ADD}]
        ini:
          - {key: host_key_auto_add, section: libssh_connection}
        type: boolean
      look_for_keys:
        default: True
        description: 'TODO: write it'
        env: [{name: ANSIBLE_LIBSSH_LOOK_FOR_KEYS}]
        ini:
        - {key: look_for_keys, section: libssh_connection}
        type: boolean
      proxy_command:
        default: ''
        description:
            - Proxy information for running the connection via a jumphost.
            - Also this plugin will scan 'ssh_args', 'ssh_extra_args' and 'ssh_common_args' from the 'ssh' plugin settings for proxy information if set.
        type: string
        env:
          - name: ANSIBLE_LIBSSH_PROXY_COMMAND
        ini:
          - {key: proxy_command, section: libssh_connection}
        vars:
          - name: ansible_paramiko_proxy_command
          - name: ansible_libssh_proxy_command
      pty:
        default: True
        description: 'TODO: write it'
        env:
          - name: ANSIBLE_LIBSSH_PTY
        ini:
          - section: libssh_connection
            key: pty
        type: boolean
      publickey_accepted_algorithms:
        default: ''
        description:
            - List of algorithms to forward to SSH_OPTIONS_PUBLICKEY_ACCEPTED_TYPES.
        type: string
        env:
          - name: ANSIBLE_LIBSSH_PUBLICKEY_ALGORITHMS
        ini:
          - {key: publickey_algorithms, section: libssh_connection}
        vars:
          - name: ansible_libssh_publickey_algorithms
      hostkeys:
        default: ''
        description: Set the preferred server host key types as a comma-separated list (e.g., ssh-rsa,ssh-dss,ecdh-sha2-nistp256).
        type: string
        env:
          - name: ANSIBLE_LIBSSH_HOSTKEYS
        ini:
          - {key: hostkeys, section: libssh_connection}
        vars:
          - name: ansible_libssh_hostkeys
      host_key_checking:
        description: 'Set this to "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_LIBSSH_HOST_KEY_CHECKING
        ini:
          - section: defaults
            key: host_key_checking
          - section: libssh_connection
            key: host_key_checking
        vars:
          - name: ansible_host_key_checking
          - name: ansible_ssh_host_key_checking
          - name: ansible_libssh_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
      ssh_args:
          version_added: 3.2.0
          description:
           - Arguments to pass to all ssh CLI tools.
           - ProxyCommand is the only supported argument.
           - This option is deprecated in favor of I(proxy_command) and will be removed
             in a release after 2026-01-01.
          type: string
          ini:
              - section: 'ssh_connection'
                key: 'ssh_args'
          env:
              - name: ANSIBLE_SSH_ARGS
          vars:
              - name: ansible_ssh_args
          cli:
              - name: ssh_args
      ssh_common_args:
          version_added: 3.2.0
          description:
           - Common extra arguments for all ssh CLI tools.
           - ProxyCommand is the only supported argument.
           - This option is deprecated in favor of I(proxy_command) and will be removed
             in a release after 2026-01-01.
          type: string
          ini:
              - section: 'ssh_connection'
                key: 'ssh_common_args'
          env:
              - name: ANSIBLE_SSH_COMMON_ARGS
          vars:
              - name: ansible_ssh_common_args
          cli:
              - name: ssh_common_args
      ssh_extra_args:
          version_added: 3.2.0
          description:
           - Extra arguments exclusive to the 'ssh' CLI tool.
           - ProxyCommand is the only supported argument.
           - This option is deprecated in favor of I(proxy_command) and will be removed
             in a release after 2026-01-01.
          type: string
          vars:
              - name: ansible_ssh_extra_args
          env:
            - name: ANSIBLE_SSH_EXTRA_ARGS
          ini:
            - key: ssh_extra_args
              section: ssh_connection
          cli:
            - name: ssh_extra_args
      config_file:
        version_added: 5.1.0
        description: Alternate SSH config file location
        type: path
        env:
          - name: ANSIBLE_LIBSSH_CONFIG_FILE
        ini:
          - section: libssh_connection
            key: config_file
        vars:
          - name: ansible_libssh_config_file
# TODO:
#timeout=self._play_context.timeout,
N)AnsibleConnectionFailureAnsibleErrorAnsibleFileNotFound)to_bytes	to_nativeto_text)missing_required_lib)ConnectionBase)Display)Version)__version__)LibsshSCPExceptionLibsshSessionException)SessionTFz
libssh: The authenticity of host '%s' can't be established due to '%s'.
The %s key fingerprint is %s.
Are you sure you want to continue connecting (yes/no)?
z(\w+)(?:\s*=\s*|\s+)(.+)c                       e Zd ZdZd Z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     o/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/ansible/netcommon/plugins/connection/libssh.py__init__zMyAddPolicy.__init__  s    $"++    c           	         t        | j                  d   | j                  d    f      r| j                  j                  d      s| j                  j                  r)t        t        j                  dd      d   ||||fz        t        t        j                  t        ||||fz  d      d	
      }| j                  j                          |dvrt        d      |j                  |       y )Nhost_key_checkinghost_key_auto_adduse_persistent_connections
   r   F)privatesurrogate_or_stricterrors)yesy z host connection rejected by user)allr   r   
get_optionforce_persistencer   AUTHENTICITY_MSGrsplitr   displayprompt_untilconnection_unlockhostkey_auto_add)r   sessionhostnameusernamekey_typefingerprintmessageinps           r   missing_host_keyzMyAddPolicy.missing_host_key	  s    12MM"566
 **+GH??44 #$++D!4Q78WhXc:dd  $$$'8['QQ[` %  -	C OO--/**"#EFF  *r   N)__name__
__module____qualname____doc__r   r;    r   r   r   r      s    ,+r   r   c                   v     e Zd ZdZdZdZd Zd Zd ZddZ	d Z
d fd		Zd fd
	Zd Zd fd	Zd Zd Z xZS )
Connectionz#SSH based connections with Paramikozansible.netcommon.libsshNc                 b    | j                   j                  d| j                   j                  dS N__)_play_contextremote_addrremote_userr   s    r   
_cache_keyzConnection._cache_key6  s*    ****
 	
r   c                     | j                         }|t        v rt        |   | _        | S | j                         x| _        t        |<   | S r   )rJ   SSH_CONNECTION_CACHEssh_connect_uncachedr   	cache_keys     r   _connectzConnection._connect<  sL    OO%	,,+I6DH  :>9O9O9QQDH+I6r   c                     || _         y r   )_log_channel)r   names     r   _set_log_channelzConnection._set_log_channelD  s
     r   c                    d }| j                  d      xs d| j                  d      xs d| j                  d      xs dg}t        |      rt        j                  d       | j	                  dj                  |            }t        |      D ]o  \  }}|j                         dk(  r	||dz      }nJt        j                  |      }|r3|j                  d      j                         dk(  r|j                  d	      }|so n |xs | j                  d
      }|ra| j                  j                  || j                  j                  d}|j                         D ]   \  }	}
|j                  |	t!        |
            }" |S )Nssh_extra_argsr*   ssh_common_argsssh_argszThe ssh_*_args options are deprecated and will be removed in a release after 2026-01-01. Please use the proxy_command option instead. proxycommand   r#   proxy_command)z%hz%pz%r)r,   anyr0   warning_split_ssh_argsjoin	enumeratelowerSETTINGS_REGEXmatchgrouprF   rG   rH   itemsreplacestr)r   portr]   rY   argsiargre   	replacersfindrh   s              r   _get_proxy_commandzConnection._get_proxy_commandG  sj    OO,-3OO-.4"OOJ'-2
 x=OO X ''(:;D#D/ 399;.0$(QKM +005E ;;q>//1^C,1KKNM  &I)I((44((44I
 "+!2 Jg - 5 5dCL IJ r   c                    t         st        t        d            t        j	                  dt
        z  | j                  j                         i }| j                  d      }| j                  d      }| j                  j                  xs d}t        j	                  d|d|d	||       t               | _        t        j                  d
kD  r)| j                  j                  t        j                         t         j"                  j%                  d      | _        | j)                  |      }	 d}| j                  j*                  rbt-        t         j"                  j%                  | j                  j*                              5 }|j/                         }t1        |d      }ddd       |r||d<   | j                  d      r| j                  d      |d<   | j                  d      r$t3        t
              dk  rt        dt
        z        | j                  d      r| j                  d      |d<   | j                  d      r| j                  d      |d<   | j                  j5                  t7        |               | j                  j8                  d|j;                         || j                  d      | j                  d      | j                  d      | j                  d      || j                  j<                  |d	| t        j	                  dtG        | j                        z          | j                  S # 1 sw Y   xY w# t>        $ r}	dtA        |	      z   }
tC        |
      d}	~	wtD        $ r}	tC        tA        |	            d}	~	ww xY w)zactivates the connection objectzansible-pylibsshzUSING PYLIBSSH VERSION %shostrH   rG      z&ESTABLISH LIBSSH CONNECTION FOR USER: z	 on PORT  TO    z~/.ssh/known_hostsNr%   r&   r[   config_filepassword_promptz1.0.0zConfiguring password prompt is not supported in ansible-pylibssh version %s. Please upgrade to ansible-pylibssh 1.0.0 or newer.publickey_accepted_algorithmshostkeyslook_for_keysr   password)	rs   userr{   r   r|   rx   private_keytimeoutrj   zssh connection failed: zssh connection is OK: r@   )$HAS_PYLIBSSHr   r   r0   vvvPYLIBSSH_VERSIONrF   rG   r,   rj   r   rM   	verbosityset_log_levelloggingINFOospath
expanduserkeyfilerp   private_key_fileopenreadr	   r   set_missing_host_key_policyr   connectrc   r   r   r   r   	Exceptionri   )r   ssh_connect_kwargsrH   rG   rj   r]   r~   fp	b_contentemsgs              r   rN   zConnection._connect_uncachedp  s    34FGHH'*::##// 	 	

  oom4oom4!!&&,"D+/ 	 	
 9q HH""7<<0ww))*>?//5-	7K!!22"'',,T-?-?-P-PQR TVX "	I"*9=R"SKT 5B">2}-48OOM4R"=101w?O7PSZ7Z"IK[\ 
 >?FJoo3G"#BC z*151L":.HH00T1BCDHH  &&( "ooo>"&//2E"F4 $0A B'**22 %$ 	,s488}<=xx[T TL & 	0+gaj8C*3// 	7*71:66	7s>   ,AL=  L0EL= 0L:5L= =	NMN+M??Nc                    t         t        |   |||       |rt        d      d}	 | j                  j                         | _        | j                  d      r|r| j                  j                          t        j                  d|z  | j                  j                   	       t#        |d
      }d}d}	d}
d}d}d}	 | j$                  r| j$                  j'                         rd}d}| j                  j)                  |       |s|st        j+                  d       | j                  j-                  | j                  j.                         | j                  j1                  |      }t        j+                  d|z         |sCd|v r>t        | j$                  j                  d| j                              }t        d|z        n_||z  }|j3                  d      D ]@  }| j$                  j5                  |      rd} n!| j$                  j7                  |      s>d} n |s|s|rh| j$                  rQ| j$                  j                  d| j                        }| j                  j)                  t#        |d
      dz          n<t        d      |	|z  }	|
|z  }
n&| j                  j                  t        |d
            }|r%|j:                  }|j<                  }|j>                  }n| j                  jA                         }|||fS # t        $ r0}t        |      }d}|r|d|z  z  }t        t        |            d}~ww xY w# t8        j.                  $ r t        d|z         w xY w)z run a command on the remote host)in_datasudoablezHInternal Error: this module does not support optimized module pipeliningi   zFailed to open sessionz: %sNptyzEXEC %srr   r%   r&   r   Fz&Waiting for Privilege Escalation input)r   zchunk is: %ss   unknown userbecome_user)playcontextzuser %s does not existTbecome_pass   
z,A password is required but none was suppliedz0ssh timed out waiting for privilege escalation.
)!superrB   exec_commandr   rM   new_channelchanr   r   r   r
   r,   request_shellr0   r   rF   rG   r	   becomeexpect_promptsendalldebugpollr   recv
splitlinescheck_successcheck_password_promptsocket
returncodestdoutstderrget_channel_exit_status)r   cmdr   r   bufsizer   text_er   resultno_prompt_outno_prompt_errbecome_outputouterr
passpromptbecome_sucesschunkn_become_userliner   rc	__class__s                        r   r   zConnection.exec_command  s0    	j$,S'H,UZ  	;,,.DI ??5!hII##%IO$*<*<*H*HIs#892	d{{t{{88:"
 %		!!#&(JMM"JKIINN4+=+=+E+ENF IINN73EMM.5"89 *m;,5 $ 6 6$1040B0B !7 !"-M #//G-/W"XX!!U*M !. 8 8 > ";;44T:,0M!;;<<TB)-J!"+ )J8 {{&*kk&<&<)t7I7I '= ' 		))$[9NORWW ++YZZ!]2M!]2M//DY0Z[ ""B--C--C224B3|e  	;QZF*Cv&*9S>::	;R ~~ 	dRUbbcc	ds1   L <EM 	M %BM 	L?+L::L?"M$c           	         t         t        |   ||       t        j	                  d|d|| j
                  j                         t        j                  j                  t        |d            st        d|z        |dk(  rT	 | j                  j                         | _        	 | j                  j!                  t        |d      t        |d             y	|dk(  r.| j                  j%                         }	 |j!                  ||       y	t        d|z        # t        $ r}t        d|z        d	}~ww xY w# t"        $ r t        d
|z        w xY w# t&        $ r}t        d|dt)        |            d	}~ww xY w)z$transfer a file from local to remotezPUT ru   rr   r%   r&   z!file or module does not exist: %ssftp%failed to open a SFTP connection (%s)Nzfailed to transfer file to %sscpzError transferring file to : 0Don't know how to transfer file over protocol %s)r   rB   put_filer0   r   rF   rG   r   r   existsr	   r   rM   r   r   r   putIOErrorr   r   r   r   in_pathout_pathprotor   r   excr   s          r   r   zConnection.put_file"  se    	j$((;%x0##// 	 	

 ww~~hw7LMN%&IG&STTF?P HHMMO	O		W-BCX.CD e^((,,.Cc* QTYYZZ#  P"#JQ#NOOP  O"#BX#MNNO & c"(T[\_T`#abbcs<   D %2D8 8E 	D5"D00D58E	E;E66E;c                     | j                   j                  d| j                   j                  d}|t        v r	t        |   S | j	                         j
                  j                         x}t        |<   |S rD   )rF   rG   rH   SFTP_CONNECTION_CACHErQ   rM   r   )r   rP   r   s      r   _connect_sftpzConnection._connect_sftpE  sg    ****
	 --(338<8K8K8P8P8RRF*95Mr   c           	         t         t        |   ||       t        j	                  d|d|| j
                  j                         |dk(  rJ	 | j                         | _        	 | j                  j                  t        |d      t        |d             y|d
k(  r.| j                  j!                         }	 |j                  ||       yt        d|z        # t        $ r}t        dt        |      z        d}~ww xY w# t        $ r t        d	|z        w xY w# t"        $ r}t        d|dt%        |            d}~ww xY w)z(save a remote file to the specified pathzFETCH ru   rr   r   r   Nr%   r&   zfailed to transfer file from %sr   zError transferring file from r   r   )r   rB   
fetch_filer0   r   rF   rG   r   r   r   r   r
   getr	   r   rM   r   r   r   r   s          r   r   zConnection.fetch_fileP  sB    	j$*7H= '2##// 	 	

 F?[ ..0	P		W-BCX.CD e^((,,.Ce * QTYYZZ)  ["#JYWX\#YZZ[  P"#Dw#NOOP & e"HV]^aVb#cddes<   C #2C? 6D 	C< C77C<?D	E#D==Ec                 D    | j                          | j                          y r   )closerQ   rI   s    r   resetzConnection.resets  s    

r   c                    | j                         }t        j                  |d       t        j                  |d       t	        | d      r&| j
                  | j
                  j                          t	        | d      r&| j                  | j                  j                          | j                  j                          d| _	        y)zterminate the connectionNr   r   F)
rJ   rL   popr   hasattrr   r   r   rM   
_connectedrO   s     r   r   zConnection.closew  s     OO%	  D1!!)T24 yy$		!4 yy$		!r   )rt   )NT)r   )r<   r=   r>   r?   	transportrS   rJ   rQ   rU   rp   rN   r   r   r   r   r   r   __classcell__)r   s   @r   rB   rB   0  sP    -*IL
!'RN``D![F	![F r   rB   ).
__future__r   r   r   type__metaclass__DOCUMENTATIONr   r   rer   ansible.errorsr   r   r   ansible.module_utils._textr	   r
   r   ansible.module_utils.basicr   ansible.plugins.connectionr   ansible.utils.displayr   Bansible_collections.ansible.netcommon.plugins.plugin_utils.versionr   r0   pylibsshextr   r   pylibsshext.errorsr   r   pylibsshext.sessionr   r   ImportErrorr.   compilerd   objectr   rL   r   rB   r@   r   r   <module>r      s   
 A @ LZ  	 	  V V C C ; 5 ) V );M+L
  78*+& *+b   W  W G  Ls   B B"!B"