6

I am looking for a way to run part of python code/function to be run as the different user in Linux, instead of make another script.

For example:

def function1(args):
    # stuffs 

def function2():
    # stuffs

I would like to call the function function1 from function2 with passing couple of arguments and the function1 should accept those arguments and execute the stuffs as the different user and return the result. Since I have to call some stuffs in between during the entire execution and so I don't want to create multiple scripts for small piece of code. Basically am trying to connect database in the function function1 (the database connection can be done as that particular user only) and run the query and get the result.

6
  • 2
    You can't do that. You must use two processes. Commented Jul 24, 2018 at 14:20
  • 1
    do you mean a different database user or a different linux user?
    – Mohl
    Commented Jul 24, 2018 at 14:22
  • @Mohl Different linux user is fine for me.
    – Karthi1234
    Commented Jul 24, 2018 at 14:25
  • I don't think that's possible unless you're sshing into another computer Commented Jul 24, 2018 at 14:32
  • @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 SSHing is required only when we try to execute something on the remote server. But in my case the user resides on the same system only.
    – Karthi1234
    Commented Jul 24, 2018 at 15:07

1 Answer 1

8

This is a bit more difficult than you might expect. First of all, Python provides os.setuid() and os.setguid() to change the current user/group of the running script and you can create a context manager to do your bidding for you and automatically revert back to the currently executing user:

import os

class UnixUser(object):

    def __init__(self, uid, gid=None):
        self.uid = uid
        self.gid = gid

    def __enter__(self):
        self.cache = os.getuid(), os.getgid()  # cache the current UID and GID
        if self.gid is not None:  # GID change requested as well
            os.setgid(self.gid)
        os.setuid(self.uid)  # set the UID for the code within the `with` block

    def __exit__(self, exc_type, exc_val, exc_tb):
        # optionally, deal with the exception
        os.setuid(self.cache[0])  # revert back to the original UID
        os.setgid(self.cache[1])  # revert back to the original GID

And to test it:

def test():
    print("Current UID: {}".format(os.getuid()))  # prints the UID of the executing user

test()  # executes as the current user

with UnixUser(105):
    test()  # executes as the user with UID: 105

You can even create a neat decorator to select that some functions should always execute as another user:

def as_unix_user(uid, gid=None):  # optional group
    def wrapper(func):
        def wrapped(*args, **kwargs):
            with UnixUser(uid, gid):
                return func(*args, **kwargs)  # execute the function
        return wrapped
    return wrapper

def test1():
    print("Current UID: {}".format(os.getuid()))  # prints the UID of the executing user

@as_unix_user(105)
def test2():
    print("Current UID: {}".format(os.getuid()))  # prints the UID of the executing user

test1()  # executes as the current user
test2()  # executes as the user with UID: 105

The kicker? Next to not being thread-safe, it will only work if both the current user, and the user you want to execute the function as, have CAP_SETUID and, optionally, CAP_SETGID capabilities.

You can get away with having only one user with these capabilities run the main script and then fork when necessary, changing the UID/GID only on the forked process:

import os

def as_unix_user(uid, gid=None):  # optional group
    def wrapper(func):
        def wrapped(*args, **kwargs):
            pid = os.fork()
            if pid == 0:  # we're in the forked process
                if gid is not None:  # GID change requested as well
                    os.setgid(gid)
                os.setuid(uid)  # set the UID for the code within the `with` block
                func(*args, **kwargs)  # execute the function
                os._exit(0)  # exit the child process
        return wrapped
    return wrapper

def test1():
    print("Current UID: {}".format(os.getuid()))  # prints the UID of the executing user

@as_unix_user(105)
def test2():
    print("Current UID: {}".format(os.getuid()))  # prints the UID of the executing user

test1()  # executes as the current user
test2()  # executes as the user with UID: 105

The kicker here? You don't get the return data from the forked function. If you need it, you'll have to pipe it back to the parent process and then wait in the parent for it to finish. You'll also need to choose a format to pass the data between processes (if simple enough, I'd recommend JSON or resort back to native pickle)...

At that point, you're already doing half of what the subprocess module is doing so you might as well just launch your function as a subprocess and be done with it. If you have to go through such hoops to achieve your desired result, chances are your original design is at fault. In your case - why not just provide the permissions to the current user to access the DB? The user will need to have the capabilities to switch to another user who can so you're not gaining anything in terms of security from it - you're only complicating your life.

4
  • Thanks for the detailed information. I tried with os.setreuid(user_id, user_id) but when we just change the user id it doesn't take effect of the environment variables of that user. I think its better to split the script into multiple scripts and run them through subprocess using su -.
    – Karthi1234
    Commented Jul 24, 2018 at 15:49
  • Next to not being thread-safe - why is it not thread safe? I mean, there is no shared variable under usage in your example so no risk of inconsistent data imo. Could you please justify your statement? Commented Jun 13, 2022 at 18:28
  • @renatodamas - it's not thread-safe in general, the example is there just to show usage. If you tried to switch UID/GID on a threaded function it will fail as switching essentially does soft-fork so you lose shared memory in the process.
    – zwer
    Commented Jul 14, 2022 at 20:04
  • ah right ! Bcs uid/gid is a property of the process, not the thread. Then I guess an alternative to your forking approach would be to implement a mechanism (like mutex) to prevent race conditions for portions that are meant to run atomically Commented Jul 14, 2022 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.