setuser 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/python3
  2. '''
  3. Copyright (c) 2013-2015 Phusion Holding B.V.
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. '''
  20. import sys
  21. import os
  22. import pwd
  23. def abort(message):
  24. sys.stderr.write("setuser: %s\n" % message)
  25. sys.exit(1)
  26. def main():
  27. '''
  28. A simple alternative to sudo that executes a command as a user by setting
  29. the user ID and user parameters to those described by the system and then
  30. using execvp(3) to execute the command without the necessity of a TTY
  31. '''
  32. username = sys.argv[1]
  33. try:
  34. user = pwd.getpwnam(username)
  35. except KeyError:
  36. abort("user %s not found" % username)
  37. os.initgroups(username, user.pw_gid)
  38. os.setgid(user.pw_gid)
  39. os.setuid(user.pw_uid)
  40. os.environ['USER'] = username
  41. os.environ['HOME'] = user.pw_dir
  42. os.environ['UID'] = str(user.pw_uid)
  43. try:
  44. os.execvp(sys.argv[2], sys.argv[2:])
  45. except OSError as e:
  46. abort("cannot execute %s: %s" % (sys.argv[2], str(e)))
  47. if __name__ == '__main__':
  48. if len(sys.argv) < 3:
  49. sys.stderr.write("Usage: /sbin/setuser USERNAME COMMAND [args..]\n")
  50. sys.exit(1)
  51. main()