
    Vh̤                       d dl m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
Z
d dlZd dlZd dlZd dlmc mZ d dlmZ d dlmZ dZ	 d dlZdZd dl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&m'Z'm(Z( d dl)m*Z* d dl+m,Z, d dl+m-Z. d dl/m0Z0 d dl1m2Z2 	 d dl3Z3d dl4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:Z;dZ<dZ=	 d dl4m?Z? 	 d dlAZAdZBdZCdZD	 d dlEZE eFeEd      r, eeEj                  j                        ZIdeIj                  v rdZD	 d dlKZKdZL e2       ZM G d de*      ZNy# e$ r Y w xY w# e$ rZ>dZ<e>Z=Y dZ>[>dZ>[>ww xY w# e$ r  G d de@      Z?Y w xY w# e$ rZ>dZBe>ZCY dZ>[>dZ>[>ww xY w# e$ r
Z>Y dZ>[>qdZ>[>ww xY w# e$ r dZLY {w xY w)    )annotationsac  
    author: Ansible Core Team
    name: winrm
    short_description: Run tasks over Microsoft's WinRM
    description:
        - Run commands or put/fetch on a target via WinRM
        - This plugin allows extra arguments to be passed that are supported by the protocol but not explicitly defined here.
          They should take the form of variables declared with the following pattern C(ansible_winrm_<option>).
    version_added: "2.0"
    extends_documentation_fragment:
        - connection_pipelining
    requirements:
        - pywinrm (python library)
    options:
      # figure out more elegant 'delegation'
      remote_addr:
        description:
            - Address of the windows machine
        default: inventory_hostname
        vars:
            - name: inventory_hostname
            - name: ansible_host
            - name: ansible_winrm_host
        type: str
      remote_user:
        description:
            - The user to log in as to the Windows machine
        vars:
            - name: ansible_user
            - name: ansible_winrm_user
        keyword:
            - name: remote_user
        type: str
      remote_password:
        description: Authentication password for the O(remote_user). Can be supplied as CLI option.
        vars:
            - name: ansible_password
            - name: ansible_winrm_pass
            - name: ansible_winrm_password
        type: str
        aliases:
        - password  # Needed for --ask-pass to come through on delegation
      port:
        description:
            - port for winrm to connect on remote target
            - The default is the https (5986) port, if using http it should be 5985
        vars:
          - name: ansible_port
          - name: ansible_winrm_port
        default: 5986
        keyword:
            - name: port
        type: integer
      scheme:
        description:
            - URI scheme to use
            - If not set, then will default to V(https) or V(http) if O(port) is
              V(5985).
        choices: [http, https]
        vars:
          - name: ansible_winrm_scheme
        type: str
      path:
        description: URI path to connect to
        default: '/wsman'
        vars:
          - name: ansible_winrm_path
        type: str
      transport:
        description:
           - List of winrm transports to attempt to use (ssl, plaintext, kerberos, etc)
           - If None (the default) the plugin will try to automatically guess the correct list
           - The choices available depend on your version of pywinrm
        type: list
        elements: string
        vars:
          - name: ansible_winrm_transport
      kerberos_command:
        description: kerberos command to use to request a authentication ticket
        default: kinit
        vars:
          - name: ansible_winrm_kinit_cmd
        type: str
      kinit_args:
        description:
        - Extra arguments to pass to C(kinit) when getting the Kerberos authentication ticket.
        - By default no extra arguments are passed into C(kinit) unless I(ansible_winrm_kerberos_delegation) is also
          set. In that case C(-f) is added to the C(kinit) args so a forwardable ticket is retrieved.
        - If set, the args will overwrite any existing defaults for C(kinit), including C(-f) for a delegated ticket.
        type: str
        vars:
          - name: ansible_winrm_kinit_args
        version_added: '2.11'
      kinit_env_vars:
        description:
        - A list of environment variables to pass through to C(kinit) when getting the Kerberos authentication ticket.
        - By default no environment variables are passed through and C(kinit) is run with a blank slate.
        - The environment variable C(KRB5CCNAME) cannot be specified here as it's used to store the temp Kerberos
          ticket used by WinRM.
        type: list
        elements: str
        default: []
        ini:
        - section: winrm
          key: kinit_env_vars
        vars:
          - name: ansible_winrm_kinit_env_vars
        version_added: '2.12'
      kerberos_mode:
        description:
            - kerberos usage mode.
            - The managed option means Ansible will obtain kerberos ticket.
            - While the manual one means a ticket must already have been obtained by the user.
            - If having issues with Ansible freezing when trying to obtain the
              Kerberos ticket, you can either set this to V(manual) and obtain
              it outside Ansible or install C(pexpect) through pip and try
              again.
        choices: [managed, manual]
        vars:
          - name: ansible_winrm_kinit_mode
        type: str
      connection_timeout:
        description:
            - Despite its name, sets both the 'operation' and 'read' timeout settings for the WinRM
              connection.
            - The operation timeout belongs to the WS-Man layer and runs on the winRM-service on the
              managed windows host.
            - The read timeout belongs to the underlying python Request call (http-layer) and runs
              on the ansible controller.
            - The operation timeout sets the WS-Man 'Operation timeout' that runs on the managed
              windows host. The operation timeout specifies how long a command will run on the
              winRM-service before it sends the message 'WinRMOperationTimeoutError' back to the
              client. The client (silently) ignores this message and starts a new instance of the
              operation timeout, waiting for the command to finish (long running commands).
            - The read timeout sets the client HTTP-request timeout and specifies how long the
              client (ansible controller) will wait for data from the server to come back over
              the HTTP-connection (timeout for waiting for in-between messages from the server).
              When this timer expires, an exception will be thrown and the ansible connection
              will be terminated with the error message 'Read timed out'
            - To avoid the above exception to be thrown, the read timeout will be set to 10
              seconds higher than the WS-Man operation timeout, thus make the connection more
              robust on networks with long latency and/or many hops between server and client
              network wise.
            - Setting the difference between the operation and the read timeout to 10 seconds
              aligns it to the defaults used in the winrm-module and the PSRP-module which also
              uses 10 seconds (30 seconds for read timeout and 20 seconds for operation timeout)
            - Corresponds to the C(operation_timeout_sec) and
              C(read_timeout_sec) args in pywinrm so avoid setting these vars
              with this one.
            - The default value is whatever is set in the installed version of
              pywinrm.
        vars:
          - name: ansible_winrm_connection_timeout
        type: int
N)getfullargspec)
urlunsplitFT)	constants)AnsibleErrorAnsibleConnectionFailure)AnsibleFileNotFound)_filter_non_json_lines)boolean)to_bytes	to_nativeto_text)ConnectionBase)_parse_clixml)	ShellBase)secure_hash)Display)
WinRMErrorWinRMOperationTimeoutErrorWinRMTransportError)Protocol)WSManFaultErrorc                      e Zd Zy)r   N)__name__
__module____qualname__     P/home/dcms/DCMS/lib/python3.12/site-packages/ansible/plugins/connection/winrm.pyr   r      s    r   r   spawnechoc                  *    e Zd ZdZdZdZdZdZdZd fdZ	ddZ
ddZdd	Zdd
ZdddZ	 	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 	 	 d dZ	 	 	 d!	 	 	 	 	 	 	 	 	 d"dZ	 d	 	 	 	 	 	 	 d#dZd$ fdZddZd%d&dZd'd( fdZd)d*dZd+ fdZd+ fdZddZ xZS ),
Connectionz"WinRM connections over HTTP/HTTPS.winrm)z.ps1z.exe FTc                   d| _         d| _        d | _        d | _        d | _        |  d| _        t        t        | "  |i | t        j                  st        j                  d      j                  t        j                         t        j                  d      j                  t        j                         t        j                  d      j                  t        j                         y y )NT
powershellrequests_credssprequests_kerberosurllib3)always_pipeline_moduleshas_native_asyncprotocolshell_iddelegate_shell_typesuperr#   __init__CDEFAULT_DEBUGlogging	getLoggersetLevelINFO)selfargskwargs	__class__s      r   r2   zConnection.__init__  s    '+$ $/3$('j$($9&901::7<<H12;;GLLIi(11',,? r   c                   | j                  d      | _        | j                  d      | _        | j                  d      | _        | j                  d      | _        | j                  d      | _        | j
                  | j                  dk(  rdnd| _        | j                  d	      | _        | j                  d
      | _        | j                  d      | _        | j                  d      | _	        t        t        d      rt        t        j                        | _        nt        g d      | _        | j                  | j                  d   H| j
                  dk(  rdgndg}t        r&| j                  rd| j                  v rdg|z   | _        n|| _        t        | j                        j!                  | j                        }|r"t#        dt%        t'        |      d      z        | j                  d      }|5d| j                  v xr | j                  d uxr | j                  dk7  | _        n|dk(  rd| _        n|dk(  rd| _        h d}t+        | j                  | j                        | _        t/        t0        j2                        }t        |j4                        }|j7                  |       | j                  d      D ch c]  }|j9                  d d       }}|j!                  |      }	|	D ]&  }
t:        j=                  d!j?                  |
             ( |j!                  |      jA                  |      D ]&  }
| j                  d      d"|
z     | j,                  |
<   ( y c c}w )#Nremote_addrremote_userremote_passwordportschemeia  httphttpspathkerberos_command	transportconnection_timeoutFEATURE_SUPPORTED_AUTHTYPES)	plaintextsslkerberosr   rK   rJ   @rL   z?The installed version of WinRM does not support transport(s) %s
simplerepr)	nonstringkerberos_moder%   managedTmanualF>	   rE   r9   rB   endpointpasswordusername	kinit_cmdrG   
kinit_mode)rU   rT   _extrasansible_winrm_zYansible_winrm_{0} unsupported by pywinrm (is an up-to-date version of pywinrm installed?)zansible_winrm_%s)!
get_option_winrm_host_winrm_user_winrm_pass_winrm_port_winrm_scheme_winrm_path
_kinit_cmd_winrm_transport_winrm_connection_timeouthasattrr$   setrI   _winrm_supported_authtypesHAVE_KERBEROS
differencer   r   list_kerb_manageddict_winrm_kwargsr   r   r2   r:   updatereplacedisplaywarningformatintersection)r9   transport_selectorunsupported_transportsrW   internal_kwarg_maskargspecsupported_winrm_argsvpassed_winrm_argsunsupported_argsargs              r   _build_winrm_kwargszConnection._build_winrm_kwargs  s=   
  ??=9??=9??+<=??62!__X6 %+/+;+;t+CD??62//*<= $ <)-9M)N&578.1%2S2S.TD+ /22R.SD+   (D,A,A!,D,L,0,>,>',I%P[}4#3#3t?O?O8O)37I(I%(:%!$T%:%:!;!F!FtGfGf!g!`(.D)EQ]^ _ ` ` ___5
!+t/D/D!D  "C$JZJZbfJf  KBkok{k{  @B  lBD9$!%D8#!&D E!4+;+;dFVFVW !2!23"7<<0##$78FJooV_F`aQYY'7<aa,778LM $ 	ECOOw~~  @C  D  E	E %//0CDQQRfg 	[C&*ooi&@ASVYAY&ZDs#	[ bs   >Mc                   |d}t        j                         | _        t        j	                  d| j                  j
                  z         d| j                  j
                  z  }|t        j                  d<   t        t        j                  d   |      }| j                  d      }|D ]0  }||vs|t        j                  v st        j                  |   ||<   2 | j                  g}| j                  d      }|rNt        j                  |      D 	cg c]  }	|	j                         st        |	        }}	|j                  |       n;t!        | j                  d	      j#                  d
d            r|j%                  d       |j%                  |       t&        rd}
|j)                  d      }t        |dd      }t        j+                  d|z         	 t-        j.                  ||d|d      }	 |j7                  d       |j9                  |       |j=                         }|j?                          |j@                  }nd}
tC        |dd      }t        j+                  d|z         	 tE        jF                  |tD        jH                  tD        jH                  tD        jH                  |      }|jK                  |dz         \  }}|jL                  dk7  }|dk7  rJt3        |j                               }|jO                  t3        |      d      }d|d|
d |}t5        |      t        j	                  d!|z         y c c}	w # t,        j0                  $ r!}d|dt3        |      }t5        |      d }~ww xY w# t:        $ r,}t        j+                  dt3        |      z         Y d }~d }~ww xY w# t:        $ r+}d| j                  dt3        |      }t5        |      d }~ww xY w)"Nr%   zcreating Kerberos CC at %szFILE:%s
KRB5CCNAMEPATH)r   r~   kinit_env_vars
kinit_argsrX   !ansible_winrm_kerberos_delegationFz-fpexpectr   zutf-8surrogate_or_strict)encodingerrorsz+calling kinit with pexpect for principal %s<   )timeoutenvr!   z.Kerberos auth failure when calling kinit cmd 'z': z.*:z%kinit with pexpect raised OSError: %s
subprocessz.calling kinit with subprocess for principal %s)stdinstdoutstderrr      
z
<redacted>z$Kerberos auth failure for principal z with : z kinit succeeded for principal %s)(tempfileNamedTemporaryFile_kerb_ccachero   vvvvvnameosenvironrk   rZ   ra   shlexsplitstripr   extendr   getappendHAS_PEXPECTpopvvvvr   r    ExceptionPexpectr   r   expectsendlineOSErrorreadwait
exitstatusr   r   PopenPIPEcommunicate
returncodern   )r9   	principalrT   
krb5ccnamekrb5envr   varkinit_cmdliner   aproc_mechanismcommandchilderrerr_msgr   rc
b_passwordpr   exp_msgs                        r   
_kerb_authzConnection._kerb_auth^  si   H$7792T5F5F5K5KKL!2!2!7!77
#-

< BJJv.:F )9:! 	/C'!cRZZ&7!zz#	/ )__\2
.3kk*.ES'!*SJS  ,T__Y/334WY^_`  &Y' &N#''*Gx'&;=H LLF$% &8g}b*1?/U#x( ZZ\FJJL!!B)N!(W)>@J LLI$% &	8$$]*//,6OO,6OO)02 ]]:+=>NFF"B7  /Gooi&9<HG #NG=G*73389DES T. ++ 8(/3A.w778  / D(~. / //0  8(,3I.w778sU   L9'L9L> /"M5 'AN- >M2M--M25	N*>!N%%N*-	O!6&OO!c                   t         j                  d| j                  d| j                  d| j                  | j                         | j                  }t
        r3t         j                  d|z         	 t        j                  |       d|z  }d|| j                  fz  }t        | j                  || j                  ddf      }g }| j                  D ]"  }|d	k(  rJt        s|j                  d
       !| j                   r&| j#                  | j                  | j$                         t         j'                  d|d|| j                         	 | j(                  j+                         }| j,                  r!| j,                  |d<   | j,                  dz   |d<   t/        |fd|i|}| j0                  sE|j3                  d      | _        t         j'                  d| j0                  z  | j                         |c S  |r(tK        djM                  tO        tP        |                  tA        d       # t        j                  $ r Y w xY w# t4        $ r}t7        |      j9                         }	t;        j<                  t7        d      |	t:        j>                        rtA        d      t;        j<                  t7        d      |	      }
|
r2tC        |
jE                         d         }|dk(  rd}	n|dk(  r	cY d}~c S |j                  |d|	       t         j'                  d|	dt7        tG        jH                               | j                         Y d}~d}~ww xY w)!z?
        Establish a WinRM connection over HTTP/HTTPS.
        z%ESTABLISH WINRM CONNECTION FOR USER: z	 on PORT z TO hostz,checking if winrm_host %s is an IPv6 addressz[%s]z%s:%dr%   rL   z6kerberos: the python kerberos library is not installedzWINRM CONNECT: transport=z
 endpoint=operation_timeout_sec
   read_timeout_secrG   i  )codepagezWINRM OPEN SHELL: %szOperation\s+?timed\s+?outz the connection attempt timed outzCode\s+?(\d{3})r   i  z5the specified credentials were rejected by the serveri  Nr   zWINRM CONNECTION ERROR: 
z, z'No transport found for WinRM connection))ro   vvvr\   r^   r[   HAS_IPADDRESSdebug	ipaddressIPv6AddressAddressValueErrorr   r_   r`   rb   rg   r   rj   r   r]   r   rl   copyrc   r   r.   
open_shell	Exceptionr   r   researchIr   intgroups	traceback
format_excr   joinmapr   )r9   
winrm_hostnetlocrS   r   rG   winrm_kwargsr-   er   mcodes               r   _winrm_connectzConnection._winrm_connect  s    	%%t'7'79I9IKQUQaQa 	 	c %%
MMH:UV1%%j1 $j0
J(8(899t1164;K;KRQSTU.. !	EIJ&$MM"Z[%%OOD$4$4d6F6FGMMyRZ[bfbrbrMsE#1166811<@<Z<ZL!897;7U7UXZ7ZL!34#HR	R\R }}$,$7$7$7$GDMMM"84=="HtO_O_M`)!	ED *499SF5K+LMMHII[ .. :  E!!***,99W%ABGRTTR&'IJJIIg&897Cqxxz!}-Ds{"Y'9g>?7GT]ThThTjLklsw  tD  tD  E  EEs9   4H, B'I,II
MBM-M5AMMc           	        |D ]B  \  }}t        dd      D ].  }	 | j                  | j                  | j                  |||        B D y # t        $ r/ t
        j                  d       |st        j                  d       Y =t        $ rK}|dk(  sdt        |      vr t
        j                  d| d	       t        j                  d       Y d }~d }~ww xY w)
N      )eofzWSMan OperationTimeout during send input, attempting to continue. If this continues to occur, try increasing the connection_timeout value for this host.      z'wsmanfault_code': '170'zWSMan send failed on attempt z2 as the command is busy, trying to send data again)range_winrm_send_inputr-   r.   r   ro   rp   timesleepr   str)r9   
command_idstdin_iteratordatais_lastattemptr   s          r   _winrm_write_stdinzConnection._winrm_write_stdin  s    - "	OT7 A; !**4==$--UY_f*g> C!"	
 2 & OO/
 #

1!  !|'AQ'OOO&CG9L~$  AJJqMs   *A		5C CACCc                F   d|j                  dd|      i}|d   j                  di       j                  di       j                  di       }d|d	<   ||d
<   t        j                  t	        |            |d<   |rd|d<   |j                  t        j                  |             y )Nenv:Envelope;http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmdz<http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Sendresource_uriactionr.   env:Bodyzrsp:Sendz
rsp:Streamr   z@Name
@CommandId#texttruez@End)_get_soap_header
setdefaultbase64	b64encoder   send_message	xmltodictunparse)r9   r-   r.   r   r   r   rqstreams           r   r   zConnection._winrm_send_input  s    h77VQ 8    N#..z2>II*VXYZb) 	!w)| **8E?;w#F6Ni//34r   c           	     d   d|j                  dd|      i}|d   j                  di       j                  di       j                  di       }||d<   d	|d
<   |j                  t        j                  |            }t        j                  |      }|j                  d      D cg c]  }|j                  j                  d      r|! }	}g }
g }d}|	D ]  }|j                  s|j                  d   dk(  r>|
j                  t        j                  |j                  j                  d                   `|j                  d   dk(  ss|j                  t        j                  |j                  j                  d                    t!        |j                  d      D cg c]%  }|j#                  dd      j                  d      r|' c}      dk(  }|r4t%        t'        d |j                  d      D              j                        }dj)                  |
      dj)                  |      ||fS c c}w c c}w )Nr   r   z?http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receiver   r   zrsp:Receivezrsp:DesiredStreamr   zstdout stderrr   z.//*StreamNamer   asciir   Stater%   zCommandState/Doner   c              3  V   K   | ]!  }|j                   j                  d       r| # yw)ExitCodeN)tagendswith).0nodes     r   	<genexpr>z;Connection._winrm_get_raw_command_output.<locals>.<genexpr>Q  s)      7d))*5  7s   ')r   )r   r   r   r   r   ET
fromstringfindallr  r	  textattribr   r   	b64decodeencodelenr   r   nextr   )r9   r-   r.   r   r   r   resrootr  stream_nodesr   r   return_codestream_nodecommand_dones                  r   _winrm_get_raw_command_outputz(Connection._winrm_get_raw_command_output,  s(    h77VT 8   
 N#..z2>II-Y[\Z+R0 	)|)w##I$5$5b$9:}}S!!\\&1,xx  * , , ' 	RK##!!&)X5f..{/?/?/F/Fw/OPQ##F+x7f..{/?/?/F/Fw/OPQ	R !\\&1Dxx$--.AB D EHIJ  7dll6&: 7 77;t=K xx&!1;LL-,Ds   "$H(*H-c                   g g }}d}d}|s@	 | j                  |||      \  }	}
}}|j                  |	       |j                  |
       d}|s@dj                  |      dj                  |      |fS # t        $ r |rY 0Y tw xY w)NFr  r   )r  r   r   r   )r9   r-   r.   r   try_oncestdout_bufferstderr_bufferr  r  r   r   s              r   _winrm_get_command_outputz$Connection._winrm_get_command_outputV  s     (*2}66x:V :\$$V,$$V, !   xx&(?LL .  s   <A. .A>=A>c           	     (   | j                   s| j                         | _         d| _        |r(t        j	                  d|d|| j
                         n't        j                  d|d|| j
                         d }	 d}| j                  t        |      t        t        t        |            |d u       }	 |r| j                  ||       | j)                  | j                   | j*                  ||      \  }}	}
t!        |      }t!        |	      }|r't        j	                  d	|
||fz  | j
                         t        j                  d
|
z  | j
                         t        j                  d|z  | j
                         t        j                  d|z  | j
                         |	j-                  d      rt/        |	      }	t!        |      }|r$	 t1        |      \  }}t3        j4                  |       |
||	f|r(	 | j                   j;                  | j*                  |       S S # t        $ rk}t        j                  dt        |      j                  dt!        |             t        j#                  t%        j&                                d}Y d }~d }~ww xY w# t6        $ r t9        d| d|       w xY w# t<        $ r/}|j>                  dk7  r t        j                  d       Y d }~S d }~ww xY w# t@        jB                  jD                  $ r}tG        dtI        |      z        d }~ww xY w# |rc	 | j                   j;                  | j*                  |       w # t<        $ r/}|j>                  dk7  r t        j                  d       Y d }~w d }~ww xY ww xY w)NTzWINRM EXEC  r   Fconsole_mode_stdinz7ERROR DURING WINRM SEND INPUT - attempting to recover: )r  z/WINRM RESULT <Response code %d, out %r, err %r>zWINRM RC %dzWINRM STDOUT %szWINRM STDERR %ss	   #< CLIXMLz"winrm send_input failed; 
stdout: 
stderr i  z]Failed to cleanup running WinRM command, resources might still be in use on the target serverzwinrm connection error: %s)%r-   r   
_connectedro   r   r[   vvvvvv_winrm_run_commandr   tupler   r   r   rp   typer   r   r   r   r   r!  r.   
startswithr   r
   jsonloads
ValueErrorr   cleanup_commandr   r   requests
exceptionsTimeoutr   r   )r9   r   r:   	from_execr   r   stdin_push_failedexb_stdoutb_stderrr   r   r   filtered_outputdummyr   excs                    r   _winrm_execzConnection._winrm_execs  sN    }} //1DM"DOMM>TEUEUMVNN$?dFVFVNW
D	E %00!c(D)*$2d$: 1 J)!++JG &*%C%C*	 &D &"Hh X&FX&FOSUW]_eRffmqm}m}~NN=2-D4D4DNENN,v5D<L<LNMNN,v5D<L<LNM ""<0(2  h-CF-K*OUJJ/
 x) EMM11$--L W  )#'8#4#4gbk!C Di2245$(!	)F " h&)LVHT]^d]e'fggh" + Evv}OO  %D  E  E	E ""** 	Z*+G)TW.+XYY	Z EMM11$--L* Evv}OO  %D  E  E	E s   =8K. 6H 
DK. #J /K. 6&J3	J'A JK. JK. J00K. 3	K+<%K&&K+.L'L""L''L* *N.&MN	N%NNNNc                v   	 | j                   j                  | j                  |||      S # t        $ r}|j                  dk7  r t
        j                  d| j                         | j                          | j                          | j                   j                  | j                  |||      cY d}~S d}~ww xY w)z@Starts a command with handling when the WSMan quota is exceeded.r$  l   g  z1Shell operation quota exceeded, re-creating shellr   N)
r-   run_commandr.   r   wmierror_codero   r   r[   close_connect)r9   r   r:   r%  fault_errors        r   r)  zConnection._winrm_run_command  s    	==,,#5	 -    	((J6 MMMTXTdTdMeJJLMMO==,,#5	 -  	s   (+ 	B8A9B3-B83B8c                    t         st        dt        t              z        t        st        dt        t
              z        t        t        | #          | j                  s,| j                          | j                         | _	        d| _        | S )Nz&winrm or requests is not installed: %szxmltodict is not installed: %sT)	HAS_WINRMr   r   WINRM_IMPORT_ERRHAS_XMLTODICTXMLTODICT_IMPORT_ERRr1   r#   rA  r-   r|   r   r'  )r9   r<   s    r   rA  zConnection._connect  ss    G)TdJeeff?)L`Baabbj$(*}}$$& //1DM"DOr   c                Z    | j                   sy d | _        d | _        | j                          y N)r'  r-   r.   rA  r9   s    r   resetzConnection.reset  s#    r   c              #     K   t        |      }t        |      }t        d||      D ]  }||||z    ||z   |k\  f  y w)Nr   )r   r  r   )r9   payloadbuffer_sizepayload_bytes
byte_countis         r   _wrapper_payload_streamz"Connection._wrapper_payload_stream  sS      )'
q*k2 	RA!k/2AOz4QQQ	Rs   <>c                    t         t        |   |||       | j                  j	                  |ddd      }t
        j                  d       d }|r| j                  |      }| j                  |d   |dd  d|      S )	N)in_datasudoableTFas_liststrict_modepreserve_rczEXEC (via pipeline wrapper)r   r   )r4  r   )	r1   r#   exec_command_shell_encode_scriptro   r   rR  r<  )r9   cmdrT  rU  	cmd_partsr   r<   s         r   rZ  zConnection.exec_command  s    j$,S'H,UKK..sDeaf.g	 	12!99'BN	!imt\jkkr   c              #    K   t         j                  j                  t        |d            }d}t	        t        |d      d      5 t        fdd      D ]v  }|t        |      z  }| j                  j                  d|||t        |      fz  | j                         t        j                  |      d	z   }|j                         |k(  f x |dk(  rd
 d d d        y # 1 sw Y   y xY ww)Nr   r   r   rbc                 &    j                         S rI  )r   )rN  in_files   r   <lambda>z5Connection._put_file_stdin_iterator.<locals>.<lambda>  s    ',,{*C r   r   z*WINRM PUT "%s" to "%s" (offset=%d size=%d)r   s   
)r   T)r   rE   getsizer   openiterr  _displayr   r[   r   r   tell)	r9   in_pathout_pathrN  in_sizeoffsetout_datab64_datarc  s	      `    @r   _put_file_stdin_iteratorz#Connection._put_file_stdin_iterator  s     ''//(7;P"QR(7+@A4H 
	 G "CcJ <#h-'##$PT[]egmors{o|S}$}  EI  EU  EU#  V!++H5?7!:;;< {
	  
	  
	 s   AC0BC$	C0$C-)C0c                   t         t        |   ||       | j                  j	                  |      }t
        j                  d|d|d| j                         t        j                  j                  t        |d            st        dt        |      z        d}|j                  | j                  j                  |            }| j                  j!                  |d	d
d
      }| j#                  |d   |dd  | j%                  ||            \  }}}t'        |      }	t'        |      }
|dk7  rt)        |
      	 t+        j,                  |	      }|j1                  d      }|st)        d      t3        |      }||k(  s-t)        dj                  t        |      t        |                  y # t.        $ r t)        d|	d|
      w xY w)NzPUT "" TO ""r   r   r`  z#file or module does not exist: "%s"a  
            begin {{
                $path = '{0}'

                $DebugPreference = "Continue"
                $ErrorActionPreference = "Stop"
                Set-StrictMode -Version 2

                $fd = [System.IO.File]::Create($path)

                $sha1 = [System.Security.Cryptography.SHA1CryptoServiceProvider]::Create()

                $bytes = @() #initialize for empty file case
            }}
            process {{
               $bytes = [System.Convert]::FromBase64String($input)
               $sha1.TransformBlock($bytes, 0, $bytes.Length, $bytes, 0) | Out-Null
               $fd.Write($bytes, 0, $bytes.Length)
            }}
            end {{
                $sha1.TransformFinalBlock($bytes, 0, 0) | Out-Null

                $hash = [System.BitConverter]::ToString($sha1.Hash).Replace("-", "").ToLowerInvariant()

                $fd.Close()

                Write-Output "{{""sha1"":""$hash""}}"
            }}
        TFrV  r   r   )r   z winrm put_file failed; 
stdout: r&  sha1zRemote sha1 was not returnedz2Remote sha1 hash {0} does not match local hash {1})r1   r#   put_filer[  _unquotero   r   r[   r   rE   existsr   r	   r   rq   _escaper\  r<  rp  r   r   r-  r.  r/  r   r   )r9   rj  rk  script_templatescriptr^  status_coder7  r8  r   r   
put_outputremote_sha1
local_sha1r<   s                 r   ru  zConnection.put_file"  s   j$((;;;''1'8<4CSCSTww~~hw7LMN%&KiX_N`&`aa< !''(;(;H(EFKK..vtQVdi.j	*.*:*:9Q<STSUgk  hE  hE  FM  OW  hX*:  +Y'Xx""!v&&	dF+J
 !nnV,=>> )
j(SZZ[dep[qs|  ~H  tI   J  K  K )  	dSY[abcc	ds   :F+ +Gc                t   t         t        |   ||       | j                  j	                  |      }|j                  dd      }t        j                  d|d|d| j                         d}d }	 d}	 	 d
t        || j                  j                  |      |      z  }t        j                  d|||fz  | j                         | j                  j                  |d	d      }| j                  |d   |dd        \  }}	}
t        |	      }t        |
      }|dk7  rt        |      |j!                         dk(  rd }n#t#        j$                  |j!                               }|nu|sBt&        j(                  j+                  t-        |d            rnHt/        t-        |d      d      }|j1                  |       t3        |      |k  rn|t3        |      z  }	 c|r|j?                          y y # t4        $ r, t7        j8                          t;        dt=        |      z        w xY w# |r|j?                          w w xY w)N\/zFETCH "rr  rs  r   i   r   Ta<  
                        $path = '%(path)s'
                        If (Test-Path -LiteralPath $path -PathType Leaf)
                        {
                            $buffer_size = %(buffer_size)d
                            $offset = %(offset)d

                            $stream = New-Object -TypeName IO.FileStream($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite)
                            $stream.Seek($offset, [System.IO.SeekOrigin]::Begin) > $null
                            $buffer = New-Object -TypeName byte[] $buffer_size
                            $bytes_read = $stream.Read($buffer, 0, $buffer_size)
                            if ($bytes_read -gt 0) {
                                $bytes = $buffer[0..($bytes_read - 1)]
                                [System.Convert]::ToBase64String($bytes)
                            }
                            $stream.Close() > $null
                        }
                        ElseIf (Test-Path -LiteralPath $path -PathType Container)
                        {
                            Write-Host "[DIR]";
                        }
                        Else
                        {
                            Write-Error "$path does not exist";
                            Exit 1;
                        }
                    )rN  rE   rm  z$WINRM FETCH "%s" to "%s" (offset=%d)F)rW  rY  r   z[DIR]r   r`  wbzfailed to transfer file to "%s") r1   r#   
fetch_filer[  rv  rn   ro   r   r[   rk   rx  r   r\  r<  r   IOErrorr   r   r  r   rE   isdirr   rf  writer  r   r   	print_excr   r   r@  )r9   rj  rk  rN  out_filerm  rz  r^  r{  r7  r8  r   r   r   r<   s                 r   r  zConnection.fetch_file`  s#   j$*7H=++&&w/##D#.GX>TEUEUV<	!F6`4 ;T[[=P=PQX=Ybhi5jF6 MM"HGU]_eKf"fmqm}m}M~ $ : :64]b : cI6:6F6FyQR|U^_`_aUb6c3K8$X.F$X.F"a'%fo-||~0#%//?|'!ww}}XhG\-]^ %'+HXF[,\^b'cH t,t9{2!#d)+i r   	 ! `'')&'H9U]K^'^__`   sI   0H" 4C,G*  H" !,G* H" 6G* H" G* H" *5HH" "H7c                   | j                   r_| j                  rSt        j                  d| j                  z  | j                         | j                   j                  | j                         d | _        d | _         d| _        y )NzWINRM CLOSE SHELL: %sr   F)r-   r.   ro   r   r[   close_shellr'  rJ  s    r   r@  zConnection.close  sZ    ==T]]MM1DMMAHXHXMYMM%%dmm4r   )r:   t.Anyr;   r  returnNone)r  r  )r   r   rT   r   r  r  )r  winrm.Protocol)r   r   r   t.Iterable[tuple[bytes, bool]]r  r  )F)r-   r  r.   r   r   r   r   bytesr   boolr  r  )r-   r  r.   r   r   r   r  ztuple[bytes, bytes, int, bool])
r-   r  r.   r   r   r   r  r  r  ztuple[bytes, bytes, int])r   FN)
r   r   r:   zt.Iterable[bytes]r4  r  r   r  r  tuple[int, bytes, bytes])r   r  r:   ztuple[bytes, ...]r%  r  r  r   )r  r#   )i@ )rM  r  rN  r   r  r  )NT)r]  r   rT  zbytes | NonerU  r  r  r  )i )rj  r   rk  r   rN  r   r  r  )rj  r   rk  r   r  r  )r   r   r   __doc__rG   !module_implementation_preferencesallow_executablehas_pipeliningallow_extrasr2   r|   r   r   r   r   r  r!  r<  r)  rA  rK  rR  rZ  rp  ru  r  r@  __classcell__)r<   s   @r   r#   r#      sg   ,I(<%NL@$F[T^F@9Jv#J5(M (M (M 	(M
 
((M^ M M M 	M
 M 
"M@ #%9=SESE  SE 	SE
 7SE 
"SEr $)	   !	
 
BRl <K|D!L r   r#   )O
__future__r   DOCUMENTATIONr   r5   r   r   r   r-  r   r   r   r   typingtxml.etree.ElementTreeetreeElementTreer  inspectr   urllib.parser   rg   rL   ImportErroransibler   r3   ansible.errorsr   r   r	   ansible.module_utils.json_utilsr
   )ansible.module_utils.parsing.convert_boolr   +ansible.module_utils.common.text.convertersr   r   r   ansible.plugins.connectionr    ansible.plugins.shell.powershellr   r   PowerShellBaseansible.utils.hashingr   ansible.utils.displayr   r$   winrm.exceptionsr   r   r   winrm.protocolr   requests.exceptionsr1  rD  rE  r   r   r   r   rF  rG  r   r   rd   r    r2   rv   r:   r   r   ro   r#   r   r   r   <module>r     s  
 #Zx   	 	        " " " #	M # A . B = T T 5 : H - )	\\'I
0M
 
	 w  !7!78W\\!K
M )s
  s
 E  		.  I  )   M  		  Msx   D D) 9D?  E 9E+ E= D&%D&)D<.D77D<?EEE(E##E(+E:5E:=FF