Python windows run as user

How to run python process as another Windows user

With the subprocess.Popen we can call any executable under the currently logged-in user credentials like so:

Would it be possible to call and execute the same executable.exe under another user credentials assuming that the user’s name and the password are known, such as:

1 Answer 1

This question doesn’t really have anything to do with Python. You’re just asking how to execute a command as another user from the Windows command line. The runas program will do that for you:

Usage as given in the link:

  • /profile
    Loads the user’s profile. This is the default. This parameter cannot be used with the /netonly parameter.
  • /no profile
    Specifies that the user’s profile is not to be loaded. This allows the application to load more quickly, but it can also cause a malfunction in some applications.
  • /env
    Specifies that the current network environment be used instead of the user’s local environment.
  • /netonly
    Indicates that the user information specified is for remote access only. This parameter cannot be used with the /profile parameter.
  • /savecred
    Indicates if the credentials have been previously saved by this user. This parameter is not available and will be ignored on Windows Vista Home or Windows Vista Starter Editions. This parameter cannot be used with the /smartcard parameter.
  • /smartcard
    Indicates whether the credentials are to be supplied from a smartcard. This parameter cannot be used with the /savecred parameter.
  • /showtrustlevels
    Displays the trust levels that can be used as arguments to /trustlevel.
  • /trustlevel
    Specifies the level of authorization at which the application is to run. Use /showtrustlevels to see the trust levels available.
  • /user: » »
    Specifies the name of the user account under which to run the program, the program name, and the path to the program file. The user account name format should be @ or \.
  • /?
    Displays help at the command prompt.

It doesn’t look like there’s any built-in way to provide the user’s password, so you’ll have to set up input and output pipes to be able to provide it when prompted. You may find this task easier with Pexpect, which is a third-party module for automating subprocess keyboard interaction.

What user do python scripts run as in windows? [duplicate]

I’m trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn’t have rights?

is what I get when I run the script.
I’ve tried

they all return the same error.

7 Answers 7

We’ve had issues removing files and directories on Windows, even if we had just copied them, if they were set to ‘readonly’. shutil.rmtree() offers you sort of exception handlers to handle this situation. You call it and provide an exception handler like this:

You might want to try that.

I’ve never used Python, but I would assume it runs as whatever user executes the script.

The scripts have no special user, they just run under the currently logged-in user which executed the script.

Have you tried checking that:

  • you are trying to delete a valid path? and that
  • the path has no locked files?

How are you running the script? From an interactive console session? If so, just open up a DOS command window (using cmd) and type ‘whoami’. That is who you are running the scripts interactively.

Ok I saw your edits just now. why don’t you print the path and check the properties to see if the user account running the scripts has the required privileges?

If whoami does not work on your version of Windows, you may use the environment variables like SET USERNAME and SET DOMAINNAME from your command window.

@ThomasH : another brick to the wall.

On unix systems, you have to ensure that parent directory is writeable too. Here is another version :

Читайте также:  Windows sidebar для windows x64

How to run process as different user from windows service

I’ve created a service which is already started before a user logs in. The service is running as «Network Service» user. From time to time it has to run an update process which needs to be run as a domain user. The case that no user is logged in while the update process is started has to be considered. It is not possible to run the service as the domain user because of password rules (need to be changed from time to time). The password for the domain user is fetched from another machine when the update process needs to be run. My problem is that the service is able to create the process as the domain user with CreateProcessWithLogonW but as soon as the process is started it is immediately destroyed. Return value is 0 and I get no stdout and no stderr. The only hint I get is an entry in the event log with the error code 0xc0000142. I’ve also tried several other solutions I’ve found on the web. But no solution works. For example I’ve also tried LogonUser -> Adjust privileges -> CreateProcessAsUser. The OS is Windows 7. The update program is just a console application. I only need return code, stdout and stderr. No window should popup when the process is started. Can anyone help me with a working solution? Best would be an example in Python. Thanks in advance. Best regards, Martin

Update: Currently I ended up with the following code:

But it doesn’t work. The process is created with the desired user, but when it is started it is immediately destroyed. Return code is 0. No output on stdout and no stderr. GetLastError also returns 0. No entry is shown in the event viewer.

How do you run a Python script as a service in Windows?

I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.

I am currently aiming for Python and the Django framework as the technologies to implement that service with. I’m pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.

Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)? I won’t necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.

Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: How is Windows aware of my service? Can I manage it with the native Windows utilities? What is the equivalent of putting a start/stop script in /etc/init.d?

13 Answers 13

Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).

This is a basic skeleton for a simple service:

Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method

Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?

I stumbled across the wonderful Non-sucking Service Manager, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.

I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.

Читайте также:  Delete node js mac os

The simplest way is to use the: NSSM — the Non-Sucking Service Manager. Just download and unzip to a location of your choosing. It’s a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no «installation» is needed. The zip contains a 64-bit and a 32-bit version of the utility. Either should work well on current systems (you can use the 32-bit version to manage services on 64-bit systems).

GUI approach

1 — install the python program as a service. Open a Win prompt as admin

2 — On NSSM´s GUI console:

Startup directory: C:\Python27

3 — check the created services on services.msc

Scripting approach (no GUI)

This is handy if your service should be part of an automated, non-interactive procedure, that may be beyond your control, such as a batch or installer script. It is assumed that the commands are executed with administrative privileges.

For convenience the commands are described here by simply referring to the utility as nssm.exe . It is advisable, however, to refer to it more explicitly in scripting with its full path c:\path\to\nssm.exe , since it’s a self-contained executable that may be located in a private path that the system is not aware of.

1. Install the service

You must specify a name for the service, the path to the proper Python executable, and the path to the script:

Alternatively you may want your Python app to be started as a Python module. One easy approach is to tell nssm that it needs to change to the proper starting directory, as you would do yourself when launching from a command shell:

This approach works well with virtual environments and self-contained (embedded) Python installs. Just make sure to have properly resolved any path issues in those environments with the usual methods. nssm has a way to set environment variables (e.g. PYTHONPATH) if needed, and can also launch batch scripts.

2. To start the service

3. To stop the service

4. To remove the service, specify the confirm parameter to skip the interactive confirmation.

The simplest way to achieve this is to use native command sc.exe:

References:

There are a couple alternatives for installing as a service virtually any Windows executable.

Method 1: Use instsrv and srvany from rktools.exe

For Windows Home Server or Windows Server 2003 (works with WinXP too), the Windows Server 2003 Resource Kit Tools comes with utilities that can be used in tandem for this, called instsrv.exe and srvany.exe. See this Microsoft KB article KB137890 for details on how to use these utils.

For Windows Home Server, there is a great user friendly wrapper for these utilities named aptly «Any Service Installer».

Method 2: Use ServiceInstaller for Windows NT

There is another alternative using ServiceInstaller for Windows NT (download-able here) with python instructions available. Contrary to the name, it works with both Windows 2000 and Windows XP as well. Here are some instructions for how to install a python script as a service.

Installing a Python script

Run ServiceInstaller to create a new service. (In this example, it is assumed that python is installed at c:\python25)

After installing, open the Control Panel’s Services applet, select and start the PythonTest service.

After my initial answer, I noticed there were closely related Q&A already posted on SO. See also:

Step by step explanation how to make it work :

1- First create a python file according to the basic skeleton mentioned above. And save it to a path for example : «c:\PythonFiles\AppServerSvc.py»

2 — On this step we should register our service.

Run command prompt as administrator and type as:

sc create TestService binpath= «C:\Python36\Python.exe c:\PythonFiles\AppServerSvc.py» DisplayName= «TestService» start= auto

the first argument of binpath is the path of python.exe

second argument of binpath is the path of your python file that we created already

Don’t miss that you should put one space after every «=» sign.

Then if everything is ok, you should see

Now your python service is installed as windows service now. You can see it in Service Manager and registry under :

3- Ok now. You can start your service on service manager.

You can execute every python file that provides this service skeleton.

Example script to run as a service taken from pythonhosted.org:

Create and start service

Stop and delete service

Читайте также:  Изменить меню начала цвета windows 10

nssm in python 3+

(I converted my .py file to .exe with pyinstaller)

nssm: as said before

    run nssm install

On NSSM´s console:

path: path\to\your\program.exe

Startup directory: path\to\your\ #same as the path but without your program.exe

Arguments: empty

If you don’t want to convert your project to .exe

  • create a .bat file with python <>
  • and set the path to the .bat file

I started hosting as a service with pywin32.

Everything was well but I met the problem that service was not able to start within 30 seconds (default timeout for Windows) on system startup. It was critical for me because Windows startup took place simultaneous on several virtual machines hosted on one physical machine, and IO load was huge. Error messages were:

Error 1053: The service did not respond to the start or control request in a timely fashion.

Error 7009: Timeout (30000 milliseconds) waiting for the service to connect.

I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.

A complete pywin32 example using loop or subthread

After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.

This is complete working code for one loop-based and one thread-based solution. It may work on both python 2 and 3, although I’ve only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the waitress wsgi server that does not have a standard way to shut down gracefully.

I would also like to note that there seems to be loads of examples out there, like this that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?

That said I still feel I’m on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing misleading here.

To run simply copy the code to a file and follow the instructions.

update:

Use a simple flag to terminate thread. The important bit is that «thread done» prints.
For a more elaborate example exiting from an uncooperative server thread see my post about the waitress wsgi server.

The accepted answer using win32serviceutil works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). You write and comfortably debug a normal python program and when it finally works you use NSSM to install it as a service in less than a minute:

From an elevated (admin) command prompt you run nssm.exe install NameOfYourService and you fill-in these options:

  • path: (the path to python.exe e.g. C:\Python27\Python.exe )
  • Arguments: (the path to your python script, e.g. c:\path\to\program.py )

By the way, if your program prints useful messages that you want to keep in a log file NSSM can also handle this and a lot more for you.

This answer is plagiarizer from several sources on StackOverflow — most of them above, but I’ve forgotten the others — sorry. It’s simple and scripts run «as is». For releases you test you script, then copy it to the server and Stop/Start the associated service. And it should work for all scripting languages (Python, Perl, node.js), plus batch scripts such as GitBash, PowerShell, even old DOS bat scripts. pyGlue is the glue that sits between Windows Services and your script.

Now there’s a bit of editing and you don’t want all your services called ‘pyGlue’. So there’s a script (build.sh) to plug in the bits and create a customized ‘pyGlue’ and create an ‘.exe’. It is this ‘.exe’ which gets installed as a Windows Service. Once installed you can set it to run automatically.

Installation — copy the ‘.exe’ the server and the script to the specified folder. Run the ‘.exe’, as Administrator, with the ‘install’ option. Open Windows Services, as Adminstrator, and start you service. For upgrade, just copy the new version of the script and Stop/Start the service.

Оцените статью