Skip to content

Instantly share code, notes, and snippets.

@Jasata
Created December 17, 2019 11:05
Show Gist options
  • Save Jasata/8b1a8eb3457c2a4918d4d8a36e42bce5 to your computer and use it in GitHub Desktop.
Save Jasata/8b1a8eb3457c2a4918d4d8a36e42bce5 to your computer and use it in GitHub Desktop.
Convenient short term user change
#! /usr/bin/env python3
#
# with_identity.py - Jani Tammi <[email protected]>
#
# Convenient way to assume another user identity for limited work.
# Created for installation scripts that run as root.
#
import os
import pwd
import grp
class Identity():
def __init__(self, user: str, group: str = None):
self.uid = pwd.getpwnam(user).pw_uid
if not group:
self.gid = pwd.getpwnam(user).pw_gid
else:
self.gid = grp.getgrnam(group).gr_gid
def __enter__(self):
self.original_uid = os.getuid()
self.original_gid = os.getgid()
os.setegid(self.uid)
os.seteuid(self.gid)
def __exit__(self, type, value, traceback):
os.seteuid(self.original_uid)
os.setegid(self.original_gid)
if __name__ == '__main__':
with Identity('pi', 'www-data'):
with open("/var/www/hello.html", "w") as f:
f.write("<html><body>Hello World!</body></html>")
# 'with' context ends, effecive user and group are restored
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment