Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running python script as another user

Tags:

python

linux

On a Linux box I want to run a Python script as another user.

I've already made a wrapper program in C++ that calls the script, since I've realized that the ownership of running the script is decided by the ownership of the python interpreter. After that I change the C++ program to a different user and run the C++ program.

This setup doesn't seem to be working. Any ideas?

like image 475
johannix Avatar asked Sep 30 '09 16:09

johannix


People also ask

How do I share a python script?

Use the "Share" button in the Editor The PythonAnywhere editor (from the Files tab) gives you the option to share a file -- look for the paperclip icon at the top of the editor. This only works for single files, and people you share with will need a PythonAnywhere account.

How do I run a script without another password?

Using Sudoers File You can also su to another user without requiring a password by making some changes in the sudoers file. In this case, the user (for example aaronk) who will switch to another user account (for example postgres) should be in the sudoers file or in the sudo group to be able to invoke the sudo command.


1 Answers

You can set the user with os.setuid(), and you can get the uid with pwd. Like so:

>>> import pwd, os
>>> uid = pwd.getpwnam('root')[2]
>>> os.setuid(uid)

Obviously this only works if the user or executable has the permission to do so. Exactly how to set that up I don't know. Obviously it works if you are root. I think you may need to the the setuid flag on the Python executable, and that would leave a WHOPPING security hole. possible that's permittable if the user you setuid too is a dedicated restricted user that can't do anything except whatever you need to do.

Unix security, based on users and setuiding and stuff, is not very good or practical, and it's easy to leave big security holes. A more secure option is actually to do this client-server typish, so you have a demon that does everything, and the client talks to it. The demon can then run with a higher security than the users, but the users would have to give a name and password when they run the script, or identify themselves with some public/private key or somesuch.

like image 143
Lennart Regebro Avatar answered Sep 28 '22 12:09

Lennart Regebro