
    VhJ                     ^   d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZmZ d dlmZmZ d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mZmZ d dlZdZdZ!	 d dl"Z"d dl#m$Z$ dZ%d Z&d Z'e(dk(  r e'        yy# e$ r  e	j@                         ZdZY =w xY w# e$ r  e	j@                         Z!dZ%Y Lw xY w)    )absolute_importdivisionprint_functiona  
---
module: psexec
short_description: Runs commands on a remote Windows host based on the PsExec
  model
description:
- Runs a remote command from a Linux host to a Windows host without WinRM being
  set up.
- Can be run on the Ansible controller to bootstrap Windows hosts to get them
  ready for WinRM.
options:
  hostname:
    description:
    - The remote Windows host to connect to, can be either an IP address or a
      hostname.
    type: str
    required: yes
  connection_username:
    description:
    - The username to use when connecting to the remote Windows host.
    - This user must be a member of the C(Administrators) group of the Windows
      host.
    - Required if the Kerberos requirements are not installed or the username
      is a local account to the Windows host.
    - Can be omitted to use the default Kerberos principal ticket in the
      local credential cache if the Kerberos library is installed.
    - If I(process_username) is not specified, then the remote process will run
      under a Network Logon under this account.
    type: str
  connection_password:
    description:
    - The password for I(connection_user).
    - Required if the Kerberos requirements are not installed or the username
      is a local account to the Windows host.
    - Can be omitted to use a Kerberos principal ticket for the principal set
      by I(connection_user) if the Kerberos library is installed and the
      ticket has already been retrieved with the C(kinit) command before.
    type: str
  port:
    description:
    - The port that the remote SMB service is listening on.
    type: int
    default: 445
  encrypt:
    description:
    - Will use SMB encryption to encrypt the SMB messages sent to and from the
      host.
    - This requires the SMB 3 protocol which is only supported from Windows
      Server 2012 or Windows 8, older versions like Windows 7 or Windows Server
      2008 (R2) must set this to C(no) and use no encryption.
    - When setting to C(no), the packets are in plaintext and can be seen by
      anyone sniffing the network, any process options are included in this.
    type: bool
    default: yes
  connection_timeout:
    description:
    - The timeout in seconds to wait when receiving the initial SMB negotiate
      response from the server.
    type: int
    default: 60
  executable:
    description:
    - The executable to run on the Windows host.
    type: str
    required: yes
  arguments:
    description:
    - Any arguments as a single string to use when running the executable.
    type: str
  working_directory:
    description:
    - Changes the working directory set when starting the process.
    type: str
    default: C:\Windows\System32
  asynchronous:
    description:
    - Will run the command as a detached process and the module returns
      immediately after starting the process while the process continues to
      run in the background.
    - The I(stdout) and I(stderr) return values will be null when this is set
      to C(yes).
    - The I(stdin) option does not work with this type of process.
    - The I(rc) return value is not set when this is C(yes)
    type: bool
    default: no
  load_profile:
    description:
    - Runs the remote command with the user's profile loaded.
    type: bool
    default: yes
  process_username:
    description:
    - The user to run the process as.
    - This can be set to run the process under an Interactive logon of the
      specified account which bypasses limitations of a Network logon used when
      this isn't specified.
    - If omitted then the process is run under the same account as
      I(connection_username) with a Network logon.
    - Set to C(System) to run as the builtin SYSTEM account, no password is
      required with this account.
    - If I(encrypt) is C(no), the username and password are sent as a simple
      XOR scrambled byte string that is not encrypted. No special tools are
      required to get the username and password just knowledge of the protocol.
    type: str
  process_password:
    description:
    - The password for I(process_username).
    - Required if I(process_username) is defined and not C(System).
    type: str
  integrity_level:
    description:
    - The integrity level of the process when I(process_username) is defined
      and is not equal to C(System).
    - When C(default), the default integrity level based on the system setup.
    - When C(elevated), the command will be run with Administrative rights.
    - When C(limited), the command will be forced to run with
      non-Administrative rights.
    type: str
    choices:
    - limited
    - default
    - elevated
    default: default
  interactive:
    description:
    - Will run the process as an interactive process that shows a process
      Window of the Windows session specified by I(interactive_session).
    - The I(stdout) and I(stderr) return values will be null when this is set
      to C(yes).
    - The I(stdin) option does not work with this type of process.
    type: bool
    default: no
  interactive_session:
    description:
    - The Windows session ID to use when displaying the interactive process on
      the remote Windows host.
    - This is only valid when I(interactive) is C(yes).
    - The default is C(0) which is the console session of the Windows host.
    type: int
    default: 0
  priority:
    description:
    - Set the command's priority on the Windows host.
    - See U(https://msdn.microsoft.com/en-us/library/windows/desktop/ms683211.aspx)
      for more details.
    type: str
    choices:
    - above_normal
    - below_normal
    - high
    - idle
    - normal
    - realtime
    default: normal
  show_ui_on_logon_screen:
    description:
    - Shows the process UI on the Winlogon secure desktop when
      I(process_username) is C(System).
    type: bool
    default: no
  process_timeout:
    description:
    - The timeout in seconds that is placed upon the running process.
    - A value of C(0) means no timeout.
    type: int
    default: 0
  stdin:
    description:
    - Data to send on the stdin pipe once the process has started.
    - This option has no effect when I(interactive) or I(asynchronous) is
      C(yes).
    type: str
requirements:
- pypsexec
- smbprotocol[kerberos] for optional Kerberos authentication
notes:
- This module requires the Windows host to have SMB configured and enabled,
  and port 445 opened on the firewall.
- This module will wait until the process is finished unless I(asynchronous)
  is C(yes), ensure the process is run as a non-interactive command to avoid
  infinite hangs waiting for input.
- The I(connection_username) must be a member of the local Administrator group
  of the Windows host. For non-domain joined hosts, the
  C(LocalAccountTokenFilterPolicy) should be set to C(1) to ensure this works,
  see U(https://support.microsoft.com/en-us/help/951016/description-of-user-account-control-and-remote-restrictions-in-windows).
- For more information on this module and the various host requirements, see
  U(https://github.com/jborean93/pypsexec).
seealso:
- module: ansible.builtin.raw
- module: ansible.windows.win_command
- module: community.windows.win_psexec
- module: ansible.windows.win_shell
author:
- Jordan Borean (@jborean93)
a+  
- name: Run a cmd.exe command
  community.windows.psexec:
    hostname: server
    connection_username: username
    connection_password: password
    executable: cmd.exe
    arguments: /c echo Hello World

- name: Run a PowerShell command
  community.windows.psexec:
    hostname: server.domain.local
    connection_username: username@DOMAIN.LOCAL
    connection_password: password
    executable: powershell.exe
    arguments: Write-Host Hello World

- name: Send data through stdin
  community.windows.psexec:
    hostname: 192.168.1.2
    connection_username: username
    connection_password: password
    executable: powershell.exe
    arguments: '-'
    stdin: |
      Write-Host Hello World
      Write-Error Error Message
      exit 0

- name: Run the process as a different user
  community.windows.psexec:
    hostname: server
    connection_user: username
    connection_password: password
    executable: whoami.exe
    arguments: /all
    process_username: anotheruser
    process_password: anotherpassword

- name: Run the process asynchronously
  community.windows.psexec:
    hostname: server
    connection_username: username
    connection_password: password
    executable: cmd.exe
    arguments: /c rmdir C:\temp
    asynchronous: true

- name: Use Kerberos authentication for the connection (requires smbprotocol[kerberos])
  community.windows.psexec:
    hostname: host.domain.local
    connection_username: user@DOMAIN.LOCAL
    executable: C:\some\path\to\executable.exe
    arguments: /s

- name: Disable encryption to work with WIndows 7/Server 2008 (R2)
  community.windows.psexec:
    hostanme: windows-pc
    connection_username: Administrator
    connection_password: Password01
    encrypt: false
    integrity_level: elevated
    process_username: Administrator
    process_password: Password01
    executable: powershell.exe
    arguments: (New-Object -ComObject Microsoft.Update.Session).CreateUpdateInstaller().IsBusy

- name: Download and run ConfigureRemotingForAnsible.ps1 to setup WinRM
  community.windows.psexec:
    hostname: '{{ hostvars[inventory_hostname]["ansible_host"] | default(inventory_hostname) }}'
    connection_username: '{{ ansible_user }}'
    connection_password: '{{ ansible_password }}'
    encrypt: true
    executable: powershell.exe
    arguments: '-'
    stdin: |
      $ErrorActionPreference = "Stop"
      $sec_protocols = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::SystemDefault
      $sec_protocols = $sec_protocols -bor [Net.SecurityProtocolType]::Tls12
      [Net.ServicePointManager]::SecurityProtocol = $sec_protocols
      $url = "https://github.com/ansible/ansible-documentation/raw/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
      Invoke-Expression ((New-Object Net.WebClient).DownloadString($url))
      exit
  delegate_to: localhost
aW  
msg:
  description: Any exception details when trying to run the process
  returned: module failed
  type: str
  sample: 'Received exception from remote PAExec service: Failed to start "invalid.exe". The system cannot find the file specified. [Err=0x2, 2]'
stdout:
  description: The stdout from the remote process
  returned: success and interactive or asynchronous is 'no'
  type: str
  sample: Hello World
stderr:
  description: The stderr from the remote process
  returned: success and interactive or asynchronous is 'no'
  type: str
  sample: Error [10] running process
pid:
  description: The process ID of the asynchronous process that was created
  returned: success and asynchronous is 'yes'
  type: int
  sample: 719
rc:
  description: The return code of the remote process
  returned: success and asynchronous is 'no'
  type: int
  sample: 0
N)AnsibleModulemissing_required_lib)to_bytesto_text)client)PypsexecExceptionPDUExceptionSCMRException)ProcessPriority)SMBExceptionSMBAuthenticationErrorSMBResponseExceptionTF)inquire_sec_context_by_oidc                     	  |j                           y # t        t        f$ r'}| j                  dt	        |      z         Y d }~y d }~ww xY w)Nz3Failed to cleanup PAExec service and executable: %s)remove_servicer   r   warnr	   )moduler
   excs      l/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/windows/plugins/modules/psexec.pyremove_artifactsr   ]  sK    $+, $Icl# 	$ 	$$s    A
AA
c                     t        dMi dt        dd      dt        d      dt        dd      d	t        d
dd      dt        dd      dt        d
d      dt        dd      dt        d      dt        dd      dt        dd      dt        dd      dt        d      dt        dd      dt        ddg d      dt        dd      d t        d
d!      d"t        dd#g d$      d%t        dd      d&t        d
d!      d't        d      } t        d(      }t        | d)      }|j                  d   }|j                  d   }d}||j                         d*k(  rd}d }d }|||j	                  d+,       t
        s |j	                  t        d-      t        .       |j                  d   }|j                  d   }|j                  d   }|j                  d	   }	|j                  d   }
|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   d/k(  }|j                  d   d0k(  }|j                  d   }|j                  d    }t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  d$|j                  d"      }|j                  d%   }|j                  d&   }|j                  d'   }||&t        s |j	                  t        d1      t         2       t#        j$                  ||||	|
3      }	 |j'                  |4       d|d9<   |rt;        |d:;      nd }t        dMi d|d|d|d|d|d |d<|d=|d>|d?|d@|dA|d"|dB|dC|d'|}	 |j=                          	  |j>                  dMi |}tA        ||       |r	dF   |dG<   n#|r	dF   |dH<   nd!   |dI<   |dJ   |dK<   |dF   |dH<   	 |jC                           |jF                  dMi | y # t(        $ r(}|j	                  d5t+        |      z  ,       Y d }~d }~wt,        $ r)}|j	                  d6t+        |      z  ,       Y d }~-d }~wt.        $ r)}|j	                  d7t+        |      z  ,       Y d }~]d }~wt0        $ r)}|j	                  d8t+        |      z  ,       Y d }~d }~wt2        t4        f$ r&}|j	                  t+        |      ,       Y d }~d }~wt6        j8                  $ r&}|j	                  t+        |      ,       Y d }~d }~ww xY w# t2        t4        f$ r)}|j	                  dDt+        |      z  ,       Y d }~d }~ww xY w# t2        t4        f$ r)}|j	                  dEt+        |      z  ,       Y d }~d }~ww xY w# tA        ||       w xY w# t2        t4        f$ r(}|jE                  dLt+        |      z         Y d }~d }~ww xY w)NNhostnamestrT)typerequiredconnection_username)r   connection_password)r   no_logportintFi  )r   r   defaultencryptbool)r   r$   connection_timeout<   
executable	argumentsworking_directoryzC:\Windows\System32asynchronousload_profileprocess_usernameprocess_passwordintegrity_levelr$   )r$   elevatedlimited)r   r$   choicesinteractiveinteractive_sessionr   prioritynormal)above_normalbelow_normalhighidler7   realtimeshow_ui_on_logon_screenprocess_timeoutstdin)changed)argument_specsupports_check_modesystemz_parameters are required together when not running as System: process_username, process_password)msgpypsexec)rD   	exceptionr1   r2   gssapi)rD   	execption)serverusernamepasswordr"   r%   )timeoutz#Failed to authenticate over SMB: %sz@Received unexpected SMB response when opening the connection: %sz.Received an exception with RPC PDU message: %szDReceived an exception when dealing with SCMR on the Windows host: %sr@   zutf-8)encodingrun_elevatedrun_limitedrJ   rK   use_system_accountworking_dirshow_ui_on_win_logontimeout_secondsz#Failed to create PAExec service: %sz.Received error when running remote process: %s   pidrcstdout   stderrz&Failed to close the SMB connection: %s )$dictr   paramslower	fail_jsonHAS_PYPSEXECr   PYPSEXEC_IMP_ERRr   ABOVE_NORMAL_PRIORITY_CLASSBELOW_NORMAL_PRIORITY_CLASSHIGH_PRIORITY_CLASSIDLE_PRIORITY_CLASSNORMAL_PRIORITY_CLASSREALTIME_PRIORITY_CLASSHAS_KERBEROSKERBEROS_IMP_ERRr
   Clientconnectr   r	   r   r   r   r   r   socketerrorr   create_servicerun_executabler   
disconnectr   	exit_json)module_argsresultr   r.   r/   
use_systemr   r   r    r"   r%   r'   r)   r*   r+   r,   r-   r1   r2   r4   r5   r6   r=   r>   r?   
win_clientr   b_stdinrun_argsproc_results                                 r   mainrx   e  s    540 e, !eD9 uuc:	
 &$/  UB7 UT2 E" E3IJ vu5 vt4 5) 56 %%GI  fe4!" !eQ7#$ 5(=>%* !%&% @+, %3-. /K2 F !!F
 }}%78}}%78J#(8(>(>(@H(L
#(8(@ 0 	1 1*=#3 	 	5 }}Z(H --(=> --(=>== DmmI&G';<|,Jk*I&9:==0L==0L}}./:=Hmm-.);G--.K --(=> (CC'CC3333!77#;; mmJ!H %mm,EFmm$56OMM'"E#':'B1(;#3 	 	5 h9L(;$'.0J+#56& F938huw/dG 		)2	AM	!	/:	 0	 		 ,3		
 "	
 -=	 &	 4E	 	 1H	 (	 07	H)!!#
-/j//;(;
 	,#Au	"1~t&q>x&q>x"1~tM Fvw " -B&s|, 	- 	- B 24;CLA 	B 	B -M&s|, 	- 	- D 46=clC 	D 	D+, +WS\**<< +WS\**+$ +, )B"3<( 	) 	)) +, )M"3<( 	) 	)) 	, +, M<ws|KLLMs   ;Q V .W ;X 	V	'R

V	R::V	S**V	6TV	,UV	#VV	WV??WW?W:4X :W??X XY
"YY
__main__))
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURN	tracebackansible.module_utils.basicr   r   ansible.module_utils._textr   r	   r`   rE   r
   pypsexec.exceptionsr   r   r   pypsexec.paexecr   smbprotocol.exceptionsr   r   r   rk   r_   ImportError
format_excrh   rG   
gssapi.rawr   rg   r   rx   __name__rZ       r   <module>r      s    A @BHTl
8  J 8 
RR/ L
  5L$Up zF _  +y++-L  +y++-Ls#   &A3 B 3BBB,+B,