U N9a)_@sdZddlmZddlZddlZddlmmZddl Z ddl m Z ddl m Z ddlmZmZmZddd d ZGd d d eZdS) z@Contains client side logic of WinRM SOAP protocol implementation)unicode_literalsN) text_type) Transport) WinRMErrorWinRMTransportErrorWinRMOperationTimeoutErrorz'http://www.w3.org/2003/05/soap-envelopez0http://schemas.xmlsoap.org/ws/2004/08/addressingz4http://schemas.microsoft.com/wbem/wsman/1/wsmanfault)soapenvsoapaddrZ wsmanfaultc@seZdZdZdZdZdZdZddddddd ddd d eedd d d d fddZd&ddZ d'ddZ ddZ d(ddZ d)ddZ ddZd*d d!Zd"d#Zd$d%ZdS)+ProtocolzThis is the main class that does the SOAP request/response logic. There are a few helper classes, but pretty much everything comes through here first. iXen-US plaintextNHTTPZlegacy_requestsvalidateFautoTcCsz t| } Wn2tk r>}ztdt|W5d}~XYnXz t|}Wn2tk r~}ztdt|W5d}~XYnX|| ks|dkrtd| |_||_tj|_tj |_ t |||||||| | |j| | ||||||d|_ ||_ ||_||_||_||_| |_| |_||_||_dS)ap @param string endpoint: the WinRM webservice endpoint @param string transport: transport type, one of 'plaintext' (default), 'kerberos', 'ssl', 'ntlm', 'credssp' # NOQA @param string username: username @param string password: password @param string realm: unused @param string service: the service name, default is HTTP @param string keytab: the path to a keytab file if you are using one @param string ca_trust_path: Certification Authority trust path. If server_cert_validation is set to 'validate': 'legacy_requests'(default) to use environment variables, None to explicitly disallow any additional CA trust path Any other value will be considered the CA trust path to use. @param string cert_pem: client authentication certificate file path in PEM format # NOQA @param string cert_key_pem: client authentication certificate key file path in PEM format # NOQA @param string server_cert_validation: whether server certificate should be validated on Python versions that suppport it; one of 'validate' (default), 'ignore' #NOQA @param bool kerberos_delegation: if True, TGT is sent to target server to allow multiple hops # NOQA @param int read_timeout_sec: maximum seconds to wait before an HTTP connect/read times out (default 30). This value should be slightly higher than operation_timeout_sec, as the server can block *at least* that long. # NOQA @param int operation_timeout_sec: maximum allowed time in seconds for any single wsman HTTP operation (default 20). Note that operation timeouts while receiving output (the only wsman operation that should take any significant time, and where these timeouts are expected) will be silently retried indefinitely. # NOQA @param string kerberos_hostname_override: the hostname to use for the kerberos exchange (defaults to the hostname in the endpoint URL) @param bool message_encryption_enabled: Will encrypt the WinRM messages if set to True and the transport auth supports message encryption (Default True). @param string proxy: Specify a proxy for the WinRM connection to use. 'legacy_requests'(default) to use environment variables, None to disable proxies completely or the proxy URL itself. z+failed to parse read_timeout_sec as int: %sNz0failed to parse operation_timeout_sec as int: %szMread_timeout_sec must exceed operation_timeout_sec, and both must be non-zero)endpointusernamepasswordrealmservicekeytab ca_trust_pathcert_pem cert_key_pemread_timeout_secserver_cert_validationkerberos_delegationkerberos_hostname_overrideZ auth_methodmessage_encryptioncredssp_disable_tlsv1_2send_cbtproxy)int ValueErrorstrrroperation_timeout_secr DEFAULT_MAX_ENV_SIZEZ max_env_szDEFAULT_LOCALElocaler transportrrrrrrrrr!)selfrr+rrrrrrrrrrrr'rr r!r"r#ver.C:\Users\Justin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\winrm/protocol.py__init__sV% " "zProtocol.__init__stdin stdout stderrc Csd|jdddi} | dd} ddt|dd t|dgi| d <| dd id i} || d <|| d<|rz|| d<|r|| d<|r| didg} |D]\} }| | |dq|t| }t |}t dd| dDj S)a Create a Shell on the destination host @param string i_stream: Which input stream to open. Leave this alone unless you know what you're doing (default: stdin) @param string o_stream: Which output stream to open. Leave this alone unless you know what you're doing (default: stdout stderr) @param string working_directory: the directory to create the shell in @param dict env_vars: environment variables to set for the shell. For instance: {'PATH': '%PATH%;c:/Program Files (x86)/Git/bin/', 'CYGWIN': 'nontsec codepage:utf8'} @returns The ShellId from the SOAP response. This is our open shell instance on the remote machine. @rtype string env:Envelope;http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmdz5http://schemas.xmlsoap.org/ws/2004/09/transfer/Create) resource_uriaction env:Headerw:OptionZWINRS_NOPROFILE@Name#textZWINRS_CODEPAGE w:OptionSetenv:Bodyz rsp:Shellzrsp:InputStreamszrsp:OutputStreamszrsp:WorkingDirectoryzrsp:IdleTimeOutzrsp:Environmentz rsp:Variablecss |]}|ddkr|VqdS)NameShellIdN)get.0noder.r.r/ sz&Protocol.open_shell...//*)_get_soap_headerr&upper setdefaultitemsappend send_message xmltodictunparseET fromstringnextfindalltext)r,Zi_streamZo_streamZworking_directoryZenv_varsZ noprofileZcodepageZlifetimeZ idle_timeoutreqheadershellenvkeyvalueresrootr.r.r/ open_shellosH    zProtocol.open_shellcCs|s t}ddtdtdddddd d d d d dddidddd|dddddddt|jd|dd|dd d }|rdd|di|dd<|S)Nz http://www.w3.org/2001/XMLSchemaz)http://www.w3.org/2001/XMLSchema-instancerr z3http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsdz1http://schemas.xmlsoap.org/ws/2004/09/enumerationz.http://schemas.xmlsoap.org/ws/2004/09/transferz.http://schemas.dmtf.org/wbem/wsman/1/wsman.xsdz3http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd7http://schemas.microsoft.com/wbem/wsman/1/windows/shellz0http://schemas.microsoft.com/wbem/wsman/1/configzhttp://windows-host:5985/wsmanz a:Addresstruez?http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous)@mustUnderstandr<Z153600zuuid:{0}falser )r_z @xml:langzPT{0}S) za:Toz a:ReplyTozw:MaxEnvelopeSizez a:MessageIDzw:Localez p:DataLocalezw:OperationTimeoutz w:ResourceURIza:Action) z @xmlns:xsdz @xmlns:xsiz @xmlns:envz@xmlns:az@xmlns:bz@xmlns:nz@xmlns:xz@xmlns:wz@xmlns:p @xmlns:rspz @xmlns:cfgr8z w:Selectorr@r:r8z w:SelectorSet)uuiduuid4xmlnsformatr$r')r,r7r6shell_id message_idrUr.r.r/rGsZ1 zProtocol._get_soap_headerc Cs.z|j|}|WStk r(}zzt|j}Wntk rN|YnX|dt}|dk rt |j |j d}|dt}|dk r| d|d<|ddkrt |dt}|dk r|j|d<|d t} | dk r| j|d <|d t} | dk r| j} nd } td | |W5d}~XYnXdS)Nzsoapenv:Body/soapenv:Fault)Ztransport_messageZhttp_status_codez+soapenv:Detail/wsmanfault:WSManFault[@Code]ZCodewsmanfault_codeZ 2150858793zsoapenv:Code/soapenv:Value fault_codez*soapenv:Code/soapenv:Subcode/soapenv:Value fault_subcodezsoapenv:Reason/soapenv:Textz(no error message in fault)z{0} (extended fault data: {1}))r+rLrrOrPZ response_text ExceptionfindrddictmessagecoderArrSrre) r,rnrespexr[faultZ fault_datarhrirj error_messager.r.r/rLs<            zProtocol.send_messagecCszft}d|jdd||di}|ddi|t|}t |}t dd| dDj }W5|rv|jXt|d d |kstd S) a Close the shell @param string shell_id: The shell id on the remote machine. See #open_shell @param bool close_session: If we want to close the requests's session. Allows to completely close all TCP connections to the server. @returns This should have more error checking but it just returns true for now. @rtype bool r4r5z5http://schemas.xmlsoap.org/ws/2004/09/transfer/Deleter6r7rfrgr>css|]}|jdr|VqdSZ RelatesToNtagendswithrBr.r.r/rE3s z'Protocol.close_shell..rFuuid:N)r+ close_sessionrbrcrGrIrLrMrNrOrPrQrRrSUUIDreplaceAssertionError)r,rfr{rgrTrZr[ relates_tor.r.r/ close_shells"   zProtocol.close_shellr.c Csd|jdd|di}|dd}ddt|dd t|dgi|d <|dd id i}d |i|d<|rdd|D} d| |d<|t|} t | } t dd| dDj } | S)a< Run a command on a machine with an open shell @param string shell_id: The shell id on the remote machine. See #open_shell @param string command: The command to run on the remote machine @param iterable of string arguments: An array of arguments for this command @param bool console_mode_stdin: (default: True) @param bool skip_cmd_shell: (default: False) @return: The CommandId from the SOAP response. This is the ID we need to query in order to get output. @rtype string r4r5z?http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Commandr6r7rfr8r9ZWINRS_CONSOLEMODE_STDINr:ZWINRS_SKIP_CMD_SHELLr=r>zrsp:CommandLiner<z rsp:CommandcSs$g|]}t|tr|n|dqS)zutf-8) isinstancerdecode)rCar.r.r/ dsz(Protocol.run_command.. z rsp:Argumentscss|]}|jdr|VqdS)Z CommandIdNrvrBr.r.r/rEis z'Protocol.run_command..rF) rGr&rHrIjoinrLrMrNrOrPrQrRrS) r,rfcommand argumentsZconsole_mode_stdinZskip_cmd_shellrTrUZcmd_lineZ unicode_argsrZr[ command_idr.r.r/ run_command?s@       zProtocol.run_commandc Cst}d|jdd||di}|ddidi}||d<d|d <|t|}t|}t d d | d Dj }t | d d|kstdS)ar Clean-up after a command. @see #run_command @param string shell_id: The shell id on the remote machine. See #open_shell @param string command_id: The command id on the remote machine. See #run_command @returns: This should have more error checking but it just returns true for now. @rtype bool r4r5z>http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signalrtr>z rsp:Signal @CommandIdzHhttp://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminatezrsp:Codecss|]}|jdr|VqdSrurvrBr.r.r/rEs z+Protocol.cleanup_command..rFryrzN)rbrcrGrIrLrMrNrOrPrQrRrSr|r}r~) r,rfrrgrTsignalrZr[rr.r.r/cleanup_commandns,   zProtocol.cleanup_commandcCst|tr|d}d|jdd|di}|ddididi}||d <d |d <|rfd |d <nd|d <d|d<t||d<|t |dS)a Send input to the given shell and command. @param string shell_id: The shell id on the remote machine. See #open_shell @param string command_id: The command id on the remote machine. See #run_command @param string stdin_input: The input unicode string or byte string to be sent. @param bool end: Boolean value which will close the stdin stream. If end=True then the stdin pipe to the remotely running process will be closed causing the next read by the remote process to stdin to return a EndOfFile error; the behavior of each process when this error is encountered is defined by the process, but most processes ( like CMD and powershell for instance) will just exit. Setting this value to 'True' means that no more input will be able to be sent to the process and attempting to do so should result in an error. @return: None 437r4r5zzrsp:Sendz rsp:Streamrr1r;r^z@Endr`r]rar<N) rrencoderGrIbase64 b64encoderLrMrN)r,rfrZ stdin_inputendrTZstdin_enveloper.r.r/send_command_inputs,   zProtocol.send_command_inputc Cslgg}}d}|sVz,|||\}}}}||||Wqtk rRYqXqd|d||fS)a% Get the Output of the given shell and command @param string shell_id: The shell id on the remote machine. See #open_shell @param string command_id: The command id on the remote machine. See #run_command #@return [Hash] Returns a Hash with a key :exitcode and :data. Data is an Array of Hashes where the cooresponding key # is either :stdout or :stderr. The reason it is in an Array so so we can get the output in the order it ocurrs on # the console. F)_raw_get_command_outputrKrr) r,rfrZ stdout_bufferZ stderr_buffer command_donestdoutstderr return_coder.r.r/get_command_outputs   zProtocol.get_command_outputc Cs&d|jdd|di}|ddididi}||d<d |d <|t|}t|}d d |d D}d}} d} |D]V} | jsq| j ddkr|t | j d7}q| j ddkr| t | j d7} qt dd |d Ddk} | rttdd|d Dj} || | | fS)Nr4r5z?http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receiverr>z rsp:Receivezrsp:DesiredStreamrr2r<cSsg|]}|jdr|qS)ZStreamrvrBr.r.r/rs z4Protocol._raw_get_command_output..rFrr?rasciircSs"g|]}|dddr|qS)StaterzzCommandState/Done)rArxrBr.r.r/rsrcss|]}|jdr|VqdS)ZExitCodeNrvrBr.r.r/rEs z3Protocol._raw_get_command_output..)rGrIrLrMrNrOrPrRrSattribr b64decoderlenr$rQ) r,rfrrTstreamrZr[Z stream_nodesrrrZ stream_noderr.r.r/rsL  z Protocol._raw_get_command_output)r1r2NNFr3NN)NNNN)T)r.TF)F)__name__ __module__ __qualname____doc__ZDEFAULT_READ_TIMEOUT_SECZDEFAULT_OPERATION_TIMEOUT_SECr(r)r0r\rGrLrrrrrrr.r.r.r/r s^ P B ?, % / !r )r __future__rrrbxml.etree.ElementTreeetree ElementTreerOrMsixrZwinrm.transportrZwinrm.exceptionsrrrrdobjectr r.r.r.r/s